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