MDL-25276 dml - fix/implement sql_cast2int/real() across the 5 drivers. Tests passing.
[moodle.git] / lib / dml / sqlsrv_native_moodle_database.php
CommitLineData
0c57c867 1<?php
2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 2 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
18/**
f2ed3f05
PS
19 * Native sqlsrv class representing moodle database interface.
20 *
66c0ee78 21 * @package core
f2ed3f05
PS
22 * @subpackage dml
23 * @copyright 2009 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v2 or later
25 */
26
27defined('MOODLE_INTERNAL') || die();
0c57c867 28
29require_once($CFG->libdir.'/dml/moodle_database.php');
30require_once($CFG->libdir.'/dml/sqlsrv_native_moodle_recordset.php');
31require_once($CFG->libdir.'/dml/sqlsrv_native_moodle_temptables.php');
32
33/**
2740cea0
PS
34 * Native sqlsrv class representing moodle database interface.
35 */
0c57c867 36class sqlsrv_native_moodle_database extends moodle_database {
37
38 protected $sqlsrv = null;
39 protected $last_error_reporting; // To handle SQL*Server-Native driver default verbosity
40 protected $temptables; // Control existing temptables (sqlsrv_moodle_temptables object)
6055f89d 41 protected $collation; // current DB collation cache
0c57c867 42
43 /**
2740cea0 44 * Constructor - instantiates the database, specifying if it's external (connect to other systems) or no (Moodle DB)
0c57c867 45 * note this has effect to decide if prefix checks must be performed or no
46 * @param bool true means external database used
47 */
48 public function __construct($external=false) {
49 parent::__construct($external);
50 }
51
2740cea0
PS
52 /**
53 * Detects if all needed PHP stuff installed.
54 * Note: can be used before connect()
55 * @return mixed true if ok, string if something
56 */
0c57c867 57 public function driver_installed() {
58 // use 'function_exists()' rather than 'extension_loaded()' because
f2ed3f05
PS
59 // the name used by 'extension_loaded()' is case specific! The extension
60 // therefore *could be* mixed case and hence not found.
0c57c867 61 if (!function_exists('sqlsrv_num_rows')) {
62 return get_string('sqlsrvextensionisnotpresentinphp', 'install');
63 }
64 return true;
65 }
66
67 /**
2740cea0
PS
68 * Returns database family type - describes SQL dialect
69 * Note: can be used before connect()
70 * @return string db family name (mysql, postgres, mssql, sqlsrv, oracle, etc.)
71 */
0c57c867 72 public function get_dbfamily() {
0c57c867 73 return 'mssql';
74 }
75
2740cea0
PS
76 /**
77 * Returns more specific database driver type
78 * Note: can be used before connect()
4a6c2ab8 79 * @return string db type mysqli, pgsql, oci, mssql, sqlsrv
2740cea0 80 */
0c57c867 81 protected function get_dbtype() {
82 return 'sqlsrv';
83 }
84
2740cea0
PS
85 /**
86 * Returns general database library name
87 * Note: can be used before connect()
88 * @return string db type pdo, native
89 */
0c57c867 90 protected function get_dblibrary() {
91 return 'native';
92 }
93
94 /**
2740cea0
PS
95 * Returns localised database type name
96 * Note: can be used before connect()
97 * @return string
98 */
0c57c867 99 public function get_name() {
100 return get_string('nativesqlsrv', 'install');
101 }
102
103 /**
2740cea0
PS
104 * Returns localised database configuration help.
105 * Note: can be used before connect()
106 * @return string
107 */
0c57c867 108 public function get_configuration_help() {
109 return get_string('nativesqlsrvhelp', 'install');
110 }
111
112 /**
2740cea0
PS
113 * Returns localised database description
114 * Note: can be used before connect()
115 * @return string
116 */
0c57c867 117 public function get_configuration_hints() {
118 $str = get_string('databasesettingssub_sqlsrv', 'install');
119 $str .= "<p style='text-align:right'><a href=\"javascript:void(0)\" ";
120 $str .= "onclick=\"return window.open('http://docs.moodle.org/en/Installing_sqlsrv_for_PHP')\"";
121 $str .= ">";
122 $str .= '<img src="pix/docs.gif'.'" alt="Docs" class="iconhelp" />';
123 $str .= get_string('moodledocslink', 'install').'</a></p>';
124 return $str;
125 }
126
127 /**
2740cea0
PS
128 * Connect to db
129 * Must be called before other methods.
130 * @param string $dbhost
131 * @param string $dbuser
132 * @param string $dbpass
133 * @param string $dbname
134 * @param mixed $prefix string means moodle db prefix, false used for external databases where prefix not used
135 * @param array $dboptions driver specific options
136 * @return bool true
137 * @throws dml_connection_exception if error
138 */
0c57c867 139 public function connect($dbhost, $dbuser, $dbpass, $dbname, $prefix, array $dboptions=null) {
140 $driverstatus = $this->driver_installed();
141
142 if ($driverstatus !== true) {
143 throw new dml_exception('dbdriverproblem', $driverstatus);
144 }
145
146 /*
2740cea0
PS
147 * Log all Errors.
148 */
0c57c867 149 sqlsrv_configure("WarningsReturnAsErrors", FALSE);
150 sqlsrv_configure("LogSubsystems", SQLSRV_LOG_SYSTEM_ALL);
151 sqlsrv_configure("LogSeverity", SQLSRV_LOG_SEVERITY_ERROR);
152
153 $this->store_settings($dbhost, $dbuser, $dbpass, $dbname, $prefix, $dboptions);
154 $this->sqlsrv = sqlsrv_connect($this->dbhost, array
155 (
156 'UID' => $this->dbuser,
157 'PWD' => $this->dbpass,
158 'Database' => $this->dbname,
159 'CharacterSet' => 'UTF-8',
160 'MultipleActiveResultSets' => true,
5585eab3 161 'ConnectionPooling' => !empty($this->dboptions['dbpersist']),
0c57c867 162 'ReturnDatesAsStrings' => true,
163 ));
164
165 if ($this->sqlsrv === false) {
166 $this->sqlsrv = null;
167 $dberr = $this->get_last_error();
168
169 throw new dml_connection_exception($dberr);
170 }
171
172 // Allow quoted identifiers
173 $sql = "SET QUOTED_IDENTIFIER ON";
174 $this->query_start($sql, null, SQL_QUERY_AUX);
175 $result = sqlsrv_query($this->sqlsrv, $sql);
176 $this->query_end($result);
177
178 $this->free_result($result);
179
180 // Force ANSI nulls so the NULL check was done by IS NULL and NOT IS NULL
181 // instead of equal(=) and distinct(<>) symbols
182 $sql = "SET ANSI_NULLS ON";
183 $this->query_start($sql, null, SQL_QUERY_AUX);
184 $result = sqlsrv_query($this->sqlsrv, $sql);
185 $this->query_end($result);
186
187 $this->free_result($result);
188
189 // Force ANSI warnings so arithmetic/string overflows will be
190 // returning error instead of transparently truncating data
191 $sql = "SET ANSI_WARNINGS ON";
192 $this->query_start($sql, null, SQL_QUERY_AUX);
193 $result = sqlsrv_query($this->sqlsrv, $sql);
194 $this->query_end($result);
195
196 // Concatenating null with anything MUST return NULL
197 $sql = "SET CONCAT_NULL_YIELDS_NULL ON";
198 $this->query_start($sql, null, SQL_QUERY_AUX);
199 $result = sqlsrv_query($this->sqlsrv, $sql);
200 $this->query_end($result);
201
202 $this->free_result($result);
203
204 // Set transactions isolation level to READ_COMMITTED
205 // prevents dirty reads when using transactions +
206 // is the default isolation level of sqlsrv
207 $sql = "SET TRANSACTION ISOLATION LEVEL READ COMMITTED";
208 $this->query_start($sql, NULL, SQL_QUERY_AUX);
209 $result = sqlsrv_query($this->sqlsrv, $sql);
210 $this->query_end($result);
211
212 $this->free_result($result);
213
214 // Connection established and configured, going to instantiate the temptables controller
215 $this->temptables = new sqlsrv_native_moodle_temptables($this);
216
217 return true;
218 }
219
220 /**
2740cea0
PS
221 * Close database connection and release all resources
222 * and memory (especially circular memory references).
223 * Do NOT use connect() again, create a new instance if needed.
224 */
0c57c867 225 public function dispose() {
226 parent::dispose(); // Call parent dispose to write/close session and other common stuff before closing connection
227
228 if ($this->sqlsrv) {
229 sqlsrv_close($this->sqlsrv);
230 $this->sqlsrv = null;
231 }
232 }
233
234 /**
2740cea0
PS
235 * Called before each db query.
236 * @param string $sql
237 * @param array array of parameters
238 * @param int $type type of query
239 * @param mixed $extrainfo driver specific extra information
240 * @return void
241 */
0c57c867 242 protected function query_start($sql, array $params = null, $type, $extrainfo = null) {
243 parent::query_start($sql, $params, $type, $extrainfo);
244 }
245
246 /**
2740cea0
PS
247 * Called immediately after each db query.
248 * @param mixed db specific result
249 * @return void
250 */
0c57c867 251 protected function query_end($result) {
252 parent::query_end($result);
253 }
254
255 /**
2740cea0
PS
256 * Returns database server info array
257 * @return array
258 */
0c57c867 259 public function get_server_info() {
260 static $info;
261
262 if (!$info) {
263 $server_info = sqlsrv_server_info($this->sqlsrv);
264
265 if ($server_info) {
b809f813 266 $info['description'] = $server_info['SQLServerName'];
0c57c867 267 $info['version'] = $server_info['SQLServerVersion'];
268 $info['database'] = $server_info['CurrentDatabase'];
269 }
270 }
271 return $info;
272 }
273
274 /**
2740cea0
PS
275 * Get the minimum SQL allowed
276 *
277 * @param mixed $version
278 * @return mixed
279 */
0c57c867 280 protected function is_min_version($version) {
281 $server = $this->get_server_info();
282 $server = $server['version'];
283 return version_compare($server, $version, '>=');
284 }
285
286 /**
2740cea0
PS
287 * Override: Converts short table name {tablename} to real table name
288 * supporting temp tables (#) if detected
289 *
290 * @param string sql
291 * @return string sql
292 */
0c57c867 293 protected function fix_table_names($sql) {
294 if (preg_match_all('/\{([a-z][a-z0-9_]*)\}/i', $sql, $matches)) {
295 foreach ($matches[0] as $key => $match) {
296 $name = $matches[1][$key];
297
298 if ($this->temptables->is_temptable($name)) {
299 $sql = str_replace($match, $this->temptables->get_correct_name($name), $sql);
300 } else {
301 $sql = str_replace($match, $this->prefix.$name, $sql);
302 }
303 }
304 }
305 return $sql;
306 }
307
308 /**
2740cea0 309 * Returns supported query parameter types
9331d879 310 * @return int bitmask
2740cea0 311 */
0c57c867 312 protected function allowed_param_types() {
313 return SQL_PARAMS_QM; // sqlsrv 1.1 can bind
314 }
315
316 /**
2740cea0 317 * Returns last error reported by database engine.
9331d879 318 * @return string error message
2740cea0 319 */
0c57c867 320 public function get_last_error() {
321 $retErrors = sqlsrv_errors(SQLSRV_ERR_ALL);
322 $errorMessage = 'No errors found';
323
324 if ($retErrors != null) {
325 $errorMessage = '';
326
327 foreach ($retErrors as $arrError) {
328 $errorMessage .= "SQLState: ".$arrError['SQLSTATE']."<br>\n";
329 $errorMessage .= "Error Code: ".$arrError['code']."<br>\n";
330 $errorMessage .= "Message: ".$arrError['message']."<br>\n";
331 }
332 }
333
334 return $errorMessage;
335 }
336
337 /***
2740cea0
PS
338 * Bound variables *are* supported. Until I can get it to work, emulate the bindings
339 * The challenge/problem/bug is that although they work, doing a SELECT SCOPE_IDENTITY()
340 * doesn't return a value (no result set)
341 */
0c57c867 342
343 /**
2740cea0
PS
344 * Prepare the query binding and do the actual query.
345 *
346 * @param string $sql The sql statement
347 * @param mixed $params array of params for binding. If NULL, they are ignored.
348 * @param mixed $sql_query_type - Type of operation
349 * @param mixed $free_result - Default true, transaction query will be freed.
350 */
0c57c867 351 private function do_query($sql, $params, $sql_query_type, $free_result = true) {
352 list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
353
354 $sql = $this->emulate_bound_params($sql, $params);
355 $this->query_start($sql, $params, $sql_query_type);
356 $result = sqlsrv_query($this->sqlsrv, $sql);
357
358 if ($result === false) {
359 // TODO do something with error or just use if DEV or DEBUG?
360 $dberr = $this->get_last_error();
361 }
362
363 $this->query_end($result);
364
365 if ($free_result) {
366 $this->free_result($result);
367 return true;
368 }
369 return $result;
370 }
371
372 /**
2740cea0
PS
373 * Return tables in database WITHOUT current prefix
374 * @return array of table names in lowercase and without prefix
375 */
0c57c867 376 public function get_tables($usecache = true) {
377 if ($usecache and count($this->tables) > 0) {
378 return $this->tables;
379 }
380 $this->tables = array ();
b4833117 381 $prefix = str_replace('_', '\\_', $this->prefix);
30e7e9e4
PS
382 $sql = "SELECT table_name
383 FROM information_schema.tables
a4411e56 384 WHERE table_name LIKE '$prefix%' ESCAPE '\\' AND table_type = 'BASE TABLE'";
0c57c867 385
386 $this->query_start($sql, null, SQL_QUERY_AUX);
387 $result = sqlsrv_query($this->sqlsrv, $sql);
388 $this->query_end($result);
389
390 if ($result) {
391 while ($row = sqlsrv_fetch_array($result)) {
392 $tablename = reset($row);
393 if (strpos($tablename, $this->prefix) !== 0) {
394 continue;
395 }
396 $tablename = substr($tablename, strlen($this->prefix));
397 $this->tables[$tablename] = $tablename;
398 }
399 $this->free_result($result);
400 }
401
402 // Add the currently available temptables
403 $this->tables = array_merge($this->tables, $this->temptables->get_temptables());
404 return $this->tables;
405 }
406
407 /**
2740cea0
PS
408 * Return table indexes - everything lowercased
409 * @return array of arrays
410 */
0c57c867 411 public function get_indexes($table) {
412 $indexes = array ();
413 $tablename = $this->prefix.$table;
414
415 // Indexes aren't covered by information_schema metatables, so we need to
416 // go to sys ones. Skipping primary key indexes on purpose.
417 $sql = "SELECT i.name AS index_name, i.is_unique, ic.index_column_id, c.name AS column_name
30e7e9e4
PS
418 FROM sys.indexes i
419 JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
420 JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
421 JOIN sys.tables t ON i.object_id = t.object_id
422 WHERE t.name = '$tablename' AND i.is_primary_key = 0
423 ORDER BY i.name, i.index_id, ic.index_column_id";
0c57c867 424
425 $this->query_start($sql, null, SQL_QUERY_AUX);
426 $result = sqlsrv_query($this->sqlsrv, $sql);
427 $this->query_end($result);
428
429 if ($result) {
430 $lastindex = '';
431 $unique = false;
432 $columns = array ();
433
434 while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
435 if ($lastindex and $lastindex != $row['index_name'])
436 { // Save lastindex to $indexes and reset info
437 $indexes[$lastindex] = array
438 (
439 'unique' => $unique,
440 'columns' => $columns
441 );
442
443 $unique = false;
444 $columns = array ();
445 }
446 $lastindex = $row['index_name'];
447 $unique = empty($row['is_unique']) ? false : true;
448 $columns[] = $row['column_name'];
449 }
450
451 if ($lastindex) { // Add the last one if exists
452 $indexes[$lastindex] = array
453 (
454 'unique' => $unique,
455 'columns' => $columns
456 );
457 }
458
459 $this->free_result($result);
460 }
461 return $indexes;
462 }
463
464 /**
2740cea0
PS
465 * Returns detailed information about columns in table. This information is cached internally.
466 * @param string $table name
467 * @param bool $usecache
468 * @return array array of database_column_info objects indexed with column names
469 */
0c57c867 470 public function get_columns($table, $usecache = true) {
471 if ($usecache and isset($this->columns[$table])) {
472 return $this->columns[$table];
473 }
474
475 $this->columns[$table] = array ();
476
477 if (!$this->temptables->is_temptable($table)) { // normal table, get metadata from own schema
478 $sql = "SELECT column_name AS name,
30e7e9e4
PS
479 data_type AS type,
480 numeric_precision AS max_length,
481 character_maximum_length AS char_max_length,
482 numeric_scale AS scale,
483 is_nullable AS is_nullable,
484 columnproperty(object_id(quotename(table_schema) + '.' + quotename(table_name)), column_name, 'IsIdentity') AS auto_increment,
485 column_default AS default_value
486 FROM information_schema.columns
487 WHERE table_name = '{".$table."}'
488 ORDER BY ordinal_position";
0c57c867 489 } else { // temp table, get metadata from tempdb schema
490 $sql = "SELECT column_name AS name,
30e7e9e4
PS
491 data_type AS type,
492 numeric_precision AS max_length,
493 character_maximum_length AS char_max_length,
494 numeric_scale AS scale,
495 is_nullable AS is_nullable,
496 columnproperty(object_id(quotename(table_schema) + '.' + quotename(table_name)), column_name, 'IsIdentity') AS auto_increment,
497 column_default AS default_value
498 FROM tempdb.information_schema.columns ".
0c57c867 499 // check this statement
500 // JOIN tempdb..sysobjects ON name = table_name
501 // WHERE id = object_id('tempdb..{".$table."}')
30e7e9e4
PS
502 "WHERE table_name LIKE '{".$table."}__________%'
503 ORDER BY ordinal_position";
0c57c867 504 }
505
506 list($sql, $params, $type) = $this->fix_sql_params($sql, null);
507
508 $this->query_start($sql, null, SQL_QUERY_AUX);
509 $result = sqlsrv_query($this->sqlsrv, $sql);
510 $this->query_end($result);
511
512 if (!$result) {
513 return array ();
514 }
515
516 while ($rawcolumn = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
517
518 $rawcolumn = (object)$rawcolumn;
519
ac6f1a82 520 $info = new stdClass();
0c57c867 521 $info->name = $rawcolumn->name;
522 $info->type = $rawcolumn->type;
523 $info->meta_type = $this->sqlsrvtype2moodletype($info->type);
524
525 // Prepare auto_increment info
526 $info->auto_increment = $rawcolumn->auto_increment ? true : false;
527
528 // Define type for auto_increment columns
529 $info->meta_type = ($info->auto_increment && $info->meta_type == 'I') ? 'R' : $info->meta_type;
530
531 // id columns being auto_incremnt are PK by definition
532 $info->primary_key = ($info->name == 'id' && $info->meta_type == 'R' && $info->auto_increment);
533
534 // Put correct length for character and LOB types
535 $info->max_length = $info->meta_type == 'C' ? $rawcolumn->char_max_length : $rawcolumn->max_length;
536 $info->max_length = ($info->meta_type == 'X' || $info->meta_type == 'B') ? -1 : $info->max_length;
537
538 // Scale
539 $info->scale = $rawcolumn->scale ? $rawcolumn->scale : false;
540
541 // Prepare not_null info
542 $info->not_null = $rawcolumn->is_nullable == 'NO' ? true : false;
543
544 // Process defaults
545 $info->has_default = !empty($rawcolumn->default_value);
fd31089c
PS
546 if ($rawcolumn->default_value === NULL) {
547 $info->default_value = NULL;
548 } else {
549 $info->default_value = preg_replace("/^[\(N]+[']?(.*?)[']?[\)]+$/", '\\1', $rawcolumn->default_value);
550 }
0c57c867 551
552 // Process binary
553 $info->binary = $info->meta_type == 'B' ? true : false;
554
555 $this->columns[$table][$info->name] = new database_column_info($info);
556 }
557 $this->free_result($result);
558
559 return $this->columns[$table];
560 }
561
562 /**
2740cea0
PS
563 * Normalise values based in RDBMS dependencies (booleans, LOBs...)
564 *
565 * @param database_column_info $column column metadata corresponding with the value we are going to normalise
566 * @param mixed $value value we are going to normalise
567 * @return mixed the normalised value
568 */
0c57c867 569 protected function normalise_value($column, $value) {
570 if (is_bool($value)) { /// Always, convert boolean to int
571 $value = (int)$value;
572 } // And continue processing because text columns with numeric info need special handling below
573
574 if ($column->meta_type == 'B')
575 { // BLOBs need to be properly "packed", but can be inserted directly if so.
576 if (!is_null($value)) { // If value not null, unpack it to unquoted hexadecimal byte-string format
577 $value = unpack('H*hex', $value); // we leave it as array, so emulate_bound_params() can detect it
578 } // easily and "bind" the param ok.
579
580 } else if ($column->meta_type == 'X') { // sqlsrv doesn't cast from int to text, so if text column
581 if (is_numeric($value)) { // and is numeric value then cast to string
582 $value = array('numstr' => (string)$value); // and put into array, so emulate_bound_params() will know how
583 } // to "bind" the param ok, avoiding reverse conversion to number
584 } else if ($value === '') {
585
586 if ($column->meta_type == 'I' or $column->meta_type == 'F' or $column->meta_type == 'N') {
587 $value = 0; // prevent '' problems in numeric fields
588 }
589 }
590 return $value;
591 }
592
593 /**
2740cea0
PS
594 * Selectively call sqlsrv_free_stmt(), avoiding some warnings without using the horrible @
595 *
596 * @param sqlsrv_resource $resource resource to be freed if possible
597 */
0c57c867 598 private function free_result($resource) {
599 if (!is_bool($resource)) { // true/false resources cannot be freed
600 return sqlsrv_free_stmt($resource);
601 }
602 }
603
604 /**
2740cea0
PS
605 * Provides mapping between sqlsrv native data types and moodle_database - database_column_info - ones)
606 *
607 * @param string $sqlsrv_type native sqlsrv data type
608 * @return string 1-char database_column_info data type
609 */
0c57c867 610 private function sqlsrvtype2moodletype($sqlsrv_type) {
611 $type = null;
612
613 switch (strtoupper($sqlsrv_type)) {
614 case 'BIT':
615 $type = 'L';
616 break;
617
618 case 'INT':
619 case 'SMALLINT':
620 case 'INTEGER':
621 case 'BIGINT':
622 $type = 'I';
623 break;
624
625 case 'DECIMAL':
626 case 'REAL':
627 case 'FLOAT':
628 $type = 'N';
629 break;
630
631 case 'VARCHAR':
632 case 'NVARCHAR':
633 $type = 'C';
634 break;
635
636 case 'TEXT':
637 case 'NTEXT':
638 case 'VARCHAR(MAX)':
639 case 'NVARCHAR(MAX)':
640 $type = 'X';
641 break;
642
643 case 'IMAGE':
644 case 'VARBINARY(MAX)':
645 $type = 'B';
646 break;
647
648 case 'DATETIME':
649 $type = 'D';
650 break;
651 }
652
653 if (!$type) {
654 throw new dml_exception('invalidsqlsrvnativetype', $sqlsrv_type);
655 }
656 return $type;
657 }
658
659 /**
2740cea0
PS
660 * Do NOT use in code, to be used by database_manager only!
661 * @param string $sql query
662 * @return bool true
663 * @throws dml_exception if error
664 */
0c57c867 665 public function change_database_structure($sql) {
666 $this->reset_caches();
667
668 $this->query_start($sql, null, SQL_QUERY_STRUCTURE);
669 $result = sqlsrv_query($this->sqlsrv, $sql);
670 $this->query_end($result);
671
672 return true;
673 }
674
675 /**
2740cea0
PS
676 * Prepare the array of params for native binding
677 */
0c57c867 678 protected function build_native_bound_params(array $params = null) {
679
680 return null;
681 }
682
683
684 /**
2740cea0
PS
685 * Workaround for SQL*Server Native driver similar to MSSQL driver for
686 * consistent behavior.
687 */
0c57c867 688 protected function emulate_bound_params($sql, array $params = null) {
689
690 if (empty($params)) {
691 return $sql;
692 }
693 /// ok, we have verified sql statement with ? and correct number of params
694 $return = strtok($sql, '?');
695
696 foreach ($params as $param) {
697 if (is_bool($param)) {
698 $return .= (int)$param;
699 } else if (is_array($param) && isset($param['hex'])) { // detect hex binary, bind it specially
700 $return .= '0x'.$param['hex'];
701 } else if (is_array($param) && isset($param['numstr'])) { // detect numerical strings that *must not*
702 $return .= "N'{$param['numstr']}'"; // be converted back to number params, but bound as strings
703 } else if (is_null($param)) {
704 $return .= 'NULL';
705
6055f89d 706 } else if (is_number($param)) { // we can not use is_numeric() because it eats leading zeros from strings like 0045646
7d8f881a 707 $return .= "'$param'"; // this is a hack for MDL-23997, we intentionally use string because it is compatible with both nvarchar and int types
0c57c867 708 } else if (is_float($param)) {
709 $return .= $param;
710 } else {
711 $param = str_replace("'", "''", $param);
712 $return .= "N'$param'";
713 }
714
715 $return .= strtok('?');
716 }
717 return $return;
718 }
719
0c57c867 720 /**
2740cea0
PS
721 * Execute general sql query. Should be used only when no other method suitable.
722 * Do NOT use this to make changes in db structure, use database_manager::execute_sql() instead!
723 * @param string $sql query
724 * @param array $params query parameters
725 * @return bool true
726 * @throws dml_exception if error
727 */
0c57c867 728 public function execute($sql, array $params = null) {
729 if (strpos($sql, ';') !== false) {
730 throw new coding_exception('moodle_database::execute() Multiple sql statements found or bound parameters not used properly in query!');
731 }
732 $this->do_query($sql, $params, SQL_QUERY_UPDATE);
733 return true;
734 }
735
736 /**
2740cea0
PS
737 * Get a number of records as a moodle_recordset using a SQL statement.
738 *
739 * Since this method is a little less readable, use of it should be restricted to
740 * code where it's possible there might be large datasets being returned. For known
741 * small datasets use get_records_sql - it leads to simpler code.
742 *
743 * The return type is as for @see function get_recordset.
744 *
745 * @param string $sql the SQL select query to execute.
746 * @param array $params array of sql parameters
747 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
748 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
5212b07f 749 * @return moodle_recordset instance
2740cea0
PS
750 * @throws dml_exception if error
751 */
0c57c867 752 public function get_recordset_sql($sql, array $params = null, $limitfrom = 0, $limitnum = 0) {
753 $limitfrom = (int)$limitfrom;
754 $limitnum = (int)$limitnum;
755 $limitfrom = max(0, $limitfrom);
756 $limitnum = max(0, $limitnum);
757
758 if ($limitfrom or $limitnum) {
759 $sql = $this->limit_to_top_n($sql, $limitfrom, $limitnum);
760 }
761 $result = $this->do_query($sql, $params, SQL_QUERY_SELECT, false);
762 return $this->create_recordset($result);
763 }
764
765 /**
2740cea0
PS
766 * Perform a emulation for LIMIT(offset, limit)
767 *
30e7e9e4
PS
768 * @param string $sql
769 * @param int $offset
770 * @param int $limit
771 * @return string sql
2740cea0 772 */
0c57c867 773 private function limit_to_top_n($sql, $offset, $limit) {
774 if ($limit < 1 && $offset < 1) {
775 return $sql;
776 }
777 $limit = max(0, $limit);
778 $offset = max(0, $offset);
779
780 if ($limit > 0 && $offset == 0) {
3a55ee2f
EL
781 $sql1 = preg_replace('/^([\s(])*SELECT([\s]+)(DISTINCT|ALL)?(?!\s*TOP\s*\()/i',
782 "\\1SELECT\\2\\3 TOP $limit", $sql);
0c57c867 783 } else {
f2ed3f05 784 // Only apply TOP clause if we have any limitnum (limitfrom offset is handled later)
0c57c867 785 if ($limit < 1) {
786 $limit = "9223372036854775806"; // MAX BIGINT -1
787 }
788 if (preg_match('/\w*FROM[\s|{]*([\w|.]*)[\s|}]?/i', $sql, $match)) {
789 $from_table = $match[1];
790 if (preg_match('/SELECT[\w|\s]*(\*)[\w|\s]*FROM/i', $sql)) {
791 // Need all the columns as the emulation returns some temp cols
792 $cols = array_keys($this->get_columns($from_table));
793 $cols = implode(', ', $cols);
794 } else {
795 $cols = '*';
796 }
30e7e9e4
PS
797 $sql1 = "SELECT $cols
798 FROM (SELECT sub2.*, ROW_NUMBER() OVER(ORDER BY sub2.line2) AS line3
799 FROM (SELECT 1 AS line2, sub1.*
800 FROM {".$from_table."} AS sub1
801 ) AS sub2
802 ) AS sub3
803 WHERE line3 BETWEEN ".($offset+1)." AND ".($offset + $limit);
0c57c867 804 } else {
805 $sql1 = "SELECT 'Invalid table'";
806 }
807 }
808
809 return $sql1;
810 }
811
812 /**
2740cea0
PS
813 * Create a record set and initialize with first row
814 *
815 * @param mixed $result
816 * @return sqlsrv_native_moodle_recordset
817 */
0c57c867 818 protected function create_recordset($result) {
819 return new sqlsrv_native_moodle_recordset($result);
820 }
821
822 /**
2740cea0
PS
823 * Get a number of records as an array of objects using a SQL statement.
824 *
825 * Return value as for @see function get_records.
826 *
827 * @param string $sql the SQL select query to execute. The first column of this SELECT statement
828 * must be a unique value (usually the 'id' field), as it will be used as the key of the
829 * returned array.
830 * @param array $params array of sql parameters
831 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
832 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
3503dcad 833 * @return array of objects, or empty array if no records were found
2740cea0
PS
834 * @throws dml_exception if error
835 */
0c57c867 836 public function get_records_sql($sql, array $params = null, $limitfrom = 0, $limitnum = 0) {
837
838 $rs = $this->get_recordset_sql($sql, $params, $limitfrom, $limitnum);
839
840 $results = array();
841
842 foreach ($rs as $row) {
843 $id = reset($row);
844
40504474 845 if (isset($results[$id])) {
0c57c867 846 $colname = key($row);
847 debugging("Did you remember to make the first column something unique in your call to get_records? Duplicate value '$id' found in column '$colname'.", DEBUG_DEVELOPER);
848 }
849 $results[$id] = (object)$row;
850 }
851 $rs->close();
852
853 return $results;
854 }
855
856 /**
2740cea0
PS
857 * Selects records and return values (first field) as an array using a SQL statement.
858 *
859 * @param string $sql The SQL query
860 * @param array $params array of sql parameters
3503dcad 861 * @return array of values
2740cea0
PS
862 * @throws dml_exception if error
863 */
0c57c867 864 public function get_fieldset_sql($sql, array $params = null) {
865
866 $rs = $this->get_recordset_sql($sql, $params);
867
868 $results = array ();
869
870 foreach ($rs as $row) {
871 $results[] = reset($row);
872 }
873 $rs->close();
874
875 return $results;
876 }
877
878 /**
2740cea0
PS
879 * Insert new record into database, as fast as possible, no safety checks, lobs not supported.
880 * @param string $table name
881 * @param mixed $params data record as object or array
882 * @param bool $returnit return it of inserted record
883 * @param bool $bulk true means repeated inserts expected
884 * @param bool $customsequence true if 'id' included in $params, disables $returnid
3503dcad 885 * @return bool|int true or new id
2740cea0
PS
886 * @throws dml_exception if error
887 */
0c57c867 888 public function insert_record_raw($table, $params, $returnid=true, $bulk=false, $customsequence=false) {
889 if (!is_array($params)) {
890 $params = (array)$params;
891 }
892 if ($customsequence) {
893 if (!isset($params['id'])) {
894 throw new coding_exception('moodle_database::insert_record_raw() id field must be specified if custom sequences used.');
895 }
896 $returnid = false;
5c8efdc4
PS
897 // Disable IDENTITY column before inserting record with id
898 $sql = 'SET IDENTITY_INSERT {'.$table.'} ON'; // Yes, it' ON!!
899 $this->do_query($sql, null, SQL_QUERY_AUX);
900
0c57c867 901 } else {
902 unset($params['id']);
903 }
904
905 if (empty($params)) {
906 throw new coding_exception('moodle_database::insert_record_raw() no fields found.');
907 }
908 $fields = implode(',', array_keys($params));
909 $qms = array_fill(0, count($params), '?');
910 $qms = implode(',', $qms);
911 $sql = "INSERT INTO {" . $table . "} ($fields) VALUES($qms)";
912 $query_id = $this->do_query($sql, $params, SQL_QUERY_INSERT);
5c8efdc4
PS
913
914 if ($customsequence) {
915 // Enable IDENTITY column after inserting record with id
916 $sql = 'SET IDENTITY_INSERT {'.$table.'} OFF'; // Yes, it' OFF!!
917 $this->do_query($sql, null, SQL_QUERY_AUX);
918 }
919
0c57c867 920 if ($returnid) {
921 $id = $this->sqlsrv_fetch_id();
922 return $id;
923 } else {
924 return true;
925 }
926 }
927
928 /**
2740cea0
PS
929 * Get the ID of the current action
930 *
931 * @return mixed ID
932 */
0c57c867 933 private function sqlsrv_fetch_id() {
934 $query_id = sqlsrv_query($this->sqlsrv, 'SELECT SCOPE_IDENTITY()');
935 if ($query_id === false) {
936 $dberr = $this->get_last_error();
937 return false;
938 }
939 $row = $this->sqlsrv_fetchrow($query_id);
940 return (int)$row[0];
941 }
942
943 /**
2740cea0
PS
944 * Fetch a single row into an numbered array
945 *
946 * @param mixed $query_id
947 */
0c57c867 948 private function sqlsrv_fetchrow($query_id) {
949 $row = sqlsrv_fetch_array($query_id, SQLSRV_FETCH_NUMERIC);
950 if ($row === false) {
951 $dberr = $this->get_last_error();
952 return false;
953 }
954
955 foreach ($row as $key => $value) {
956 $row[$key] = ($value === ' ' || $value === NULL) ? '' : $value;
957 }
958 return $row;
959 }
960
961 /**
2740cea0
PS
962 * Insert a record into a table and return the "id" field if required.
963 *
964 * Some conversions and safety checks are carried out. Lobs are supported.
965 * If the return ID isn't required, then this just reports success as true/false.
966 * $data is an object containing needed data
967 * @param string $table The database table to be inserted into
968 * @param object $data A data object with values for one or more fields in the record
969 * @param bool $returnid Should the id of the newly created record entry be returned? If this option is not requested then true/false is returned.
3503dcad 970 * @return bool|int true or new id
2740cea0
PS
971 * @throws dml_exception if error
972 */
0c57c867 973 public function insert_record($table, $dataobject, $returnid = true, $bulk = false) {
d8fa8e40 974 $dataobject = (array)$dataobject;
0c57c867 975
976 $columns = $this->get_columns($table);
977 $cleaned = array ();
978
979 foreach ($dataobject as $field => $value) {
d8fa8e40
PS
980 if ($field === 'id') {
981 continue;
982 }
0c57c867 983 if (!isset($columns[$field])) {
984 continue;
985 }
986 $column = $columns[$field];
987 $cleaned[$field] = $this->normalise_value($column, $value);
988 }
989
990 return $this->insert_record_raw($table, $cleaned, $returnid, $bulk);
991 }
992
993 /**
2740cea0
PS
994 * Import a record into a table, id field is required.
995 * Safety checks are NOT carried out. Lobs are supported.
996 *
997 * @param string $table name of database table to be inserted into
998 * @param object $dataobject A data object with values for one or more fields in the record
999 * @return bool true
1000 * @throws dml_exception if error
1001 */
0c57c867 1002 public function import_record($table, $dataobject) {
1003 if (!is_object($dataobject)) {
1004 $dataobject = (object)$dataobject;
1005 }
1006
1007 $columns = $this->get_columns($table);
1008 $cleaned = array ();
1009
1010 foreach ($dataobject as $field => $value) {
1011 if (!isset($columns[$field])) {
1012 continue;
1013 }
1014 $column = $columns[$field];
1015 $cleaned[$field] = $this->normalise_value($column, $value);
1016 }
1017
5c8efdc4 1018 $this->insert_record_raw($table, $cleaned, false, false, true);
0c57c867 1019
5c8efdc4 1020 return true;
0c57c867 1021 }
1022
1023 /**
2740cea0
PS
1024 * Update record in database, as fast as possible, no safety checks, lobs not supported.
1025 * @param string $table name
1026 * @param mixed $params data record as object or array
1027 * @param bool true means repeated updates expected
1028 * @return bool true
1029 * @throws dml_exception if error
1030 */
0c57c867 1031 public function update_record_raw($table, $params, $bulk = false) {
d8fa8e40 1032 $params = (array)$params;
0c57c867 1033
1034 if (!isset($params['id'])) {
1035 throw new coding_exception('moodle_database::update_record_raw() id field must be specified.');
1036 }
1037 $id = $params['id'];
1038 unset($params['id']);
1039
1040 if (empty($params)) {
1041 throw new coding_exception('moodle_database::update_record_raw() no fields found.');
1042 }
1043
1044 $sets = array ();
1045
1046 foreach ($params as $field => $value) {
1047 $sets[] = "$field = ?";
1048 }
1049
1050 $params[] = $id; // last ? in WHERE condition
1051
1052 $sets = implode(',', $sets);
1053 $sql = "UPDATE {".$table."} SET $sets WHERE id = ?";
1054
1055 $this->do_query($sql, $params, SQL_QUERY_UPDATE);
1056
1057 return true;
1058 }
1059
1060 /**
2740cea0
PS
1061 * Update a record in a table
1062 *
1063 * $dataobject is an object containing needed data
1064 * Relies on $dataobject having a variable "id" to
1065 * specify the record to update
1066 *
1067 * @param string $table The database table to be checked against.
1068 * @param object $dataobject An object with contents equal to fieldname=>fieldvalue. Must have an entry for 'id' to map to the table specified.
1069 * @param bool true means repeated updates expected
1070 * @return bool true
1071 * @throws dml_exception if error
1072 */
0c57c867 1073 public function update_record($table, $dataobject, $bulk = false) {
d8fa8e40 1074 $dataobject = (array)$dataobject;
0c57c867 1075
1076 $columns = $this->get_columns($table);
1077 $cleaned = array ();
1078
1079 foreach ($dataobject as $field => $value) {
1080 if (!isset($columns[$field])) {
1081 continue;
1082 }
1083 $column = $columns[$field];
1084 $cleaned[$field] = $this->normalise_value($column, $value);
1085 }
1086
1087 return $this->update_record_raw($table, $cleaned, $bulk);
1088 }
1089
1090 /**
2740cea0
PS
1091 * Set a single field in every table record which match a particular WHERE clause.
1092 *
1093 * @param string $table The database table to be checked against.
1094 * @param string $newfield the field to set.
1095 * @param string $newvalue the value to set the field to.
1096 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1097 * @param array $params array of sql parameters
1098 * @return bool true
1099 * @throws dml_exception if error
1100 */
0c57c867 1101 public function set_field_select($table, $newfield, $newvalue, $select, array $params = null) {
1102 if ($select) {
1103 $select = "WHERE $select";
1104 }
1105
1106 if (is_null($params)) {
1107 $params = array ();
1108 }
1109
1110 /// Get column metadata
1111 $columns = $this->get_columns($table);
1112 $column = $columns[$newfield];
1113
1114 $newvalue = $this->normalise_value($column, $newvalue);
1115
1116 if (is_null($newvalue)) {
1117 $newfield = "$newfield = NULL";
1118 } else {
1119 $newfield = "$newfield = ?";
1120 array_unshift($params, $newvalue);
1121 }
1122 $sql = "UPDATE {".$table."} SET $newfield $select";
1123
1124 $this->do_query($sql, $params, SQL_QUERY_UPDATE);
1125
1126 return true;
1127 }
1128
1129 /**
2740cea0
PS
1130 * Delete one or more records from a table which match a particular WHERE clause.
1131 *
1132 * @param string $table The database table to be checked against.
1133 * @param string $select A fragment of SQL to be used in a where clause in the SQL call (used to define the selection criteria).
1134 * @param array $params array of sql parameters
1135 * @return bool true
1136 * @throws dml_exception if error
1137 */
0c57c867 1138 public function delete_records_select($table, $select, array $params = null) {
1139 if ($select) {
1140 $select = "WHERE $select";
1141 }
1142
1143 $sql = "DELETE FROM {".$table."} $select";
1144
30e7e9e4
PS
1145 // we use SQL_QUERY_UPDATE because we do not know what is in general SQL, delete constant would not be accurate
1146 $this->do_query($sql, $params, SQL_QUERY_UPDATE);
0c57c867 1147
1148 return true;
1149 }
1150
1151
1152 /// SQL helper functions
1153
0c57c867 1154 public function sql_cast_char2int($fieldname, $text = false) {
9882b2c8
EL
1155 if (!$text) {
1156 return ' CAST(' . $fieldname . ' AS INT) ';
1157 } else {
1158 return ' CAST(' . $this->sql_compare_text($fieldname) . ' AS INT) ';
1159 }
1160 }
1161
1162 public function sql_cast_char2real($fieldname, $text=false) {
1163 if (!$text) {
1164 return ' CAST(' . $fieldname . ' AS REAL) ';
1165 } else {
1166 return ' CAST(' . $this->sql_compare_text($fieldname) . ' AS REAL) ';
1167 }
0c57c867 1168 }
1169
1170 public function sql_ceil($fieldname) {
1171 return ' CEILING('.$fieldname.')';
1172 }
1173
6055f89d
PS
1174 protected function get_collation() {
1175 if (isset($this->collation)) {
1176 return $this->collation;
1177 }
1178 if (!empty($this->dboptions['dbcollation'])) {
1179 // perf speedup
1180 $this->collation = $this->dboptions['dbcollation'];
1181 return $this->collation;
1182 }
1183
1184 // make some default
1185 $this->collation = 'Latin1_General_CI_AI';
1186
1187 $sql = "SELECT CAST(DATABASEPROPERTYEX('$this->dbname', 'Collation') AS varchar(255)) AS SQLCollation";
1188 $this->query_start($sql, null, SQL_QUERY_AUX);
1189 $result = sqlsrv_query($this->sqlsrv, $sql);
1190 $this->query_end($result);
1191
1192 if ($result) {
1193 if ($rawcolumn = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
1194 $this->collation = reset($rawcolumn);
1195 }
1196 $this->free_result($result);
1197 }
1198
1199 return $this->collation;
1200 }
1201
6055f89d
PS
1202 /**
1203 * Returns 'LIKE' part of a query.
1204 *
1205 * @param string $fieldname usually name of the table column
1206 * @param string $param usually bound query parameter (?, :named)
1207 * @param bool $casesensitive use case sensitive search
1208 * @param bool $accensensitive use accent sensitive search (not all databases support accent insensitive)
16114b9d 1209 * @param bool $notlike true means "NOT LIKE"
6055f89d
PS
1210 * @param string $escapechar escape char for '%' and '_'
1211 * @return string SQL code fragment
1212 */
16114b9d 1213 public function sql_like($fieldname, $param, $casesensitive = true, $accentsensitive = true, $notlike = false, $escapechar = '\\') {
6055f89d
PS
1214 if (strpos($param, '%') !== false) {
1215 debugging('Potential SQL injection detected, sql_ilike() expects bound parameters (? or :named)');
1216 }
1217
1218 $collation = $this->get_collation();
16114b9d 1219 $LIKE = $notlike ? 'NOT LIKE' : 'LIKE';
6055f89d
PS
1220
1221 if ($casesensitive) {
1222 $collation = str_replace('_CI', '_CS', $collation);
1223 } else {
1224 $collation = str_replace('_CS', '_CI', $collation);
1225 }
1226 if ($accentsensitive) {
1227 $collation = str_replace('_AI', '_AS', $collation);
1228 } else {
1229 $collation = str_replace('_AS', '_AI', $collation);
1230 }
1231
16114b9d 1232 return "$fieldname COLLATE $collation $LIKE $param ESCAPE '$escapechar'";
6055f89d
PS
1233 }
1234
0c57c867 1235 public function sql_concat() {
1236 $arr = func_get_args();
1237
1238 foreach ($arr as $key => $ele) {
1239 $arr[$key] = ' CAST('.$ele.' AS VARCHAR(255)) ';
1240 }
1241 $s = implode(' + ', $arr);
1242
1243 if ($s === '') {
1244 return " '' ";
1245 }
1246 return " $s ";
1247 }
1248
1249 public function sql_concat_join($separator = "' '", $elements = array ()) {
1250 for ($n = count($elements) - 1; $n > 0; $n--) {
1251 array_splice($elements, $n, 0, $separator);
1252 }
1253 $s = implode(' + ', $elements);
1254
1255 if ($s === '') {
1256 return " '' ";
1257 }
1258 return " $s ";
1259 }
1260
1261 public function sql_isempty($tablename, $fieldname, $nullablefield, $textfield) {
1262 if ($textfield) {
1263 return ' ('.$this->sql_compare_text($fieldname)." = '') ";
1264 } else {
1265 return " ($fieldname = '') ";
1266 }
1267 }
1268
1269 /**
2740cea0
PS
1270 * Returns the SQL text to be used to calculate the length in characters of one expression.
1271 * @param string fieldname or expression to calculate its length in characters.
1272 * @return string the piece of SQL code to be used in the statement.
1273 */
0c57c867 1274 public function sql_length($fieldname) {
1275 return ' LEN('.$fieldname.')';
1276 }
1277
1278 public function sql_order_by_text($fieldname, $numchars = 32) {
1279 return ' CONVERT(varchar, '.$fieldname.', '.$numchars.')';
1280 }
1281
1282 /**
2740cea0
PS
1283 * Returns the SQL for returning searching one string for the location of another.
1284 */
0c57c867 1285 public function sql_position($needle, $haystack) {
1286 return "CHARINDEX(($needle), ($haystack))";
1287 }
1288
1289 /**
2740cea0
PS
1290 * Returns the proper substr() SQL text used to extract substrings from DB
1291 * NOTE: this was originally returning only function name
1292 *
1293 * @param string $expr some string field, no aggregates
1294 * @param mixed $start integer or expression evaluating to int
1295 * @param mixed $length optional integer or expression evaluating to int
1296 * @return string sql fragment
1297 */
0c57c867 1298 public function sql_substr($expr, $start, $length = false) {
1299 if (count(func_get_args()) < 2) {
2740cea0
PS
1300 throw new coding_exception('moodle_database::sql_substr() requires at least two parameters',
1301 'Originally this function was only returning name of SQL substring function, it now requires all parameters.');
0c57c867 1302 }
1303
1304 if ($length === false) {
1305 return "SUBSTRING($expr, $start, (LEN($expr) - $start + 1))";
1306 } else {
1307 return "SUBSTRING($expr, $start, $length)";
1308 }
1309 }
1310
1311 /// session locking
1312
1313 public function session_lock_supported() {
1314 return true;
1315 }
1316
1317 public function get_session_lock($rowid) {
1318 if (!$this->session_lock_supported()) {
1319 return;
1320 }
1321 parent::get_session_lock($rowid);
1322
1323 $fullname = $this->dbname.'-'.$this->prefix.'-session-'.$rowid;
1324 $sql = "sp_getapplock '$fullname', 'Exclusive', 'Session', 120000";
1325 $this->query_start($sql, null, SQL_QUERY_AUX);
1326 $result = sqlsrv_query($this->sqlsrv, $sql);
1327 $this->query_end($result);
1328 $this->free_result($result);
1329 }
1330
1331 public function release_session_lock($rowid) {
1332 if (!$this->session_lock_supported()) {
1333 return;
1334 }
1335 parent::release_session_lock($rowid);
1336
1337 $fullname = $this->dbname.'-'.$this->prefix.'-session-'.$rowid;
1338 $sql = "sp_releaseapplock '$fullname', 'Session'";
1339 $this->query_start($sql, null, SQL_QUERY_AUX);
1340 $result = sqlsrv_query($this->sqlsrv, $sql);
1341 $this->query_end($result);
1342 $this->free_result($result);
1343 }
1344
1345
1346 /// transactions
1347
1348 // NOTE:
f2ed3f05 1349 // TODO -- should these be wrapped in query start/end? They arn't a query
0c57c867 1350 // but information and error capture is nice. msk
1351
1352
1353 /**
2740cea0
PS
1354 * Driver specific start of real database transaction,
1355 * this can not be used directly in code.
1356 * @return void
1357 */
0c57c867 1358 protected function begin_transaction() {
1359 $this->query_start('native sqlsrv_begin_transaction', NULL, SQL_QUERY_AUX);
1360 $result = sqlsrv_begin_transaction($this->sqlsrv);
1361 $this->query_end($result);
1362 }
1363
1364 /**
2740cea0
PS
1365 * Driver specific commit of real database transaction,
1366 * this can not be used directly in code.
1367 * @return void
1368 */
0c57c867 1369 protected function commit_transaction() {
1370 $this->query_start('native sqlsrv_commit', NULL, SQL_QUERY_AUX);
1371 $result = sqlsrv_commit($this->sqlsrv);
1372 $this->query_end($result);
1373 }
1374
1375 /**
2740cea0
PS
1376 * Driver specific abort of real database transaction,
1377 * this can not be used directly in code.
1378 * @return void
1379 */
0c57c867 1380 protected function rollback_transaction() {
1381 $this->query_start('native sqlsrv_rollback', NULL, SQL_QUERY_AUX);
1382 $result = sqlsrv_rollback($this->sqlsrv);
1383 $this->query_end($result);
1384 }
2740cea0 1385}