MDL-23925, MDL-23888 new sql_ilike() and sql_binary_equal() - this should finally...
[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) {
266 $info['server'] = $server_info['SQLServerName'];
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
520 $info = new object();
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);
546 $info->default_value = preg_replace("/^[\(N]+[']?(.*?)[']?[\)]+$/", '\\1', $rawcolumn->default_value);
547
548 // Process binary
549 $info->binary = $info->meta_type == 'B' ? true : false;
550
551 $this->columns[$table][$info->name] = new database_column_info($info);
552 }
553 $this->free_result($result);
554
555 return $this->columns[$table];
556 }
557
558 /**
2740cea0
PS
559 * Normalise values based in RDBMS dependencies (booleans, LOBs...)
560 *
561 * @param database_column_info $column column metadata corresponding with the value we are going to normalise
562 * @param mixed $value value we are going to normalise
563 * @return mixed the normalised value
564 */
0c57c867 565 protected function normalise_value($column, $value) {
566 if (is_bool($value)) { /// Always, convert boolean to int
567 $value = (int)$value;
568 } // And continue processing because text columns with numeric info need special handling below
569
570 if ($column->meta_type == 'B')
571 { // BLOBs need to be properly "packed", but can be inserted directly if so.
572 if (!is_null($value)) { // If value not null, unpack it to unquoted hexadecimal byte-string format
573 $value = unpack('H*hex', $value); // we leave it as array, so emulate_bound_params() can detect it
574 } // easily and "bind" the param ok.
575
576 } else if ($column->meta_type == 'X') { // sqlsrv doesn't cast from int to text, so if text column
577 if (is_numeric($value)) { // and is numeric value then cast to string
578 $value = array('numstr' => (string)$value); // and put into array, so emulate_bound_params() will know how
579 } // to "bind" the param ok, avoiding reverse conversion to number
580 } else if ($value === '') {
581
582 if ($column->meta_type == 'I' or $column->meta_type == 'F' or $column->meta_type == 'N') {
583 $value = 0; // prevent '' problems in numeric fields
584 }
585 }
586 return $value;
587 }
588
589 /**
2740cea0
PS
590 * Selectively call sqlsrv_free_stmt(), avoiding some warnings without using the horrible @
591 *
592 * @param sqlsrv_resource $resource resource to be freed if possible
593 */
0c57c867 594 private function free_result($resource) {
595 if (!is_bool($resource)) { // true/false resources cannot be freed
596 return sqlsrv_free_stmt($resource);
597 }
598 }
599
600 /**
2740cea0
PS
601 * Provides mapping between sqlsrv native data types and moodle_database - database_column_info - ones)
602 *
603 * @param string $sqlsrv_type native sqlsrv data type
604 * @return string 1-char database_column_info data type
605 */
0c57c867 606 private function sqlsrvtype2moodletype($sqlsrv_type) {
607 $type = null;
608
609 switch (strtoupper($sqlsrv_type)) {
610 case 'BIT':
611 $type = 'L';
612 break;
613
614 case 'INT':
615 case 'SMALLINT':
616 case 'INTEGER':
617 case 'BIGINT':
618 $type = 'I';
619 break;
620
621 case 'DECIMAL':
622 case 'REAL':
623 case 'FLOAT':
624 $type = 'N';
625 break;
626
627 case 'VARCHAR':
628 case 'NVARCHAR':
629 $type = 'C';
630 break;
631
632 case 'TEXT':
633 case 'NTEXT':
634 case 'VARCHAR(MAX)':
635 case 'NVARCHAR(MAX)':
636 $type = 'X';
637 break;
638
639 case 'IMAGE':
640 case 'VARBINARY(MAX)':
641 $type = 'B';
642 break;
643
644 case 'DATETIME':
645 $type = 'D';
646 break;
647 }
648
649 if (!$type) {
650 throw new dml_exception('invalidsqlsrvnativetype', $sqlsrv_type);
651 }
652 return $type;
653 }
654
655 /**
2740cea0
PS
656 * Do NOT use in code, to be used by database_manager only!
657 * @param string $sql query
658 * @return bool true
659 * @throws dml_exception if error
660 */
0c57c867 661 public function change_database_structure($sql) {
662 $this->reset_caches();
663
664 $this->query_start($sql, null, SQL_QUERY_STRUCTURE);
665 $result = sqlsrv_query($this->sqlsrv, $sql);
666 $this->query_end($result);
667
668 return true;
669 }
670
671 /**
2740cea0
PS
672 * Prepare the array of params for native binding
673 */
0c57c867 674 protected function build_native_bound_params(array $params = null) {
675
676 return null;
677 }
678
679
680 /**
2740cea0
PS
681 * Workaround for SQL*Server Native driver similar to MSSQL driver for
682 * consistent behavior.
683 */
0c57c867 684 protected function emulate_bound_params($sql, array $params = null) {
685
686 if (empty($params)) {
687 return $sql;
688 }
689 /// ok, we have verified sql statement with ? and correct number of params
690 $return = strtok($sql, '?');
691
692 foreach ($params as $param) {
693 if (is_bool($param)) {
694 $return .= (int)$param;
695 } else if (is_array($param) && isset($param['hex'])) { // detect hex binary, bind it specially
696 $return .= '0x'.$param['hex'];
697 } else if (is_array($param) && isset($param['numstr'])) { // detect numerical strings that *must not*
698 $return .= "N'{$param['numstr']}'"; // be converted back to number params, but bound as strings
699 } else if (is_null($param)) {
700 $return .= 'NULL';
701
6055f89d 702 } else if (is_number($param)) { // we can not use is_numeric() because it eats leading zeros from strings like 0045646
0c57c867 703 $return .= $param;
704 } else if (is_float($param)) {
705 $return .= $param;
706 } else {
707 $param = str_replace("'", "''", $param);
708 $return .= "N'$param'";
709 }
710
711 $return .= strtok('?');
712 }
713 return $return;
714 }
715
0c57c867 716 /**
2740cea0
PS
717 * Execute general sql query. Should be used only when no other method suitable.
718 * Do NOT use this to make changes in db structure, use database_manager::execute_sql() instead!
719 * @param string $sql query
720 * @param array $params query parameters
721 * @return bool true
722 * @throws dml_exception if error
723 */
0c57c867 724 public function execute($sql, array $params = null) {
725 if (strpos($sql, ';') !== false) {
726 throw new coding_exception('moodle_database::execute() Multiple sql statements found or bound parameters not used properly in query!');
727 }
728 $this->do_query($sql, $params, SQL_QUERY_UPDATE);
729 return true;
730 }
731
732 /**
2740cea0
PS
733 * Get a number of records as a moodle_recordset using a SQL statement.
734 *
735 * Since this method is a little less readable, use of it should be restricted to
736 * code where it's possible there might be large datasets being returned. For known
737 * small datasets use get_records_sql - it leads to simpler code.
738 *
739 * The return type is as for @see function get_recordset.
740 *
741 * @param string $sql the SQL select query to execute.
742 * @param array $params array of sql parameters
743 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
744 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
5212b07f 745 * @return moodle_recordset instance
2740cea0
PS
746 * @throws dml_exception if error
747 */
0c57c867 748 public function get_recordset_sql($sql, array $params = null, $limitfrom = 0, $limitnum = 0) {
749 $limitfrom = (int)$limitfrom;
750 $limitnum = (int)$limitnum;
751 $limitfrom = max(0, $limitfrom);
752 $limitnum = max(0, $limitnum);
753
754 if ($limitfrom or $limitnum) {
755 $sql = $this->limit_to_top_n($sql, $limitfrom, $limitnum);
756 }
757 $result = $this->do_query($sql, $params, SQL_QUERY_SELECT, false);
758 return $this->create_recordset($result);
759 }
760
761 /**
2740cea0
PS
762 * Perform a emulation for LIMIT(offset, limit)
763 *
30e7e9e4
PS
764 * @param string $sql
765 * @param int $offset
766 * @param int $limit
767 * @return string sql
2740cea0 768 */
0c57c867 769 private function limit_to_top_n($sql, $offset, $limit) {
770 if ($limit < 1 && $offset < 1) {
771 return $sql;
772 }
773 $limit = max(0, $limit);
774 $offset = max(0, $offset);
775
776 if ($limit > 0 && $offset == 0) {
777 $sql1 = preg_replace('/^([\s(])*SELECT( DISTINCT | ALL)?(?!\s*TOP\s*\()/i',
778 "\\1SELECT\\2 TOP $limit", $sql);
779 } else {
f2ed3f05 780 // Only apply TOP clause if we have any limitnum (limitfrom offset is handled later)
0c57c867 781 if ($limit < 1) {
782 $limit = "9223372036854775806"; // MAX BIGINT -1
783 }
784 if (preg_match('/\w*FROM[\s|{]*([\w|.]*)[\s|}]?/i', $sql, $match)) {
785 $from_table = $match[1];
786 if (preg_match('/SELECT[\w|\s]*(\*)[\w|\s]*FROM/i', $sql)) {
787 // Need all the columns as the emulation returns some temp cols
788 $cols = array_keys($this->get_columns($from_table));
789 $cols = implode(', ', $cols);
790 } else {
791 $cols = '*';
792 }
30e7e9e4
PS
793 $sql1 = "SELECT $cols
794 FROM (SELECT sub2.*, ROW_NUMBER() OVER(ORDER BY sub2.line2) AS line3
795 FROM (SELECT 1 AS line2, sub1.*
796 FROM {".$from_table."} AS sub1
797 ) AS sub2
798 ) AS sub3
799 WHERE line3 BETWEEN ".($offset+1)." AND ".($offset + $limit);
0c57c867 800 } else {
801 $sql1 = "SELECT 'Invalid table'";
802 }
803 }
804
805 return $sql1;
806 }
807
808 /**
2740cea0
PS
809 * Create a record set and initialize with first row
810 *
811 * @param mixed $result
812 * @return sqlsrv_native_moodle_recordset
813 */
0c57c867 814 protected function create_recordset($result) {
815 return new sqlsrv_native_moodle_recordset($result);
816 }
817
818 /**
2740cea0
PS
819 * Get a number of records as an array of objects using a SQL statement.
820 *
821 * Return value as for @see function get_records.
822 *
823 * @param string $sql the SQL select query to execute. The first column of this SELECT statement
824 * must be a unique value (usually the 'id' field), as it will be used as the key of the
825 * returned array.
826 * @param array $params array of sql parameters
827 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
828 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
3503dcad 829 * @return array of objects, or empty array if no records were found
2740cea0
PS
830 * @throws dml_exception if error
831 */
0c57c867 832 public function get_records_sql($sql, array $params = null, $limitfrom = 0, $limitnum = 0) {
833
834 $rs = $this->get_recordset_sql($sql, $params, $limitfrom, $limitnum);
835
836 $results = array();
837
838 foreach ($rs as $row) {
839 $id = reset($row);
840
841 if (isset($return[$id])) {
842 $colname = key($row);
843 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);
844 }
845 $results[$id] = (object)$row;
846 }
847 $rs->close();
848
849 return $results;
850 }
851
852 /**
2740cea0
PS
853 * Selects records and return values (first field) as an array using a SQL statement.
854 *
855 * @param string $sql The SQL query
856 * @param array $params array of sql parameters
3503dcad 857 * @return array of values
2740cea0
PS
858 * @throws dml_exception if error
859 */
0c57c867 860 public function get_fieldset_sql($sql, array $params = null) {
861
862 $rs = $this->get_recordset_sql($sql, $params);
863
864 $results = array ();
865
866 foreach ($rs as $row) {
867 $results[] = reset($row);
868 }
869 $rs->close();
870
871 return $results;
872 }
873
874 /**
2740cea0
PS
875 * Insert new record into database, as fast as possible, no safety checks, lobs not supported.
876 * @param string $table name
877 * @param mixed $params data record as object or array
878 * @param bool $returnit return it of inserted record
879 * @param bool $bulk true means repeated inserts expected
880 * @param bool $customsequence true if 'id' included in $params, disables $returnid
3503dcad 881 * @return bool|int true or new id
2740cea0
PS
882 * @throws dml_exception if error
883 */
0c57c867 884 public function insert_record_raw($table, $params, $returnid=true, $bulk=false, $customsequence=false) {
885 if (!is_array($params)) {
886 $params = (array)$params;
887 }
888 if ($customsequence) {
889 if (!isset($params['id'])) {
890 throw new coding_exception('moodle_database::insert_record_raw() id field must be specified if custom sequences used.');
891 }
892 $returnid = false;
893 } else {
894 unset($params['id']);
895 }
896
897 if (empty($params)) {
898 throw new coding_exception('moodle_database::insert_record_raw() no fields found.');
899 }
900 $fields = implode(',', array_keys($params));
901 $qms = array_fill(0, count($params), '?');
902 $qms = implode(',', $qms);
903 $sql = "INSERT INTO {" . $table . "} ($fields) VALUES($qms)";
904 $query_id = $this->do_query($sql, $params, SQL_QUERY_INSERT);
905 if ($returnid) {
906 $id = $this->sqlsrv_fetch_id();
907 return $id;
908 } else {
909 return true;
910 }
911 }
912
913 /**
2740cea0
PS
914 * Get the ID of the current action
915 *
916 * @return mixed ID
917 */
0c57c867 918 private function sqlsrv_fetch_id() {
919 $query_id = sqlsrv_query($this->sqlsrv, 'SELECT SCOPE_IDENTITY()');
920 if ($query_id === false) {
921 $dberr = $this->get_last_error();
922 return false;
923 }
924 $row = $this->sqlsrv_fetchrow($query_id);
925 return (int)$row[0];
926 }
927
928 /**
2740cea0
PS
929 * Fetch a single row into an numbered array
930 *
931 * @param mixed $query_id
932 */
0c57c867 933 private function sqlsrv_fetchrow($query_id) {
934 $row = sqlsrv_fetch_array($query_id, SQLSRV_FETCH_NUMERIC);
935 if ($row === false) {
936 $dberr = $this->get_last_error();
937 return false;
938 }
939
940 foreach ($row as $key => $value) {
941 $row[$key] = ($value === ' ' || $value === NULL) ? '' : $value;
942 }
943 return $row;
944 }
945
946 /**
2740cea0
PS
947 * Insert a record into a table and return the "id" field if required.
948 *
949 * Some conversions and safety checks are carried out. Lobs are supported.
950 * If the return ID isn't required, then this just reports success as true/false.
951 * $data is an object containing needed data
952 * @param string $table The database table to be inserted into
953 * @param object $data A data object with values for one or more fields in the record
954 * @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 955 * @return bool|int true or new id
2740cea0
PS
956 * @throws dml_exception if error
957 */
0c57c867 958 public function insert_record($table, $dataobject, $returnid = true, $bulk = false) {
d8fa8e40 959 $dataobject = (array)$dataobject;
0c57c867 960
961 $columns = $this->get_columns($table);
962 $cleaned = array ();
963
964 foreach ($dataobject as $field => $value) {
d8fa8e40
PS
965 if ($field === 'id') {
966 continue;
967 }
0c57c867 968 if (!isset($columns[$field])) {
969 continue;
970 }
971 $column = $columns[$field];
972 $cleaned[$field] = $this->normalise_value($column, $value);
973 }
974
975 return $this->insert_record_raw($table, $cleaned, $returnid, $bulk);
976 }
977
978 /**
2740cea0
PS
979 * Import a record into a table, id field is required.
980 * Safety checks are NOT carried out. Lobs are supported.
981 *
982 * @param string $table name of database table to be inserted into
983 * @param object $dataobject A data object with values for one or more fields in the record
984 * @return bool true
985 * @throws dml_exception if error
986 */
0c57c867 987 public function import_record($table, $dataobject) {
988 if (!is_object($dataobject)) {
989 $dataobject = (object)$dataobject;
990 }
991
992 $columns = $this->get_columns($table);
993 $cleaned = array ();
994
995 foreach ($dataobject as $field => $value) {
996 if (!isset($columns[$field])) {
997 continue;
998 }
999 $column = $columns[$field];
1000 $cleaned[$field] = $this->normalise_value($column, $value);
1001 }
1002
1003 // Disable IDENTITY column before inserting record with id
1004 $sql = 'SET IDENTITY_INSERT {'.$table.'} ON'; // Yes, it' ON!!
1005 $this->do_query($sql, null, SQL_QUERY_AUX);
1006
1007 $insertresult = $this->insert_record_raw($table, $cleaned, false, false, true);
1008
1009 // Enable IDENTITY column after inserting record with id
1010 $sql = 'SET IDENTITY_INSERT {'.$table.'} OFF'; // Yes, it' OFF!!
1011
1012 $this->do_query($sql, null, SQL_QUERY_AUX);
1013
1014 return $insertresult;
1015 }
1016
1017 /**
2740cea0
PS
1018 * Update record in database, as fast as possible, no safety checks, lobs not supported.
1019 * @param string $table name
1020 * @param mixed $params data record as object or array
1021 * @param bool true means repeated updates expected
1022 * @return bool true
1023 * @throws dml_exception if error
1024 */
0c57c867 1025 public function update_record_raw($table, $params, $bulk = false) {
d8fa8e40 1026 $params = (array)$params;
0c57c867 1027
1028 if (!isset($params['id'])) {
1029 throw new coding_exception('moodle_database::update_record_raw() id field must be specified.');
1030 }
1031 $id = $params['id'];
1032 unset($params['id']);
1033
1034 if (empty($params)) {
1035 throw new coding_exception('moodle_database::update_record_raw() no fields found.');
1036 }
1037
1038 $sets = array ();
1039
1040 foreach ($params as $field => $value) {
1041 $sets[] = "$field = ?";
1042 }
1043
1044 $params[] = $id; // last ? in WHERE condition
1045
1046 $sets = implode(',', $sets);
1047 $sql = "UPDATE {".$table."} SET $sets WHERE id = ?";
1048
1049 $this->do_query($sql, $params, SQL_QUERY_UPDATE);
1050
1051 return true;
1052 }
1053
1054 /**
2740cea0
PS
1055 * Update a record in a table
1056 *
1057 * $dataobject is an object containing needed data
1058 * Relies on $dataobject having a variable "id" to
1059 * specify the record to update
1060 *
1061 * @param string $table The database table to be checked against.
1062 * @param object $dataobject An object with contents equal to fieldname=>fieldvalue. Must have an entry for 'id' to map to the table specified.
1063 * @param bool true means repeated updates expected
1064 * @return bool true
1065 * @throws dml_exception if error
1066 */
0c57c867 1067 public function update_record($table, $dataobject, $bulk = false) {
d8fa8e40 1068 $dataobject = (array)$dataobject;
0c57c867 1069
1070 $columns = $this->get_columns($table);
1071 $cleaned = array ();
1072
1073 foreach ($dataobject as $field => $value) {
1074 if (!isset($columns[$field])) {
1075 continue;
1076 }
1077 $column = $columns[$field];
1078 $cleaned[$field] = $this->normalise_value($column, $value);
1079 }
1080
1081 return $this->update_record_raw($table, $cleaned, $bulk);
1082 }
1083
1084 /**
2740cea0
PS
1085 * Set a single field in every table record which match a particular WHERE clause.
1086 *
1087 * @param string $table The database table to be checked against.
1088 * @param string $newfield the field to set.
1089 * @param string $newvalue the value to set the field to.
1090 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1091 * @param array $params array of sql parameters
1092 * @return bool true
1093 * @throws dml_exception if error
1094 */
0c57c867 1095 public function set_field_select($table, $newfield, $newvalue, $select, array $params = null) {
1096 if ($select) {
1097 $select = "WHERE $select";
1098 }
1099
1100 if (is_null($params)) {
1101 $params = array ();
1102 }
1103
1104 /// Get column metadata
1105 $columns = $this->get_columns($table);
1106 $column = $columns[$newfield];
1107
1108 $newvalue = $this->normalise_value($column, $newvalue);
1109
1110 if (is_null($newvalue)) {
1111 $newfield = "$newfield = NULL";
1112 } else {
1113 $newfield = "$newfield = ?";
1114 array_unshift($params, $newvalue);
1115 }
1116 $sql = "UPDATE {".$table."} SET $newfield $select";
1117
1118 $this->do_query($sql, $params, SQL_QUERY_UPDATE);
1119
1120 return true;
1121 }
1122
1123 /**
2740cea0
PS
1124 * Delete one or more records from a table which match a particular WHERE clause.
1125 *
1126 * @param string $table The database table to be checked against.
1127 * @param string $select A fragment of SQL to be used in a where clause in the SQL call (used to define the selection criteria).
1128 * @param array $params array of sql parameters
1129 * @return bool true
1130 * @throws dml_exception if error
1131 */
0c57c867 1132 public function delete_records_select($table, $select, array $params = null) {
1133 if ($select) {
1134 $select = "WHERE $select";
1135 }
1136
1137 $sql = "DELETE FROM {".$table."} $select";
1138
30e7e9e4
PS
1139 // we use SQL_QUERY_UPDATE because we do not know what is in general SQL, delete constant would not be accurate
1140 $this->do_query($sql, $params, SQL_QUERY_UPDATE);
0c57c867 1141
1142 return true;
1143 }
1144
1145
1146 /// SQL helper functions
1147
1148 public function sql_bitxor($int1, $int2) {
1149 return '('.$this->sql_bitor($int1, $int2).' - '.$this->sql_bitand($int1, $int2).')';
1150 }
1151
1152 public function sql_cast_char2int($fieldname, $text = false) {
1153 return ' CAST('.$fieldname.' AS INT) ';
1154 }
1155
1156 public function sql_ceil($fieldname) {
1157 return ' CEILING('.$fieldname.')';
1158 }
1159
6055f89d
PS
1160 protected function get_collation() {
1161 if (isset($this->collation)) {
1162 return $this->collation;
1163 }
1164 if (!empty($this->dboptions['dbcollation'])) {
1165 // perf speedup
1166 $this->collation = $this->dboptions['dbcollation'];
1167 return $this->collation;
1168 }
1169
1170 // make some default
1171 $this->collation = 'Latin1_General_CI_AI';
1172
1173 $sql = "SELECT CAST(DATABASEPROPERTYEX('$this->dbname', 'Collation') AS varchar(255)) AS SQLCollation";
1174 $this->query_start($sql, null, SQL_QUERY_AUX);
1175 $result = sqlsrv_query($this->sqlsrv, $sql);
1176 $this->query_end($result);
1177
1178 if ($result) {
1179 if ($rawcolumn = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
1180 $this->collation = reset($rawcolumn);
1181 }
1182 $this->free_result($result);
1183 }
1184
1185 return $this->collation;
1186 }
1187
1188 /**
1189 * Case and collation sensitive string 'string = string'
1190 * @param string $string1
1191 * @param string $string2
1192 * @return string SQL fragment
1193 */
1194 public function sql_binary_equal($string1, $string2) {
1195 return "$string1 COLLATE Latin1_General_CS_AS = $string2";
1196 }
1197
1198 /**
1199 * Returns 'LIKE' part of a query.
1200 *
1201 * @param string $fieldname usually name of the table column
1202 * @param string $param usually bound query parameter (?, :named)
1203 * @param bool $casesensitive use case sensitive search
1204 * @param bool $accensensitive use accent sensitive search (not all databases support accent insensitive)
1205 * @param string $escapechar escape char for '%' and '_'
1206 * @return string SQL code fragment
1207 */
1208 public function sql_like($fieldname, $param, $casesensitive = true, $accentsensitive = true, $escapechar = '\\') {
1209 if (strpos($param, '%') !== false) {
1210 debugging('Potential SQL injection detected, sql_ilike() expects bound parameters (? or :named)');
1211 }
1212
1213 $collation = $this->get_collation();
1214
1215 if ($casesensitive) {
1216 $collation = str_replace('_CI', '_CS', $collation);
1217 } else {
1218 $collation = str_replace('_CS', '_CI', $collation);
1219 }
1220 if ($accentsensitive) {
1221 $collation = str_replace('_AI', '_AS', $collation);
1222 } else {
1223 $collation = str_replace('_AS', '_AI', $collation);
1224 }
1225
1226 return "$fieldname COLLATE $collation LIKE $param ESCAPE '$escapechar'";
1227 }
1228
0c57c867 1229 public function sql_concat() {
1230 $arr = func_get_args();
1231
1232 foreach ($arr as $key => $ele) {
1233 $arr[$key] = ' CAST('.$ele.' AS VARCHAR(255)) ';
1234 }
1235 $s = implode(' + ', $arr);
1236
1237 if ($s === '') {
1238 return " '' ";
1239 }
1240 return " $s ";
1241 }
1242
1243 public function sql_concat_join($separator = "' '", $elements = array ()) {
1244 for ($n = count($elements) - 1; $n > 0; $n--) {
1245 array_splice($elements, $n, 0, $separator);
1246 }
1247 $s = implode(' + ', $elements);
1248
1249 if ($s === '') {
1250 return " '' ";
1251 }
1252 return " $s ";
1253 }
1254
1255 public function sql_isempty($tablename, $fieldname, $nullablefield, $textfield) {
1256 if ($textfield) {
1257 return ' ('.$this->sql_compare_text($fieldname)." = '') ";
1258 } else {
1259 return " ($fieldname = '') ";
1260 }
1261 }
1262
1263 /**
2740cea0
PS
1264 * Returns the SQL text to be used to calculate the length in characters of one expression.
1265 * @param string fieldname or expression to calculate its length in characters.
1266 * @return string the piece of SQL code to be used in the statement.
1267 */
0c57c867 1268 public function sql_length($fieldname) {
1269 return ' LEN('.$fieldname.')';
1270 }
1271
1272 public function sql_order_by_text($fieldname, $numchars = 32) {
1273 return ' CONVERT(varchar, '.$fieldname.', '.$numchars.')';
1274 }
1275
1276 /**
2740cea0
PS
1277 * Returns the SQL for returning searching one string for the location of another.
1278 */
0c57c867 1279 public function sql_position($needle, $haystack) {
1280 return "CHARINDEX(($needle), ($haystack))";
1281 }
1282
1283 /**
2740cea0
PS
1284 * Returns the proper substr() SQL text used to extract substrings from DB
1285 * NOTE: this was originally returning only function name
1286 *
1287 * @param string $expr some string field, no aggregates
1288 * @param mixed $start integer or expression evaluating to int
1289 * @param mixed $length optional integer or expression evaluating to int
1290 * @return string sql fragment
1291 */
0c57c867 1292 public function sql_substr($expr, $start, $length = false) {
1293 if (count(func_get_args()) < 2) {
2740cea0
PS
1294 throw new coding_exception('moodle_database::sql_substr() requires at least two parameters',
1295 'Originally this function was only returning name of SQL substring function, it now requires all parameters.');
0c57c867 1296 }
1297
1298 if ($length === false) {
1299 return "SUBSTRING($expr, $start, (LEN($expr) - $start + 1))";
1300 } else {
1301 return "SUBSTRING($expr, $start, $length)";
1302 }
1303 }
1304
1305 /// session locking
1306
1307 public function session_lock_supported() {
1308 return true;
1309 }
1310
1311 public function get_session_lock($rowid) {
1312 if (!$this->session_lock_supported()) {
1313 return;
1314 }
1315 parent::get_session_lock($rowid);
1316
1317 $fullname = $this->dbname.'-'.$this->prefix.'-session-'.$rowid;
1318 $sql = "sp_getapplock '$fullname', 'Exclusive', 'Session', 120000";
1319 $this->query_start($sql, null, SQL_QUERY_AUX);
1320 $result = sqlsrv_query($this->sqlsrv, $sql);
1321 $this->query_end($result);
1322 $this->free_result($result);
1323 }
1324
1325 public function release_session_lock($rowid) {
1326 if (!$this->session_lock_supported()) {
1327 return;
1328 }
1329 parent::release_session_lock($rowid);
1330
1331 $fullname = $this->dbname.'-'.$this->prefix.'-session-'.$rowid;
1332 $sql = "sp_releaseapplock '$fullname', 'Session'";
1333 $this->query_start($sql, null, SQL_QUERY_AUX);
1334 $result = sqlsrv_query($this->sqlsrv, $sql);
1335 $this->query_end($result);
1336 $this->free_result($result);
1337 }
1338
1339
1340 /// transactions
1341
1342 // NOTE:
f2ed3f05 1343 // TODO -- should these be wrapped in query start/end? They arn't a query
0c57c867 1344 // but information and error capture is nice. msk
1345
1346
1347 /**
2740cea0
PS
1348 * Driver specific start of real database transaction,
1349 * this can not be used directly in code.
1350 * @return void
1351 */
0c57c867 1352 protected function begin_transaction() {
1353 $this->query_start('native sqlsrv_begin_transaction', NULL, SQL_QUERY_AUX);
1354 $result = sqlsrv_begin_transaction($this->sqlsrv);
1355 $this->query_end($result);
1356 }
1357
1358 /**
2740cea0
PS
1359 * Driver specific commit of real database transaction,
1360 * this can not be used directly in code.
1361 * @return void
1362 */
0c57c867 1363 protected function commit_transaction() {
1364 $this->query_start('native sqlsrv_commit', NULL, SQL_QUERY_AUX);
1365 $result = sqlsrv_commit($this->sqlsrv);
1366 $this->query_end($result);
1367 }
1368
1369 /**
2740cea0
PS
1370 * Driver specific abort of real database transaction,
1371 * this can not be used directly in code.
1372 * @return void
1373 */
0c57c867 1374 protected function rollback_transaction() {
1375 $this->query_start('native sqlsrv_rollback', NULL, SQL_QUERY_AUX);
1376 $result = sqlsrv_rollback($this->sqlsrv);
1377 $this->query_end($result);
1378 }
2740cea0 1379}