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