MDL-28135 general Updated broken and typo docs links
[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)\" ";
3b1b5018 120 $str .= "onclick=\"return window.open('http://docs.moodle.org/en/Using_the_Microsoft_SQL_Server_Driver_for_PHP')\"";
0c57c867 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.
3479ba4d 350 * @param mixed $scrollable - Default false, to use for quickly seeking to target records
2740cea0 351 */
3479ba4d 352 private function do_query($sql, $params, $sql_query_type, $free_result = true, $scrollable = false) {
0c57c867 353 list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
354
355 $sql = $this->emulate_bound_params($sql, $params);
356 $this->query_start($sql, $params, $sql_query_type);
3479ba4d
EL
357 if (!$scrollable) { // Only supporting next row
358 $result = sqlsrv_query($this->sqlsrv, $sql);
359 } else { // Suporting absolute/relative rows
360 $result = sqlsrv_query($this->sqlsrv, $sql, array(), array('Scrollable' => SQLSRV_CURSOR_STATIC));
361 }
0c57c867 362
363 if ($result === false) {
364 // TODO do something with error or just use if DEV or DEBUG?
365 $dberr = $this->get_last_error();
366 }
367
368 $this->query_end($result);
369
370 if ($free_result) {
371 $this->free_result($result);
372 return true;
373 }
374 return $result;
375 }
376
377 /**
2740cea0
PS
378 * Return tables in database WITHOUT current prefix
379 * @return array of table names in lowercase and without prefix
380 */
0c57c867 381 public function get_tables($usecache = true) {
382 if ($usecache and count($this->tables) > 0) {
383 return $this->tables;
384 }
385 $this->tables = array ();
b4833117 386 $prefix = str_replace('_', '\\_', $this->prefix);
30e7e9e4
PS
387 $sql = "SELECT table_name
388 FROM information_schema.tables
a4411e56 389 WHERE table_name LIKE '$prefix%' ESCAPE '\\' AND table_type = 'BASE TABLE'";
0c57c867 390
391 $this->query_start($sql, null, SQL_QUERY_AUX);
392 $result = sqlsrv_query($this->sqlsrv, $sql);
393 $this->query_end($result);
394
395 if ($result) {
396 while ($row = sqlsrv_fetch_array($result)) {
397 $tablename = reset($row);
398 if (strpos($tablename, $this->prefix) !== 0) {
399 continue;
400 }
401 $tablename = substr($tablename, strlen($this->prefix));
402 $this->tables[$tablename] = $tablename;
403 }
404 $this->free_result($result);
405 }
406
407 // Add the currently available temptables
408 $this->tables = array_merge($this->tables, $this->temptables->get_temptables());
409 return $this->tables;
410 }
411
412 /**
2740cea0
PS
413 * Return table indexes - everything lowercased
414 * @return array of arrays
415 */
0c57c867 416 public function get_indexes($table) {
417 $indexes = array ();
418 $tablename = $this->prefix.$table;
419
420 // Indexes aren't covered by information_schema metatables, so we need to
421 // go to sys ones. Skipping primary key indexes on purpose.
422 $sql = "SELECT i.name AS index_name, i.is_unique, ic.index_column_id, c.name AS column_name
30e7e9e4
PS
423 FROM sys.indexes i
424 JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
425 JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
426 JOIN sys.tables t ON i.object_id = t.object_id
427 WHERE t.name = '$tablename' AND i.is_primary_key = 0
428 ORDER BY i.name, i.index_id, ic.index_column_id";
0c57c867 429
430 $this->query_start($sql, null, SQL_QUERY_AUX);
431 $result = sqlsrv_query($this->sqlsrv, $sql);
432 $this->query_end($result);
433
434 if ($result) {
435 $lastindex = '';
436 $unique = false;
437 $columns = array ();
438
439 while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
440 if ($lastindex and $lastindex != $row['index_name'])
441 { // Save lastindex to $indexes and reset info
442 $indexes[$lastindex] = array
443 (
444 'unique' => $unique,
445 'columns' => $columns
446 );
447
448 $unique = false;
449 $columns = array ();
450 }
451 $lastindex = $row['index_name'];
452 $unique = empty($row['is_unique']) ? false : true;
453 $columns[] = $row['column_name'];
454 }
455
456 if ($lastindex) { // Add the last one if exists
457 $indexes[$lastindex] = array
458 (
459 'unique' => $unique,
460 'columns' => $columns
461 );
462 }
463
464 $this->free_result($result);
465 }
466 return $indexes;
467 }
468
469 /**
2740cea0
PS
470 * Returns detailed information about columns in table. This information is cached internally.
471 * @param string $table name
472 * @param bool $usecache
473 * @return array array of database_column_info objects indexed with column names
474 */
0c57c867 475 public function get_columns($table, $usecache = true) {
476 if ($usecache and isset($this->columns[$table])) {
477 return $this->columns[$table];
478 }
479
480 $this->columns[$table] = array ();
481
482 if (!$this->temptables->is_temptable($table)) { // normal table, get metadata from own schema
483 $sql = "SELECT column_name AS name,
30e7e9e4
PS
484 data_type AS type,
485 numeric_precision AS max_length,
486 character_maximum_length AS char_max_length,
487 numeric_scale AS scale,
488 is_nullable AS is_nullable,
489 columnproperty(object_id(quotename(table_schema) + '.' + quotename(table_name)), column_name, 'IsIdentity') AS auto_increment,
490 column_default AS default_value
491 FROM information_schema.columns
492 WHERE table_name = '{".$table."}'
493 ORDER BY ordinal_position";
0c57c867 494 } else { // temp table, get metadata from tempdb schema
495 $sql = "SELECT column_name AS name,
30e7e9e4
PS
496 data_type AS type,
497 numeric_precision AS max_length,
498 character_maximum_length AS char_max_length,
499 numeric_scale AS scale,
500 is_nullable AS is_nullable,
501 columnproperty(object_id(quotename(table_schema) + '.' + quotename(table_name)), column_name, 'IsIdentity') AS auto_increment,
502 column_default AS default_value
503 FROM tempdb.information_schema.columns ".
0c57c867 504 // check this statement
505 // JOIN tempdb..sysobjects ON name = table_name
506 // WHERE id = object_id('tempdb..{".$table."}')
30e7e9e4
PS
507 "WHERE table_name LIKE '{".$table."}__________%'
508 ORDER BY ordinal_position";
0c57c867 509 }
510
511 list($sql, $params, $type) = $this->fix_sql_params($sql, null);
512
513 $this->query_start($sql, null, SQL_QUERY_AUX);
514 $result = sqlsrv_query($this->sqlsrv, $sql);
515 $this->query_end($result);
516
517 if (!$result) {
518 return array ();
519 }
520
521 while ($rawcolumn = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
522
523 $rawcolumn = (object)$rawcolumn;
524
ac6f1a82 525 $info = new stdClass();
0c57c867 526 $info->name = $rawcolumn->name;
527 $info->type = $rawcolumn->type;
528 $info->meta_type = $this->sqlsrvtype2moodletype($info->type);
529
530 // Prepare auto_increment info
531 $info->auto_increment = $rawcolumn->auto_increment ? true : false;
532
533 // Define type for auto_increment columns
534 $info->meta_type = ($info->auto_increment && $info->meta_type == 'I') ? 'R' : $info->meta_type;
535
536 // id columns being auto_incremnt are PK by definition
537 $info->primary_key = ($info->name == 'id' && $info->meta_type == 'R' && $info->auto_increment);
538
539 // Put correct length for character and LOB types
540 $info->max_length = $info->meta_type == 'C' ? $rawcolumn->char_max_length : $rawcolumn->max_length;
541 $info->max_length = ($info->meta_type == 'X' || $info->meta_type == 'B') ? -1 : $info->max_length;
542
543 // Scale
544 $info->scale = $rawcolumn->scale ? $rawcolumn->scale : false;
545
546 // Prepare not_null info
547 $info->not_null = $rawcolumn->is_nullable == 'NO' ? true : false;
548
549 // Process defaults
550 $info->has_default = !empty($rawcolumn->default_value);
fd31089c
PS
551 if ($rawcolumn->default_value === NULL) {
552 $info->default_value = NULL;
553 } else {
554 $info->default_value = preg_replace("/^[\(N]+[']?(.*?)[']?[\)]+$/", '\\1', $rawcolumn->default_value);
555 }
0c57c867 556
557 // Process binary
558 $info->binary = $info->meta_type == 'B' ? true : false;
559
560 $this->columns[$table][$info->name] = new database_column_info($info);
561 }
562 $this->free_result($result);
563
564 return $this->columns[$table];
565 }
566
567 /**
2740cea0
PS
568 * Normalise values based in RDBMS dependencies (booleans, LOBs...)
569 *
570 * @param database_column_info $column column metadata corresponding with the value we are going to normalise
571 * @param mixed $value value we are going to normalise
572 * @return mixed the normalised value
573 */
0c57c867 574 protected function normalise_value($column, $value) {
575 if (is_bool($value)) { /// Always, convert boolean to int
576 $value = (int)$value;
577 } // And continue processing because text columns with numeric info need special handling below
578
579 if ($column->meta_type == 'B')
580 { // BLOBs need to be properly "packed", but can be inserted directly if so.
581 if (!is_null($value)) { // If value not null, unpack it to unquoted hexadecimal byte-string format
582 $value = unpack('H*hex', $value); // we leave it as array, so emulate_bound_params() can detect it
583 } // easily and "bind" the param ok.
584
585 } else if ($column->meta_type == 'X') { // sqlsrv doesn't cast from int to text, so if text column
586 if (is_numeric($value)) { // and is numeric value then cast to string
587 $value = array('numstr' => (string)$value); // and put into array, so emulate_bound_params() will know how
588 } // to "bind" the param ok, avoiding reverse conversion to number
589 } else if ($value === '') {
590
591 if ($column->meta_type == 'I' or $column->meta_type == 'F' or $column->meta_type == 'N') {
592 $value = 0; // prevent '' problems in numeric fields
593 }
594 }
595 return $value;
596 }
597
598 /**
2740cea0
PS
599 * Selectively call sqlsrv_free_stmt(), avoiding some warnings without using the horrible @
600 *
601 * @param sqlsrv_resource $resource resource to be freed if possible
602 */
0c57c867 603 private function free_result($resource) {
604 if (!is_bool($resource)) { // true/false resources cannot be freed
605 return sqlsrv_free_stmt($resource);
606 }
607 }
608
609 /**
2740cea0
PS
610 * Provides mapping between sqlsrv native data types and moodle_database - database_column_info - ones)
611 *
612 * @param string $sqlsrv_type native sqlsrv data type
613 * @return string 1-char database_column_info data type
614 */
0c57c867 615 private function sqlsrvtype2moodletype($sqlsrv_type) {
616 $type = null;
617
618 switch (strtoupper($sqlsrv_type)) {
619 case 'BIT':
620 $type = 'L';
621 break;
622
623 case 'INT':
624 case 'SMALLINT':
625 case 'INTEGER':
626 case 'BIGINT':
627 $type = 'I';
628 break;
629
630 case 'DECIMAL':
631 case 'REAL':
632 case 'FLOAT':
633 $type = 'N';
634 break;
635
636 case 'VARCHAR':
637 case 'NVARCHAR':
638 $type = 'C';
639 break;
640
641 case 'TEXT':
642 case 'NTEXT':
643 case 'VARCHAR(MAX)':
644 case 'NVARCHAR(MAX)':
645 $type = 'X';
646 break;
647
648 case 'IMAGE':
649 case 'VARBINARY(MAX)':
650 $type = 'B';
651 break;
652
653 case 'DATETIME':
654 $type = 'D';
655 break;
656 }
657
658 if (!$type) {
659 throw new dml_exception('invalidsqlsrvnativetype', $sqlsrv_type);
660 }
661 return $type;
662 }
663
664 /**
2740cea0
PS
665 * Do NOT use in code, to be used by database_manager only!
666 * @param string $sql query
667 * @return bool true
668 * @throws dml_exception if error
669 */
0c57c867 670 public function change_database_structure($sql) {
671 $this->reset_caches();
672
673 $this->query_start($sql, null, SQL_QUERY_STRUCTURE);
674 $result = sqlsrv_query($this->sqlsrv, $sql);
675 $this->query_end($result);
676
677 return true;
678 }
679
680 /**
2740cea0
PS
681 * Prepare the array of params for native binding
682 */
0c57c867 683 protected function build_native_bound_params(array $params = null) {
684
685 return null;
686 }
687
688
689 /**
2740cea0
PS
690 * Workaround for SQL*Server Native driver similar to MSSQL driver for
691 * consistent behavior.
692 */
0c57c867 693 protected function emulate_bound_params($sql, array $params = null) {
694
695 if (empty($params)) {
696 return $sql;
697 }
698 /// ok, we have verified sql statement with ? and correct number of params
699 $return = strtok($sql, '?');
700
701 foreach ($params as $param) {
702 if (is_bool($param)) {
703 $return .= (int)$param;
704 } else if (is_array($param) && isset($param['hex'])) { // detect hex binary, bind it specially
705 $return .= '0x'.$param['hex'];
706 } else if (is_array($param) && isset($param['numstr'])) { // detect numerical strings that *must not*
707 $return .= "N'{$param['numstr']}'"; // be converted back to number params, but bound as strings
708 } else if (is_null($param)) {
709 $return .= 'NULL';
710
6055f89d 711 } else if (is_number($param)) { // we can not use is_numeric() because it eats leading zeros from strings like 0045646
7d8f881a 712 $return .= "'$param'"; // this is a hack for MDL-23997, we intentionally use string because it is compatible with both nvarchar and int types
0c57c867 713 } else if (is_float($param)) {
714 $return .= $param;
715 } else {
716 $param = str_replace("'", "''", $param);
717 $return .= "N'$param'";
718 }
719
720 $return .= strtok('?');
721 }
722 return $return;
723 }
724
0c57c867 725 /**
2740cea0
PS
726 * Execute general sql query. Should be used only when no other method suitable.
727 * Do NOT use this to make changes in db structure, use database_manager::execute_sql() instead!
728 * @param string $sql query
729 * @param array $params query parameters
730 * @return bool true
731 * @throws dml_exception if error
732 */
0c57c867 733 public function execute($sql, array $params = null) {
734 if (strpos($sql, ';') !== false) {
735 throw new coding_exception('moodle_database::execute() Multiple sql statements found or bound parameters not used properly in query!');
736 }
737 $this->do_query($sql, $params, SQL_QUERY_UPDATE);
738 return true;
739 }
740
741 /**
2740cea0
PS
742 * Get a number of records as a moodle_recordset using a SQL statement.
743 *
744 * Since this method is a little less readable, use of it should be restricted to
745 * code where it's possible there might be large datasets being returned. For known
746 * small datasets use get_records_sql - it leads to simpler code.
747 *
748 * The return type is as for @see function get_recordset.
749 *
750 * @param string $sql the SQL select query to execute.
751 * @param array $params array of sql parameters
752 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
753 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
5212b07f 754 * @return moodle_recordset instance
2740cea0
PS
755 * @throws dml_exception if error
756 */
0c57c867 757 public function get_recordset_sql($sql, array $params = null, $limitfrom = 0, $limitnum = 0) {
758 $limitfrom = (int)$limitfrom;
759 $limitnum = (int)$limitnum;
760 $limitfrom = max(0, $limitfrom);
761 $limitnum = max(0, $limitnum);
762
763 if ($limitfrom or $limitnum) {
3479ba4d
EL
764 if ($limitnum >= 1) { // Only apply TOP clause if we have any limitnum (limitfrom offset is handled later)
765 $fetch = $limitfrom + $limitnum;
f80de2f2
EL
766 if (PHP_INT_MAX - $limitnum < $limitfrom) { // Check PHP_INT_MAX overflow
767 $fetch = PHP_INT_MAX;
768 }
3479ba4d
EL
769 $sql = preg_replace('/^([\s(])*SELECT([\s]+(DISTINCT|ALL))?(?!\s*TOP\s*\()/i',
770 "\\1SELECT\\2 TOP $fetch", $sql);
0c57c867 771 }
772 }
3479ba4d 773 $result = $this->do_query($sql, $params, SQL_QUERY_SELECT, false, (bool)$limitfrom);
0c57c867 774
3479ba4d
EL
775 if ($limitfrom) { // Skip $limitfrom records
776 sqlsrv_fetch($result, SQLSRV_SCROLL_ABSOLUTE, $limitfrom - 1);
35d19ea6 777 }
3479ba4d 778 return $this->create_recordset($result);
0c57c867 779 }
780
781 /**
2740cea0
PS
782 * Create a record set and initialize with first row
783 *
784 * @param mixed $result
785 * @return sqlsrv_native_moodle_recordset
786 */
0c57c867 787 protected function create_recordset($result) {
788 return new sqlsrv_native_moodle_recordset($result);
789 }
790
791 /**
2740cea0
PS
792 * Get a number of records as an array of objects using a SQL statement.
793 *
794 * Return value as for @see function get_records.
795 *
796 * @param string $sql the SQL select query to execute. The first column of this SELECT statement
797 * must be a unique value (usually the 'id' field), as it will be used as the key of the
798 * returned array.
799 * @param array $params array of sql parameters
800 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
801 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
3503dcad 802 * @return array of objects, or empty array if no records were found
2740cea0
PS
803 * @throws dml_exception if error
804 */
0c57c867 805 public function get_records_sql($sql, array $params = null, $limitfrom = 0, $limitnum = 0) {
806
807 $rs = $this->get_recordset_sql($sql, $params, $limitfrom, $limitnum);
808
809 $results = array();
810
811 foreach ($rs as $row) {
812 $id = reset($row);
813
40504474 814 if (isset($results[$id])) {
0c57c867 815 $colname = key($row);
816 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);
817 }
818 $results[$id] = (object)$row;
819 }
820 $rs->close();
821
822 return $results;
823 }
824
825 /**
2740cea0
PS
826 * Selects records and return values (first field) as an array using a SQL statement.
827 *
828 * @param string $sql The SQL query
829 * @param array $params array of sql parameters
3503dcad 830 * @return array of values
2740cea0
PS
831 * @throws dml_exception if error
832 */
0c57c867 833 public function get_fieldset_sql($sql, array $params = null) {
834
835 $rs = $this->get_recordset_sql($sql, $params);
836
837 $results = array ();
838
839 foreach ($rs as $row) {
840 $results[] = reset($row);
841 }
842 $rs->close();
843
844 return $results;
845 }
846
847 /**
2740cea0
PS
848 * Insert new record into database, as fast as possible, no safety checks, lobs not supported.
849 * @param string $table name
850 * @param mixed $params data record as object or array
851 * @param bool $returnit return it of inserted record
852 * @param bool $bulk true means repeated inserts expected
853 * @param bool $customsequence true if 'id' included in $params, disables $returnid
3503dcad 854 * @return bool|int true or new id
2740cea0
PS
855 * @throws dml_exception if error
856 */
0c57c867 857 public function insert_record_raw($table, $params, $returnid=true, $bulk=false, $customsequence=false) {
858 if (!is_array($params)) {
859 $params = (array)$params;
860 }
861 if ($customsequence) {
862 if (!isset($params['id'])) {
863 throw new coding_exception('moodle_database::insert_record_raw() id field must be specified if custom sequences used.');
864 }
865 $returnid = false;
5c8efdc4
PS
866 // Disable IDENTITY column before inserting record with id
867 $sql = 'SET IDENTITY_INSERT {'.$table.'} ON'; // Yes, it' ON!!
868 $this->do_query($sql, null, SQL_QUERY_AUX);
869
0c57c867 870 } else {
871 unset($params['id']);
872 }
873
874 if (empty($params)) {
875 throw new coding_exception('moodle_database::insert_record_raw() no fields found.');
876 }
877 $fields = implode(',', array_keys($params));
878 $qms = array_fill(0, count($params), '?');
879 $qms = implode(',', $qms);
880 $sql = "INSERT INTO {" . $table . "} ($fields) VALUES($qms)";
881 $query_id = $this->do_query($sql, $params, SQL_QUERY_INSERT);
5c8efdc4
PS
882
883 if ($customsequence) {
884 // Enable IDENTITY column after inserting record with id
885 $sql = 'SET IDENTITY_INSERT {'.$table.'} OFF'; // Yes, it' OFF!!
886 $this->do_query($sql, null, SQL_QUERY_AUX);
887 }
888
0c57c867 889 if ($returnid) {
890 $id = $this->sqlsrv_fetch_id();
891 return $id;
892 } else {
893 return true;
894 }
895 }
896
897 /**
2740cea0
PS
898 * Get the ID of the current action
899 *
900 * @return mixed ID
901 */
0c57c867 902 private function sqlsrv_fetch_id() {
903 $query_id = sqlsrv_query($this->sqlsrv, 'SELECT SCOPE_IDENTITY()');
904 if ($query_id === false) {
905 $dberr = $this->get_last_error();
906 return false;
907 }
908 $row = $this->sqlsrv_fetchrow($query_id);
909 return (int)$row[0];
910 }
911
912 /**
2740cea0
PS
913 * Fetch a single row into an numbered array
914 *
915 * @param mixed $query_id
916 */
0c57c867 917 private function sqlsrv_fetchrow($query_id) {
918 $row = sqlsrv_fetch_array($query_id, SQLSRV_FETCH_NUMERIC);
919 if ($row === false) {
920 $dberr = $this->get_last_error();
921 return false;
922 }
923
924 foreach ($row as $key => $value) {
925 $row[$key] = ($value === ' ' || $value === NULL) ? '' : $value;
926 }
927 return $row;
928 }
929
930 /**
2740cea0
PS
931 * Insert a record into a table and return the "id" field if required.
932 *
933 * Some conversions and safety checks are carried out. Lobs are supported.
934 * If the return ID isn't required, then this just reports success as true/false.
935 * $data is an object containing needed data
936 * @param string $table The database table to be inserted into
937 * @param object $data A data object with values for one or more fields in the record
938 * @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 939 * @return bool|int true or new id
2740cea0
PS
940 * @throws dml_exception if error
941 */
0c57c867 942 public function insert_record($table, $dataobject, $returnid = true, $bulk = false) {
d8fa8e40 943 $dataobject = (array)$dataobject;
0c57c867 944
945 $columns = $this->get_columns($table);
946 $cleaned = array ();
947
948 foreach ($dataobject as $field => $value) {
d8fa8e40
PS
949 if ($field === 'id') {
950 continue;
951 }
0c57c867 952 if (!isset($columns[$field])) {
953 continue;
954 }
955 $column = $columns[$field];
956 $cleaned[$field] = $this->normalise_value($column, $value);
957 }
958
959 return $this->insert_record_raw($table, $cleaned, $returnid, $bulk);
960 }
961
962 /**
2740cea0
PS
963 * Import a record into a table, id field is required.
964 * Safety checks are NOT carried out. Lobs are supported.
965 *
966 * @param string $table name of database table to be inserted into
967 * @param object $dataobject A data object with values for one or more fields in the record
968 * @return bool true
969 * @throws dml_exception if error
970 */
0c57c867 971 public function import_record($table, $dataobject) {
972 if (!is_object($dataobject)) {
973 $dataobject = (object)$dataobject;
974 }
975
976 $columns = $this->get_columns($table);
977 $cleaned = array ();
978
979 foreach ($dataobject as $field => $value) {
980 if (!isset($columns[$field])) {
981 continue;
982 }
983 $column = $columns[$field];
984 $cleaned[$field] = $this->normalise_value($column, $value);
985 }
986
5c8efdc4 987 $this->insert_record_raw($table, $cleaned, false, false, true);
0c57c867 988
5c8efdc4 989 return true;
0c57c867 990 }
991
992 /**
2740cea0
PS
993 * Update record in database, as fast as possible, no safety checks, lobs not supported.
994 * @param string $table name
995 * @param mixed $params data record as object or array
996 * @param bool true means repeated updates expected
997 * @return bool true
998 * @throws dml_exception if error
999 */
0c57c867 1000 public function update_record_raw($table, $params, $bulk = false) {
d8fa8e40 1001 $params = (array)$params;
0c57c867 1002
1003 if (!isset($params['id'])) {
1004 throw new coding_exception('moodle_database::update_record_raw() id field must be specified.');
1005 }
1006 $id = $params['id'];
1007 unset($params['id']);
1008
1009 if (empty($params)) {
1010 throw new coding_exception('moodle_database::update_record_raw() no fields found.');
1011 }
1012
1013 $sets = array ();
1014
1015 foreach ($params as $field => $value) {
1016 $sets[] = "$field = ?";
1017 }
1018
1019 $params[] = $id; // last ? in WHERE condition
1020
1021 $sets = implode(',', $sets);
1022 $sql = "UPDATE {".$table."} SET $sets WHERE id = ?";
1023
1024 $this->do_query($sql, $params, SQL_QUERY_UPDATE);
1025
1026 return true;
1027 }
1028
1029 /**
2740cea0
PS
1030 * Update a record in a table
1031 *
1032 * $dataobject is an object containing needed data
1033 * Relies on $dataobject having a variable "id" to
1034 * specify the record to update
1035 *
1036 * @param string $table The database table to be checked against.
1037 * @param object $dataobject An object with contents equal to fieldname=>fieldvalue. Must have an entry for 'id' to map to the table specified.
1038 * @param bool true means repeated updates expected
1039 * @return bool true
1040 * @throws dml_exception if error
1041 */
0c57c867 1042 public function update_record($table, $dataobject, $bulk = false) {
d8fa8e40 1043 $dataobject = (array)$dataobject;
0c57c867 1044
1045 $columns = $this->get_columns($table);
1046 $cleaned = array ();
1047
1048 foreach ($dataobject as $field => $value) {
1049 if (!isset($columns[$field])) {
1050 continue;
1051 }
1052 $column = $columns[$field];
1053 $cleaned[$field] = $this->normalise_value($column, $value);
1054 }
1055
1056 return $this->update_record_raw($table, $cleaned, $bulk);
1057 }
1058
1059 /**
2740cea0
PS
1060 * Set a single field in every table record which match a particular WHERE clause.
1061 *
1062 * @param string $table The database table to be checked against.
1063 * @param string $newfield the field to set.
1064 * @param string $newvalue the value to set the field to.
1065 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1066 * @param array $params array of sql parameters
1067 * @return bool true
1068 * @throws dml_exception if error
1069 */
0c57c867 1070 public function set_field_select($table, $newfield, $newvalue, $select, array $params = null) {
1071 if ($select) {
1072 $select = "WHERE $select";
1073 }
1074
1075 if (is_null($params)) {
1076 $params = array ();
1077 }
1078
cd278cd4
PS
1079 // convert params to ? types
1080 list($select, $params, $type) = $this->fix_sql_params($select, $params);
1081
0c57c867 1082 /// Get column metadata
1083 $columns = $this->get_columns($table);
1084 $column = $columns[$newfield];
1085
1086 $newvalue = $this->normalise_value($column, $newvalue);
1087
1088 if (is_null($newvalue)) {
1089 $newfield = "$newfield = NULL";
1090 } else {
1091 $newfield = "$newfield = ?";
1092 array_unshift($params, $newvalue);
1093 }
1094 $sql = "UPDATE {".$table."} SET $newfield $select";
1095
1096 $this->do_query($sql, $params, SQL_QUERY_UPDATE);
1097
1098 return true;
1099 }
1100
1101 /**
2740cea0
PS
1102 * Delete one or more records from a table which match a particular WHERE clause.
1103 *
1104 * @param string $table The database table to be checked against.
1105 * @param string $select A fragment of SQL to be used in a where clause in the SQL call (used to define the selection criteria).
1106 * @param array $params array of sql parameters
1107 * @return bool true
1108 * @throws dml_exception if error
1109 */
0c57c867 1110 public function delete_records_select($table, $select, array $params = null) {
1111 if ($select) {
1112 $select = "WHERE $select";
1113 }
1114
1115 $sql = "DELETE FROM {".$table."} $select";
1116
30e7e9e4
PS
1117 // we use SQL_QUERY_UPDATE because we do not know what is in general SQL, delete constant would not be accurate
1118 $this->do_query($sql, $params, SQL_QUERY_UPDATE);
0c57c867 1119
1120 return true;
1121 }
1122
1123
1124 /// SQL helper functions
1125
0c57c867 1126 public function sql_cast_char2int($fieldname, $text = false) {
9882b2c8
EL
1127 if (!$text) {
1128 return ' CAST(' . $fieldname . ' AS INT) ';
1129 } else {
1130 return ' CAST(' . $this->sql_compare_text($fieldname) . ' AS INT) ';
1131 }
1132 }
1133
1134 public function sql_cast_char2real($fieldname, $text=false) {
1135 if (!$text) {
1136 return ' CAST(' . $fieldname . ' AS REAL) ';
1137 } else {
1138 return ' CAST(' . $this->sql_compare_text($fieldname) . ' AS REAL) ';
1139 }
0c57c867 1140 }
1141
1142 public function sql_ceil($fieldname) {
1143 return ' CEILING('.$fieldname.')';
1144 }
1145
6055f89d
PS
1146 protected function get_collation() {
1147 if (isset($this->collation)) {
1148 return $this->collation;
1149 }
1150 if (!empty($this->dboptions['dbcollation'])) {
1151 // perf speedup
1152 $this->collation = $this->dboptions['dbcollation'];
1153 return $this->collation;
1154 }
1155
1156 // make some default
1157 $this->collation = 'Latin1_General_CI_AI';
1158
1159 $sql = "SELECT CAST(DATABASEPROPERTYEX('$this->dbname', 'Collation') AS varchar(255)) AS SQLCollation";
1160 $this->query_start($sql, null, SQL_QUERY_AUX);
1161 $result = sqlsrv_query($this->sqlsrv, $sql);
1162 $this->query_end($result);
1163
1164 if ($result) {
1165 if ($rawcolumn = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
1166 $this->collation = reset($rawcolumn);
1167 }
1168 $this->free_result($result);
1169 }
1170
1171 return $this->collation;
1172 }
1173
6055f89d
PS
1174 /**
1175 * Returns 'LIKE' part of a query.
1176 *
1177 * @param string $fieldname usually name of the table column
1178 * @param string $param usually bound query parameter (?, :named)
1179 * @param bool $casesensitive use case sensitive search
1180 * @param bool $accensensitive use accent sensitive search (not all databases support accent insensitive)
16114b9d 1181 * @param bool $notlike true means "NOT LIKE"
6055f89d
PS
1182 * @param string $escapechar escape char for '%' and '_'
1183 * @return string SQL code fragment
1184 */
16114b9d 1185 public function sql_like($fieldname, $param, $casesensitive = true, $accentsensitive = true, $notlike = false, $escapechar = '\\') {
6055f89d
PS
1186 if (strpos($param, '%') !== false) {
1187 debugging('Potential SQL injection detected, sql_ilike() expects bound parameters (? or :named)');
1188 }
1189
1190 $collation = $this->get_collation();
16114b9d 1191 $LIKE = $notlike ? 'NOT LIKE' : 'LIKE';
6055f89d
PS
1192
1193 if ($casesensitive) {
1194 $collation = str_replace('_CI', '_CS', $collation);
1195 } else {
1196 $collation = str_replace('_CS', '_CI', $collation);
1197 }
1198 if ($accentsensitive) {
1199 $collation = str_replace('_AI', '_AS', $collation);
1200 } else {
1201 $collation = str_replace('_AS', '_AI', $collation);
1202 }
1203
16114b9d 1204 return "$fieldname COLLATE $collation $LIKE $param ESCAPE '$escapechar'";
6055f89d
PS
1205 }
1206
0c57c867 1207 public function sql_concat() {
1208 $arr = func_get_args();
1209
1210 foreach ($arr as $key => $ele) {
1211 $arr[$key] = ' CAST('.$ele.' AS VARCHAR(255)) ';
1212 }
1213 $s = implode(' + ', $arr);
1214
1215 if ($s === '') {
1216 return " '' ";
1217 }
1218 return " $s ";
1219 }
1220
1221 public function sql_concat_join($separator = "' '", $elements = array ()) {
1222 for ($n = count($elements) - 1; $n > 0; $n--) {
1223 array_splice($elements, $n, 0, $separator);
1224 }
1225 $s = implode(' + ', $elements);
1226
1227 if ($s === '') {
1228 return " '' ";
1229 }
1230 return " $s ";
1231 }
1232
1233 public function sql_isempty($tablename, $fieldname, $nullablefield, $textfield) {
1234 if ($textfield) {
1235 return ' ('.$this->sql_compare_text($fieldname)." = '') ";
1236 } else {
1237 return " ($fieldname = '') ";
1238 }
1239 }
1240
1241 /**
2740cea0
PS
1242 * Returns the SQL text to be used to calculate the length in characters of one expression.
1243 * @param string fieldname or expression to calculate its length in characters.
1244 * @return string the piece of SQL code to be used in the statement.
1245 */
0c57c867 1246 public function sql_length($fieldname) {
1247 return ' LEN('.$fieldname.')';
1248 }
1249
1250 public function sql_order_by_text($fieldname, $numchars = 32) {
1251 return ' CONVERT(varchar, '.$fieldname.', '.$numchars.')';
1252 }
1253
1254 /**
2740cea0
PS
1255 * Returns the SQL for returning searching one string for the location of another.
1256 */
0c57c867 1257 public function sql_position($needle, $haystack) {
1258 return "CHARINDEX(($needle), ($haystack))";
1259 }
1260
1261 /**
2740cea0
PS
1262 * Returns the proper substr() SQL text used to extract substrings from DB
1263 * NOTE: this was originally returning only function name
1264 *
1265 * @param string $expr some string field, no aggregates
1266 * @param mixed $start integer or expression evaluating to int
1267 * @param mixed $length optional integer or expression evaluating to int
1268 * @return string sql fragment
1269 */
0c57c867 1270 public function sql_substr($expr, $start, $length = false) {
1271 if (count(func_get_args()) < 2) {
2740cea0
PS
1272 throw new coding_exception('moodle_database::sql_substr() requires at least two parameters',
1273 'Originally this function was only returning name of SQL substring function, it now requires all parameters.');
0c57c867 1274 }
1275
1276 if ($length === false) {
1277 return "SUBSTRING($expr, $start, (LEN($expr) - $start + 1))";
1278 } else {
1279 return "SUBSTRING($expr, $start, $length)";
1280 }
1281 }
1282
1283 /// session locking
1284
1285 public function session_lock_supported() {
1286 return true;
1287 }
1288
1289 public function get_session_lock($rowid) {
1290 if (!$this->session_lock_supported()) {
1291 return;
1292 }
1293 parent::get_session_lock($rowid);
1294
1295 $fullname = $this->dbname.'-'.$this->prefix.'-session-'.$rowid;
1296 $sql = "sp_getapplock '$fullname', 'Exclusive', 'Session', 120000";
1297 $this->query_start($sql, null, SQL_QUERY_AUX);
1298 $result = sqlsrv_query($this->sqlsrv, $sql);
1299 $this->query_end($result);
1300 $this->free_result($result);
1301 }
1302
1303 public function release_session_lock($rowid) {
1304 if (!$this->session_lock_supported()) {
1305 return;
1306 }
1307 parent::release_session_lock($rowid);
1308
1309 $fullname = $this->dbname.'-'.$this->prefix.'-session-'.$rowid;
1310 $sql = "sp_releaseapplock '$fullname', 'Session'";
1311 $this->query_start($sql, null, SQL_QUERY_AUX);
1312 $result = sqlsrv_query($this->sqlsrv, $sql);
1313 $this->query_end($result);
1314 $this->free_result($result);
1315 }
1316
1317
1318 /// transactions
1319
1320 // NOTE:
f2ed3f05 1321 // TODO -- should these be wrapped in query start/end? They arn't a query
0c57c867 1322 // but information and error capture is nice. msk
1323
1324
1325 /**
2740cea0
PS
1326 * Driver specific start of real database transaction,
1327 * this can not be used directly in code.
1328 * @return void
1329 */
0c57c867 1330 protected function begin_transaction() {
1331 $this->query_start('native sqlsrv_begin_transaction', NULL, SQL_QUERY_AUX);
1332 $result = sqlsrv_begin_transaction($this->sqlsrv);
1333 $this->query_end($result);
1334 }
1335
1336 /**
2740cea0
PS
1337 * Driver specific commit of real database transaction,
1338 * this can not be used directly in code.
1339 * @return void
1340 */
0c57c867 1341 protected function commit_transaction() {
1342 $this->query_start('native sqlsrv_commit', NULL, SQL_QUERY_AUX);
1343 $result = sqlsrv_commit($this->sqlsrv);
1344 $this->query_end($result);
1345 }
1346
1347 /**
2740cea0
PS
1348 * Driver specific abort of real database transaction,
1349 * this can not be used directly in code.
1350 * @return void
1351 */
0c57c867 1352 protected function rollback_transaction() {
1353 $this->query_start('native sqlsrv_rollback', NULL, SQL_QUERY_AUX);
1354 $result = sqlsrv_rollback($this->sqlsrv);
1355 $this->query_end($result);
1356 }
2740cea0 1357}