Merge branch 'MDL-63140-master' of git://github.com/rezaies/moodle
[moodle.git] / lib / dml / sqlsrv_native_moodle_database.php
blob9174f70c60086bac64712d5a10757fe4a0851874
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 2 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Native sqlsrv class representing moodle database interface.
20 * @package core_dml
21 * @copyright 2009 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v2 or later
25 defined('MOODLE_INTERNAL') || die();
27 require_once(__DIR__.'/moodle_database.php');
28 require_once(__DIR__.'/sqlsrv_native_moodle_recordset.php');
29 require_once(__DIR__.'/sqlsrv_native_moodle_temptables.php');
31 /**
32 * Native sqlsrv class representing moodle database interface.
34 * @package core_dml
35 * @copyright 2009 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
36 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v2 or later
38 class sqlsrv_native_moodle_database extends moodle_database {
40 protected $sqlsrv = null;
41 protected $last_error_reporting; // To handle SQL*Server-Native driver default verbosity
42 protected $temptables; // Control existing temptables (sqlsrv_moodle_temptables object)
43 protected $collation; // current DB collation cache
44 /**
45 * Does the used db version support ANSI way of limiting (2012 and higher)
46 * @var bool
48 protected $supportsoffsetfetch;
50 /** @var array list of open recordsets */
51 protected $recordsets = array();
53 /** @var array list of reserve words in MSSQL / Transact from http://msdn2.microsoft.com/en-us/library/ms189822.aspx */
54 protected $reservewords = [
55 "add", "all", "alter", "and", "any", "as", "asc", "authorization", "avg", "backup", "begin", "between", "break",
56 "browse", "bulk", "by", "cascade", "case", "check", "checkpoint", "close", "clustered", "coalesce", "collate", "column",
57 "commit", "committed", "compute", "confirm", "constraint", "contains", "containstable", "continue", "controlrow",
58 "convert", "count", "create", "cross", "current", "current_date", "current_time", "current_timestamp", "current_user",
59 "cursor", "database", "dbcc", "deallocate", "declare", "default", "delete", "deny", "desc", "disk", "distinct",
60 "distributed", "double", "drop", "dummy", "dump", "else", "end", "errlvl", "errorexit", "escape", "except", "exec",
61 "execute", "exists", "exit", "external", "fetch", "file", "fillfactor", "floppy", "for", "foreign", "freetext",
62 "freetexttable", "from", "full", "function", "goto", "grant", "group", "having", "holdlock", "identity",
63 "identity_insert", "identitycol", "if", "in", "index", "inner", "insert", "intersect", "into", "is", "isolation",
64 "join", "key", "kill", "left", "level", "like", "lineno", "load", "max", "merge", "min", "mirrorexit", "national",
65 "nocheck", "nonclustered", "not", "null", "nullif", "of", "off", "offsets", "on", "once", "only", "open",
66 "opendatasource", "openquery", "openrowset", "openxml", "option", "or", "order", "outer", "over", "percent", "perm",
67 "permanent", "pipe", "pivot", "plan", "precision", "prepare", "primary", "print", "privileges", "proc", "procedure",
68 "processexit", "public", "raiserror", "read", "readtext", "reconfigure", "references", "repeatable", "replication",
69 "restore", "restrict", "return", "revert", "revoke", "right", "rollback", "rowcount", "rowguidcol", "rule", "save",
70 "schema", "securityaudit", "select", "semantickeyphrasetable", "semanticsimilaritydetailstable",
71 "semanticsimilaritytable", "serializable", "session_user", "set", "setuser", "shutdown", "some", "statistics", "sum",
72 "system_user", "table", "tablesample", "tape", "temp", "temporary", "textsize", "then", "to", "top", "tran",
73 "transaction", "trigger", "truncate", "try_convert", "tsequal", "uncommitted", "union", "unique", "unpivot", "update",
74 "updatetext", "use", "user", "values", "varying", "view", "waitfor", "when", "where", "while", "with", "within group",
75 "work", "writetext"
78 /**
79 * Constructor - instantiates the database, specifying if it's external (connect to other systems) or no (Moodle DB)
80 * note this has effect to decide if prefix checks must be performed or no
81 * @param bool true means external database used
83 public function __construct($external=false) {
84 parent::__construct($external);
87 /**
88 * Detects if all needed PHP stuff installed.
89 * Note: can be used before connect()
90 * @return mixed true if ok, string if something
92 public function driver_installed() {
93 // use 'function_exists()' rather than 'extension_loaded()' because
94 // the name used by 'extension_loaded()' is case specific! The extension
95 // therefore *could be* mixed case and hence not found.
96 if (!function_exists('sqlsrv_num_rows')) {
97 return get_string('nativesqlsrvnodriver', 'install');
99 return true;
103 * Returns database family type - describes SQL dialect
104 * Note: can be used before connect()
105 * @return string db family name (mysql, postgres, mssql, sqlsrv, oracle, etc.)
107 public function get_dbfamily() {
108 return 'mssql';
112 * Returns more specific database driver type
113 * Note: can be used before connect()
114 * @return string db type mysqli, pgsql, oci, mssql, sqlsrv
116 protected function get_dbtype() {
117 return 'sqlsrv';
121 * Returns general database library name
122 * Note: can be used before connect()
123 * @return string db type pdo, native
125 protected function get_dblibrary() {
126 return 'native';
130 * Returns localised database type name
131 * Note: can be used before connect()
132 * @return string
134 public function get_name() {
135 return get_string('nativesqlsrv', 'install');
139 * Returns localised database configuration help.
140 * Note: can be used before connect()
141 * @return string
143 public function get_configuration_help() {
144 return get_string('nativesqlsrvhelp', 'install');
148 * Diagnose database and tables, this function is used
149 * to verify database and driver settings, db engine types, etc.
151 * @return string null means everything ok, string means problem found.
153 public function diagnose() {
154 // Verify the database is running with READ_COMMITTED_SNAPSHOT enabled.
155 // (that's required to get snapshots/row versioning on READ_COMMITED mode).
156 $correctrcsmode = false;
157 $sql = "SELECT is_read_committed_snapshot_on
158 FROM sys.databases
159 WHERE name = '{$this->dbname}'";
160 $this->query_start($sql, null, SQL_QUERY_AUX);
161 $result = sqlsrv_query($this->sqlsrv, $sql);
162 $this->query_end($result);
163 if ($result) {
164 if ($row = sqlsrv_fetch_array($result)) {
165 $correctrcsmode = (bool)reset($row);
168 $this->free_result($result);
170 if (!$correctrcsmode) {
171 return get_string('mssqlrcsmodemissing', 'error');
174 // Arrived here, all right.
175 return null;
179 * Connect to db
180 * Must be called before most other methods. (you can call methods that return connection configuration parameters)
181 * @param string $dbhost The database host.
182 * @param string $dbuser The database username.
183 * @param string $dbpass The database username's password.
184 * @param string $dbname The name of the database being connected to.
185 * @param mixed $prefix string|bool The moodle db table name's prefix. false is used for external databases where prefix not used
186 * @param array $dboptions driver specific options
187 * @return bool true
188 * @throws dml_connection_exception if error
190 public function connect($dbhost, $dbuser, $dbpass, $dbname, $prefix, array $dboptions=null) {
191 if ($prefix == '' and !$this->external) {
192 // Enforce prefixes for everybody but mysql.
193 throw new dml_exception('prefixcannotbeempty', $this->get_dbfamily());
196 $driverstatus = $this->driver_installed();
198 if ($driverstatus !== true) {
199 throw new dml_exception('dbdriverproblem', $driverstatus);
203 * Log all Errors.
205 sqlsrv_configure("WarningsReturnAsErrors", FALSE);
206 sqlsrv_configure("LogSubsystems", SQLSRV_LOG_SYSTEM_OFF);
207 sqlsrv_configure("LogSeverity", SQLSRV_LOG_SEVERITY_ERROR);
209 $this->store_settings($dbhost, $dbuser, $dbpass, $dbname, $prefix, $dboptions);
211 $dbhost = $this->dbhost;
212 if (!empty($dboptions['dbport'])) {
213 $dbhost .= ',' . $dboptions['dbport'];
216 $this->sqlsrv = sqlsrv_connect($dbhost, array
218 'UID' => $this->dbuser,
219 'PWD' => $this->dbpass,
220 'Database' => $this->dbname,
221 'CharacterSet' => 'UTF-8',
222 'MultipleActiveResultSets' => true,
223 'ConnectionPooling' => !empty($this->dboptions['dbpersist']),
224 'ReturnDatesAsStrings' => true,
227 if ($this->sqlsrv === false) {
228 $this->sqlsrv = null;
229 $dberr = $this->get_last_error();
231 throw new dml_connection_exception($dberr);
234 // Disable logging until we are fully setup.
235 $this->query_log_prevent();
237 // Allow quoted identifiers
238 $sql = "SET QUOTED_IDENTIFIER ON";
239 $this->query_start($sql, null, SQL_QUERY_AUX);
240 $result = sqlsrv_query($this->sqlsrv, $sql);
241 $this->query_end($result);
243 $this->free_result($result);
245 // Force ANSI nulls so the NULL check was done by IS NULL and NOT IS NULL
246 // instead of equal(=) and distinct(<>) symbols
247 $sql = "SET ANSI_NULLS ON";
248 $this->query_start($sql, null, SQL_QUERY_AUX);
249 $result = sqlsrv_query($this->sqlsrv, $sql);
250 $this->query_end($result);
252 $this->free_result($result);
254 // Force ANSI warnings so arithmetic/string overflows will be
255 // returning error instead of transparently truncating data
256 $sql = "SET ANSI_WARNINGS ON";
257 $this->query_start($sql, null, SQL_QUERY_AUX);
258 $result = sqlsrv_query($this->sqlsrv, $sql);
259 $this->query_end($result);
261 // Concatenating null with anything MUST return NULL
262 $sql = "SET CONCAT_NULL_YIELDS_NULL ON";
263 $this->query_start($sql, null, SQL_QUERY_AUX);
264 $result = sqlsrv_query($this->sqlsrv, $sql);
265 $this->query_end($result);
267 $this->free_result($result);
269 // Set transactions isolation level to READ_COMMITTED
270 // prevents dirty reads when using transactions +
271 // is the default isolation level of sqlsrv
272 $sql = "SET TRANSACTION ISOLATION LEVEL READ COMMITTED";
273 $this->query_start($sql, NULL, SQL_QUERY_AUX);
274 $result = sqlsrv_query($this->sqlsrv, $sql);
275 $this->query_end($result);
277 $this->free_result($result);
279 $serverinfo = $this->get_server_info();
280 // Fetch/offset is supported staring from SQL Server 2012.
281 $this->supportsoffsetfetch = $serverinfo['version'] > '11';
283 // We can enable logging now.
284 $this->query_log_allow();
286 // Connection established and configured, going to instantiate the temptables controller
287 $this->temptables = new sqlsrv_native_moodle_temptables($this);
289 return true;
293 * Close database connection and release all resources
294 * and memory (especially circular memory references).
295 * Do NOT use connect() again, create a new instance if needed.
297 public function dispose() {
298 parent::dispose(); // Call parent dispose to write/close session and other common stuff before closing connection
300 if ($this->sqlsrv) {
301 sqlsrv_close($this->sqlsrv);
302 $this->sqlsrv = null;
307 * Called before each db query.
308 * @param string $sql
309 * @param array $params array of parameters
310 * @param int $type type of query
311 * @param mixed $extrainfo driver specific extra information
312 * @return void
314 protected function query_start($sql, array $params = null, $type, $extrainfo = null) {
315 parent::query_start($sql, $params, $type, $extrainfo);
319 * Called immediately after each db query.
320 * @param mixed db specific result
321 * @return void
323 protected function query_end($result) {
324 parent::query_end($result);
328 * Returns database server info array
329 * @return array Array containing 'description', 'version' and 'database' (current db) info
331 public function get_server_info() {
332 static $info;
334 if (!$info) {
335 $server_info = sqlsrv_server_info($this->sqlsrv);
337 if ($server_info) {
338 $info['description'] = $server_info['SQLServerName'];
339 $info['version'] = $server_info['SQLServerVersion'];
340 $info['database'] = $server_info['CurrentDatabase'];
343 return $info;
347 * Override: Converts short table name {tablename} to real table name
348 * supporting temp tables (#) if detected
350 * @param string sql
351 * @return string sql
353 protected function fix_table_names($sql) {
354 if (preg_match_all('/\{([a-z][a-z0-9_]*)\}/i', $sql, $matches)) {
355 foreach ($matches[0] as $key => $match) {
356 $name = $matches[1][$key];
358 if ($this->temptables->is_temptable($name)) {
359 $sql = str_replace($match, $this->temptables->get_correct_name($name), $sql);
360 } else {
361 $sql = str_replace($match, $this->prefix.$name, $sql);
365 return $sql;
369 * Returns supported query parameter types
370 * @return int bitmask
372 protected function allowed_param_types() {
373 return SQL_PARAMS_QM; // sqlsrv 1.1 can bind
377 * Returns last error reported by database engine.
378 * @return string error message
380 public function get_last_error() {
381 $retErrors = sqlsrv_errors(SQLSRV_ERR_ALL);
382 $errorMessage = 'No errors found';
384 if ($retErrors != null) {
385 $errorMessage = '';
387 foreach ($retErrors as $arrError) {
388 $errorMessage .= "SQLState: ".$arrError['SQLSTATE']."<br>\n";
389 $errorMessage .= "Error Code: ".$arrError['code']."<br>\n";
390 $errorMessage .= "Message: ".$arrError['message']."<br>\n";
394 return $errorMessage;
398 * Prepare the query binding and do the actual query.
400 * @param string $sql The sql statement
401 * @param array $params array of params for binding. If NULL, they are ignored.
402 * @param int $sql_query_type - Type of operation
403 * @param bool $free_result - Default true, transaction query will be freed.
404 * @param bool $scrollable - Default false, to use for quickly seeking to target records
405 * @return resource|bool result
407 private function do_query($sql, $params, $sql_query_type, $free_result = true, $scrollable = false) {
408 list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
411 * Bound variables *are* supported. Until I can get it to work, emulate the bindings
412 * The challenge/problem/bug is that although they work, doing a SELECT SCOPE_IDENTITY()
413 * doesn't return a value (no result set)
415 * -- somebody from MS
418 $sql = $this->emulate_bound_params($sql, $params);
419 $this->query_start($sql, $params, $sql_query_type);
420 if (!$scrollable) { // Only supporting next row
421 $result = sqlsrv_query($this->sqlsrv, $sql);
422 } else { // Supporting absolute/relative rows
423 $result = sqlsrv_query($this->sqlsrv, $sql, array(), array('Scrollable' => SQLSRV_CURSOR_STATIC));
426 if ($result === false) {
427 // TODO do something with error or just use if DEV or DEBUG?
428 $dberr = $this->get_last_error();
431 $this->query_end($result);
433 if ($free_result) {
434 $this->free_result($result);
435 return true;
437 return $result;
441 * Return tables in database WITHOUT current prefix.
442 * @param bool $usecache if true, returns list of cached tables.
443 * @return array of table names in lowercase and without prefix
445 public function get_tables($usecache = true) {
446 if ($usecache and $this->tables !== null) {
447 return $this->tables;
449 $this->tables = array ();
450 $prefix = str_replace('_', '\\_', $this->prefix);
451 $sql = "SELECT table_name
452 FROM INFORMATION_SCHEMA.TABLES
453 WHERE table_name LIKE '$prefix%' ESCAPE '\\' AND table_type = 'BASE TABLE'";
455 $this->query_start($sql, null, SQL_QUERY_AUX);
456 $result = sqlsrv_query($this->sqlsrv, $sql);
457 $this->query_end($result);
459 if ($result) {
460 while ($row = sqlsrv_fetch_array($result)) {
461 $tablename = reset($row);
462 if ($this->prefix !== false && $this->prefix !== '') {
463 if (strpos($tablename, $this->prefix) !== 0) {
464 continue;
466 $tablename = substr($tablename, strlen($this->prefix));
468 $this->tables[$tablename] = $tablename;
470 $this->free_result($result);
473 // Add the currently available temptables
474 $this->tables = array_merge($this->tables, $this->temptables->get_temptables());
475 return $this->tables;
479 * Return table indexes - everything lowercased.
480 * @param string $table The table we want to get indexes from.
481 * @return array of arrays
483 public function get_indexes($table) {
484 $indexes = array ();
485 $tablename = $this->prefix.$table;
487 // Indexes aren't covered by information_schema metatables, so we need to
488 // go to sys ones. Skipping primary key indexes on purpose.
489 $sql = "SELECT i.name AS index_name, i.is_unique, ic.index_column_id, c.name AS column_name
490 FROM sys.indexes i
491 JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
492 JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
493 JOIN sys.tables t ON i.object_id = t.object_id
494 WHERE t.name = '$tablename' AND i.is_primary_key = 0
495 ORDER BY i.name, i.index_id, ic.index_column_id";
497 $this->query_start($sql, null, SQL_QUERY_AUX);
498 $result = sqlsrv_query($this->sqlsrv, $sql);
499 $this->query_end($result);
501 if ($result) {
502 $lastindex = '';
503 $unique = false;
504 $columns = array ();
506 while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
507 if ($lastindex and $lastindex != $row['index_name'])
508 { // Save lastindex to $indexes and reset info
509 $indexes[$lastindex] = array
511 'unique' => $unique,
512 'columns' => $columns
515 $unique = false;
516 $columns = array ();
518 $lastindex = $row['index_name'];
519 $unique = empty($row['is_unique']) ? false : true;
520 $columns[] = $row['column_name'];
523 if ($lastindex) { // Add the last one if exists
524 $indexes[$lastindex] = array
526 'unique' => $unique,
527 'columns' => $columns
531 $this->free_result($result);
533 return $indexes;
537 * Returns detailed information about columns in table. This information is cached internally.
538 * @param string $table name
539 * @param bool $usecache
540 * @return array array of database_column_info objects indexed with column names
542 public function get_columns($table, $usecache = true) {
543 if ($usecache) {
544 if ($this->temptables->is_temptable($table)) {
545 if ($data = $this->get_temp_tables_cache()->get($table)) {
546 return $data;
548 } else {
549 if ($data = $this->get_metacache()->get($table)) {
550 return $data;
555 $structure = array();
557 if (!$this->temptables->is_temptable($table)) { // normal table, get metadata from own schema
558 $sql = "SELECT column_name AS name,
559 data_type AS type,
560 numeric_precision AS max_length,
561 character_maximum_length AS char_max_length,
562 numeric_scale AS scale,
563 is_nullable AS is_nullable,
564 columnproperty(object_id(quotename(table_schema) + '.' + quotename(table_name)), column_name, 'IsIdentity') AS auto_increment,
565 column_default AS default_value
566 FROM INFORMATION_SCHEMA.COLUMNS
567 WHERE table_name = '{".$table."}'
568 ORDER BY ordinal_position";
569 } else { // temp table, get metadata from tempdb schema
570 $sql = "SELECT column_name AS name,
571 data_type AS type,
572 numeric_precision AS max_length,
573 character_maximum_length AS char_max_length,
574 numeric_scale AS scale,
575 is_nullable AS is_nullable,
576 columnproperty(object_id(quotename(table_schema) + '.' + quotename(table_name)), column_name, 'IsIdentity') AS auto_increment,
577 column_default AS default_value
578 FROM tempdb.INFORMATION_SCHEMA.COLUMNS ".
579 // check this statement
580 // JOIN tempdb..sysobjects ON name = table_name
581 // WHERE id = object_id('tempdb..{".$table."}')
582 "WHERE table_name LIKE '{".$table."}__________%'
583 ORDER BY ordinal_position";
586 list($sql, $params, $type) = $this->fix_sql_params($sql, null);
588 $this->query_start($sql, null, SQL_QUERY_AUX);
589 $result = sqlsrv_query($this->sqlsrv, $sql);
590 $this->query_end($result);
592 if (!$result) {
593 return array ();
596 while ($rawcolumn = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
598 $rawcolumn = (object)$rawcolumn;
600 $info = new stdClass();
601 $info->name = $rawcolumn->name;
602 $info->type = $rawcolumn->type;
603 $info->meta_type = $this->sqlsrvtype2moodletype($info->type);
605 // Prepare auto_increment info
606 $info->auto_increment = $rawcolumn->auto_increment ? true : false;
608 // Define type for auto_increment columns
609 $info->meta_type = ($info->auto_increment && $info->meta_type == 'I') ? 'R' : $info->meta_type;
611 // id columns being auto_incremnt are PK by definition
612 $info->primary_key = ($info->name == 'id' && $info->meta_type == 'R' && $info->auto_increment);
614 if ($info->meta_type === 'C' and $rawcolumn->char_max_length == -1) {
615 // This is NVARCHAR(MAX), not a normal NVARCHAR.
616 $info->max_length = -1;
617 $info->meta_type = 'X';
618 } else {
619 // Put correct length for character and LOB types
620 $info->max_length = $info->meta_type == 'C' ? $rawcolumn->char_max_length : $rawcolumn->max_length;
621 $info->max_length = ($info->meta_type == 'X' || $info->meta_type == 'B') ? -1 : $info->max_length;
624 // Scale
625 $info->scale = $rawcolumn->scale;
627 // Prepare not_null info
628 $info->not_null = $rawcolumn->is_nullable == 'NO' ? true : false;
630 // Process defaults
631 $info->has_default = !empty($rawcolumn->default_value);
632 if ($rawcolumn->default_value === NULL) {
633 $info->default_value = NULL;
634 } else {
635 $info->default_value = preg_replace("/^[\(N]+[']?(.*?)[']?[\)]+$/", '\\1', $rawcolumn->default_value);
638 // Process binary
639 $info->binary = $info->meta_type == 'B' ? true : false;
641 $structure[$info->name] = new database_column_info($info);
643 $this->free_result($result);
645 if ($usecache) {
646 if ($this->temptables->is_temptable($table)) {
647 $this->get_temp_tables_cache()->set($table, $structure);
648 } else {
649 $this->get_metacache()->set($table, $structure);
653 return $structure;
657 * Normalise values based in RDBMS dependencies (booleans, LOBs...)
659 * @param database_column_info $column column metadata corresponding with the value we are going to normalise
660 * @param mixed $value value we are going to normalise
661 * @return mixed the normalised value
663 protected function normalise_value($column, $value) {
664 $this->detect_objects($value);
666 if (is_bool($value)) { // Always, convert boolean to int
667 $value = (int)$value;
668 } // And continue processing because text columns with numeric info need special handling below
670 if ($column->meta_type == 'B')
671 { // BLOBs need to be properly "packed", but can be inserted directly if so.
672 if (!is_null($value)) { // If value not null, unpack it to unquoted hexadecimal byte-string format
673 $value = unpack('H*hex', $value); // we leave it as array, so emulate_bound_params() can detect it
674 } // easily and "bind" the param ok.
676 } else if ($column->meta_type == 'X') { // sqlsrv doesn't cast from int to text, so if text column
677 if (is_numeric($value)) { // and is numeric value then cast to string
678 $value = array('numstr' => (string)$value); // and put into array, so emulate_bound_params() will know how
679 } // to "bind" the param ok, avoiding reverse conversion to number
680 } else if ($value === '') {
682 if ($column->meta_type == 'I' or $column->meta_type == 'F' or $column->meta_type == 'N') {
683 $value = 0; // prevent '' problems in numeric fields
686 return $value;
690 * Selectively call sqlsrv_free_stmt(), avoiding some warnings without using the horrible @
692 * @param sqlsrv_resource $resource resource to be freed if possible
693 * @return bool
695 private function free_result($resource) {
696 if (!is_bool($resource)) { // true/false resources cannot be freed
697 return sqlsrv_free_stmt($resource);
702 * Provides mapping between sqlsrv native data types and moodle_database - database_column_info - ones)
704 * @param string $sqlsrv_type native sqlsrv data type
705 * @return string 1-char database_column_info data type
707 private function sqlsrvtype2moodletype($sqlsrv_type) {
708 $type = null;
710 switch (strtoupper($sqlsrv_type)) {
711 case 'BIT':
712 $type = 'L';
713 break;
715 case 'INT':
716 case 'SMALLINT':
717 case 'INTEGER':
718 case 'BIGINT':
719 $type = 'I';
720 break;
722 case 'DECIMAL':
723 case 'REAL':
724 case 'FLOAT':
725 $type = 'N';
726 break;
728 case 'VARCHAR':
729 case 'NVARCHAR':
730 $type = 'C';
731 break;
733 case 'TEXT':
734 case 'NTEXT':
735 case 'VARCHAR(MAX)':
736 case 'NVARCHAR(MAX)':
737 $type = 'X';
738 break;
740 case 'IMAGE':
741 case 'VARBINARY':
742 case 'VARBINARY(MAX)':
743 $type = 'B';
744 break;
746 case 'DATETIME':
747 $type = 'D';
748 break;
751 if (!$type) {
752 throw new dml_exception('invalidsqlsrvnativetype', $sqlsrv_type);
754 return $type;
758 * Do NOT use in code, to be used by database_manager only!
759 * @param string|array $sql query
760 * @param array|null $tablenames an array of xmldb table names affected by this request.
761 * @return bool true
762 * @throws ddl_change_structure_exception A DDL specific exception is thrown for any errors.
764 public function change_database_structure($sql, $tablenames = null) {
765 $this->get_manager(); // Includes DDL exceptions classes ;-)
766 $sqls = (array)$sql;
768 try {
769 foreach ($sqls as $sql) {
770 $this->query_start($sql, null, SQL_QUERY_STRUCTURE);
771 $result = sqlsrv_query($this->sqlsrv, $sql);
772 $this->query_end($result);
774 } catch (ddl_change_structure_exception $e) {
775 $this->reset_caches($tablenames);
776 throw $e;
779 $this->reset_caches($tablenames);
780 return true;
784 * Prepare the array of params for native binding
786 protected function build_native_bound_params(array $params = null) {
788 return null;
792 * Workaround for SQL*Server Native driver similar to MSSQL driver for
793 * consistent behavior.
795 protected function emulate_bound_params($sql, array $params = null) {
797 if (empty($params)) {
798 return $sql;
800 // ok, we have verified sql statement with ? and correct number of params
801 $parts = array_reverse(explode('?', $sql));
802 $return = array_pop($parts);
803 foreach ($params as $param) {
804 if (is_bool($param)) {
805 $return .= (int)$param;
806 } else if (is_array($param) && isset($param['hex'])) { // detect hex binary, bind it specially
807 $return .= '0x'.$param['hex'];
808 } else if (is_array($param) && isset($param['numstr'])) { // detect numerical strings that *must not*
809 $return .= "N'{$param['numstr']}'"; // be converted back to number params, but bound as strings
810 } else if (is_null($param)) {
811 $return .= 'NULL';
813 } else if (is_number($param)) { // we can not use is_numeric() because it eats leading zeros from strings like 0045646
814 $return .= "'$param'"; // this is a hack for MDL-23997, we intentionally use string because it is compatible with both nvarchar and int types
815 } else if (is_float($param)) {
816 $return .= $param;
817 } else {
818 $param = str_replace("'", "''", $param);
819 $param = str_replace("\0", "", $param);
820 $return .= "N'$param'";
823 $return .= array_pop($parts);
825 return $return;
829 * Execute general sql query. Should be used only when no other method suitable.
830 * Do NOT use this to make changes in db structure, use database_manager methods instead!
831 * @param string $sql query
832 * @param array $params query parameters
833 * @return bool true
834 * @throws dml_exception A DML specific exception is thrown for any errors.
836 public function execute($sql, array $params = null) {
837 if (strpos($sql, ';') !== false) {
838 throw new coding_exception('moodle_database::execute() Multiple sql statements found or bound parameters not used properly in query!');
840 $this->do_query($sql, $params, SQL_QUERY_UPDATE);
841 return true;
845 * Get a number of records as a moodle_recordset using a SQL statement.
847 * Since this method is a little less readable, use of it should be restricted to
848 * code where it's possible there might be large datasets being returned. For known
849 * small datasets use get_records_sql - it leads to simpler code.
851 * The return type is like:
852 * @see function get_recordset.
854 * @param string $sql the SQL select query to execute.
855 * @param array $params array of sql parameters
856 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
857 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
858 * @return moodle_recordset instance
859 * @throws dml_exception A DML specific exception is thrown for any errors.
861 public function get_recordset_sql($sql, array $params = null, $limitfrom = 0, $limitnum = 0) {
863 list($limitfrom, $limitnum) = $this->normalise_limit_from_num($limitfrom, $limitnum);
864 $needscrollable = (bool)$limitfrom; // To determine if we'll need to perform scroll to $limitfrom.
866 if ($limitfrom or $limitnum) {
867 if (!$this->supportsoffsetfetch) {
868 if ($limitnum >= 1) { // Only apply TOP clause if we have any limitnum (limitfrom offset is handled later).
869 $fetch = $limitfrom + $limitnum;
870 if (PHP_INT_MAX - $limitnum < $limitfrom) { // Check PHP_INT_MAX overflow.
871 $fetch = PHP_INT_MAX;
873 $sql = preg_replace('/^([\s(])*SELECT([\s]+(DISTINCT|ALL))?(?!\s*TOP\s*\()/i',
874 "\\1SELECT\\2 TOP $fetch", $sql);
876 } else {
877 $needscrollable = false; // Using supported fetch/offset, no need to scroll anymore.
878 $sql = (substr($sql, -1) === ';') ? substr($sql, 0, -1) : $sql;
879 // We need order by to use FETCH/OFFSET.
880 // Ordering by first column shouldn't break anything if there was no order in the first place.
881 if (!strpos(strtoupper($sql), "ORDER BY")) {
882 $sql .= " ORDER BY 1";
885 $sql .= " OFFSET ".$limitfrom." ROWS ";
887 if ($limitnum > 0) {
888 $sql .= " FETCH NEXT ".$limitnum." ROWS ONLY";
893 // Add WITH (NOLOCK) to any temp tables.
894 $sql = $this->add_no_lock_to_temp_tables($sql);
896 $result = $this->do_query($sql, $params, SQL_QUERY_SELECT, false, $needscrollable);
898 if ($needscrollable) { // Skip $limitfrom records.
899 sqlsrv_fetch($result, SQLSRV_SCROLL_ABSOLUTE, $limitfrom - 1);
901 return $this->create_recordset($result);
905 * Use NOLOCK on any temp tables. Since it's a temp table and uncommitted reads are low risk anyway.
907 * @param string $sql the SQL select query to execute.
908 * @return string The SQL, with WITH (NOLOCK) added to all temp tables
910 protected function add_no_lock_to_temp_tables($sql) {
911 return preg_replace_callback('/(\{([a-z][a-z0-9_]*)\})(\s+(\w+))?/', function($matches) {
912 $table = $matches[1]; // With the braces, so we can put it back in the query.
913 $name = $matches[2]; // Without the braces, so we can check if it's a temptable.
914 $tail = isset($matches[3]) ? $matches[3] : ''; // Catch the next word afterwards so that we can check if it's an alias.
915 $replacement = $matches[0]; // The table and the word following it, so we can replace it back if no changes are needed.
917 if ($this->temptables && $this->temptables->is_temptable($name)) {
918 if (!empty($tail)) {
919 if (in_array(strtolower(trim($tail)), $this->reservewords)) {
920 // If the table is followed by a reserve word, it's not an alias so put the WITH (NOLOCK) in between.
921 return $table . ' WITH (NOLOCK)' . $tail;
924 // If the table is not followed by a reserve word, put the WITH (NOLOCK) after the whole match.
925 return $replacement . ' WITH (NOLOCK)';
926 } else {
927 return $replacement;
929 }, $sql);
933 * Create a record set and initialize with first row
935 * @param mixed $result
936 * @return sqlsrv_native_moodle_recordset
938 protected function create_recordset($result) {
939 $rs = new sqlsrv_native_moodle_recordset($result, $this);
940 $this->recordsets[] = $rs;
941 return $rs;
945 * Do not use outside of recordset class.
946 * @internal
947 * @param sqlsrv_native_moodle_recordset $rs
949 public function recordset_closed(sqlsrv_native_moodle_recordset $rs) {
950 if ($key = array_search($rs, $this->recordsets, true)) {
951 unset($this->recordsets[$key]);
956 * Get a number of records as an array of objects using a SQL statement.
958 * Return value is like:
959 * @see function get_records.
961 * @param string $sql the SQL select query to execute. The first column of this SELECT statement
962 * must be a unique value (usually the 'id' field), as it will be used as the key of the
963 * returned array.
964 * @param array $params array of sql parameters
965 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
966 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
967 * @return array of objects, or empty array if no records were found
968 * @throws dml_exception A DML specific exception is thrown for any errors.
970 public function get_records_sql($sql, array $params = null, $limitfrom = 0, $limitnum = 0) {
972 $rs = $this->get_recordset_sql($sql, $params, $limitfrom, $limitnum);
974 $results = array();
976 foreach ($rs as $row) {
977 $id = reset($row);
979 if (isset($results[$id])) {
980 $colname = key($row);
981 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);
983 $results[$id] = (object)$row;
985 $rs->close();
987 return $results;
991 * Selects records and return values (first field) as an array using a SQL statement.
993 * @param string $sql The SQL query
994 * @param array $params array of sql parameters
995 * @return array of values
996 * @throws dml_exception A DML specific exception is thrown for any errors.
998 public function get_fieldset_sql($sql, array $params = null) {
1000 $rs = $this->get_recordset_sql($sql, $params);
1002 $results = array ();
1004 foreach ($rs as $row) {
1005 $results[] = reset($row);
1007 $rs->close();
1009 return $results;
1013 * Insert new record into database, as fast as possible, no safety checks, lobs not supported.
1014 * @param string $table name
1015 * @param mixed $params data record as object or array
1016 * @param bool $returnit return it of inserted record
1017 * @param bool $bulk true means repeated inserts expected
1018 * @param bool $customsequence true if 'id' included in $params, disables $returnid
1019 * @return bool|int true or new id
1020 * @throws dml_exception A DML specific exception is thrown for any errors.
1022 public function insert_record_raw($table, $params, $returnid=true, $bulk=false, $customsequence=false) {
1023 if (!is_array($params)) {
1024 $params = (array)$params;
1027 $isidentity = false;
1029 if ($customsequence) {
1030 if (!isset($params['id'])) {
1031 throw new coding_exception('moodle_database::insert_record_raw() id field must be specified if custom sequences used.');
1034 $returnid = false;
1035 $columns = $this->get_columns($table);
1036 if (isset($columns['id']) and $columns['id']->auto_increment) {
1037 $isidentity = true;
1040 // Disable IDENTITY column before inserting record with id, only if the
1041 // column is identity, from meta information.
1042 if ($isidentity) {
1043 $sql = 'SET IDENTITY_INSERT {'.$table.'} ON'; // Yes, it' ON!!
1044 $this->do_query($sql, null, SQL_QUERY_AUX);
1047 } else {
1048 unset($params['id']);
1051 if (empty($params)) {
1052 throw new coding_exception('moodle_database::insert_record_raw() no fields found.');
1054 $fields = implode(',', array_keys($params));
1055 $qms = array_fill(0, count($params), '?');
1056 $qms = implode(',', $qms);
1057 $sql = "INSERT INTO {" . $table . "} ($fields) VALUES($qms)";
1058 $query_id = $this->do_query($sql, $params, SQL_QUERY_INSERT);
1060 if ($customsequence) {
1061 // Enable IDENTITY column after inserting record with id, only if the
1062 // column is identity, from meta information.
1063 if ($isidentity) {
1064 $sql = 'SET IDENTITY_INSERT {'.$table.'} OFF'; // Yes, it' OFF!!
1065 $this->do_query($sql, null, SQL_QUERY_AUX);
1069 if ($returnid) {
1070 $id = $this->sqlsrv_fetch_id();
1071 return $id;
1072 } else {
1073 return true;
1078 * Get the ID of the current action
1080 * @return mixed ID
1082 private function sqlsrv_fetch_id() {
1083 $query_id = sqlsrv_query($this->sqlsrv, 'SELECT SCOPE_IDENTITY()');
1084 if ($query_id === false) {
1085 $dberr = $this->get_last_error();
1086 return false;
1088 $row = $this->sqlsrv_fetchrow($query_id);
1089 return (int)$row[0];
1093 * Fetch a single row into an numbered array
1095 * @param mixed $query_id
1097 private function sqlsrv_fetchrow($query_id) {
1098 $row = sqlsrv_fetch_array($query_id, SQLSRV_FETCH_NUMERIC);
1099 if ($row === false) {
1100 $dberr = $this->get_last_error();
1101 return false;
1104 foreach ($row as $key => $value) {
1105 $row[$key] = ($value === ' ' || $value === NULL) ? '' : $value;
1107 return $row;
1111 * Insert a record into a table and return the "id" field if required.
1113 * Some conversions and safety checks are carried out. Lobs are supported.
1114 * If the return ID isn't required, then this just reports success as true/false.
1115 * $data is an object containing needed data
1116 * @param string $table The database table to be inserted into
1117 * @param object $data A data object with values for one or more fields in the record
1118 * @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.
1119 * @return bool|int true or new id
1120 * @throws dml_exception A DML specific exception is thrown for any errors.
1122 public function insert_record($table, $dataobject, $returnid = true, $bulk = false) {
1123 $dataobject = (array)$dataobject;
1125 $columns = $this->get_columns($table);
1126 if (empty($columns)) {
1127 throw new dml_exception('ddltablenotexist', $table);
1130 $cleaned = array ();
1132 foreach ($dataobject as $field => $value) {
1133 if ($field === 'id') {
1134 continue;
1136 if (!isset($columns[$field])) {
1137 continue;
1139 $column = $columns[$field];
1140 $cleaned[$field] = $this->normalise_value($column, $value);
1143 return $this->insert_record_raw($table, $cleaned, $returnid, $bulk);
1147 * Import a record into a table, id field is required.
1148 * Safety checks are NOT carried out. Lobs are supported.
1150 * @param string $table name of database table to be inserted into
1151 * @param object $dataobject A data object with values for one or more fields in the record
1152 * @return bool true
1153 * @throws dml_exception A DML specific exception is thrown for any errors.
1155 public function import_record($table, $dataobject) {
1156 if (!is_object($dataobject)) {
1157 $dataobject = (object)$dataobject;
1160 $columns = $this->get_columns($table);
1161 $cleaned = array ();
1163 foreach ($dataobject as $field => $value) {
1164 if (!isset($columns[$field])) {
1165 continue;
1167 $column = $columns[$field];
1168 $cleaned[$field] = $this->normalise_value($column, $value);
1171 $this->insert_record_raw($table, $cleaned, false, false, true);
1173 return true;
1177 * Update record in database, as fast as possible, no safety checks, lobs not supported.
1178 * @param string $table name
1179 * @param mixed $params data record as object or array
1180 * @param bool true means repeated updates expected
1181 * @return bool true
1182 * @throws dml_exception A DML specific exception is thrown for any errors.
1184 public function update_record_raw($table, $params, $bulk = false) {
1185 $params = (array)$params;
1187 if (!isset($params['id'])) {
1188 throw new coding_exception('moodle_database::update_record_raw() id field must be specified.');
1190 $id = $params['id'];
1191 unset($params['id']);
1193 if (empty($params)) {
1194 throw new coding_exception('moodle_database::update_record_raw() no fields found.');
1197 $sets = array ();
1199 foreach ($params as $field => $value) {
1200 $sets[] = "$field = ?";
1203 $params[] = $id; // last ? in WHERE condition
1205 $sets = implode(',', $sets);
1206 $sql = "UPDATE {".$table."} SET $sets WHERE id = ?";
1208 $this->do_query($sql, $params, SQL_QUERY_UPDATE);
1210 return true;
1214 * Update a record in a table
1216 * $dataobject is an object containing needed data
1217 * Relies on $dataobject having a variable "id" to
1218 * specify the record to update
1220 * @param string $table The database table to be checked against.
1221 * @param object $dataobject An object with contents equal to fieldname=>fieldvalue. Must have an entry for 'id' to map to the table specified.
1222 * @param bool true means repeated updates expected
1223 * @return bool true
1224 * @throws dml_exception A DML specific exception is thrown for any errors.
1226 public function update_record($table, $dataobject, $bulk = false) {
1227 $dataobject = (array)$dataobject;
1229 $columns = $this->get_columns($table);
1230 $cleaned = array ();
1232 foreach ($dataobject as $field => $value) {
1233 if (!isset($columns[$field])) {
1234 continue;
1236 $column = $columns[$field];
1237 $cleaned[$field] = $this->normalise_value($column, $value);
1240 return $this->update_record_raw($table, $cleaned, $bulk);
1244 * Set a single field in every table record which match a particular WHERE clause.
1246 * @param string $table The database table to be checked against.
1247 * @param string $newfield the field to set.
1248 * @param string $newvalue the value to set the field to.
1249 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1250 * @param array $params array of sql parameters
1251 * @return bool true
1252 * @throws dml_exception A DML specific exception is thrown for any errors.
1254 public function set_field_select($table, $newfield, $newvalue, $select, array $params = null) {
1255 if ($select) {
1256 $select = "WHERE $select";
1259 if (is_null($params)) {
1260 $params = array ();
1263 // convert params to ? types
1264 list($select, $params, $type) = $this->fix_sql_params($select, $params);
1266 // Get column metadata
1267 $columns = $this->get_columns($table);
1268 $column = $columns[$newfield];
1270 $newvalue = $this->normalise_value($column, $newvalue);
1272 if (is_null($newvalue)) {
1273 $newfield = "$newfield = NULL";
1274 } else {
1275 $newfield = "$newfield = ?";
1276 array_unshift($params, $newvalue);
1278 $sql = "UPDATE {".$table."} SET $newfield $select";
1280 $this->do_query($sql, $params, SQL_QUERY_UPDATE);
1282 return true;
1286 * Delete one or more records from a table which match a particular WHERE clause.
1288 * @param string $table The database table to be checked against.
1289 * @param string $select A fragment of SQL to be used in a where clause in the SQL call (used to define the selection criteria).
1290 * @param array $params array of sql parameters
1291 * @return bool true
1292 * @throws dml_exception A DML specific exception is thrown for any errors.
1294 public function delete_records_select($table, $select, array $params = null) {
1295 if ($select) {
1296 $select = "WHERE $select";
1299 $sql = "DELETE FROM {".$table."} $select";
1301 // we use SQL_QUERY_UPDATE because we do not know what is in general SQL, delete constant would not be accurate
1302 $this->do_query($sql, $params, SQL_QUERY_UPDATE);
1304 return true;
1308 public function sql_cast_char2int($fieldname, $text = false) {
1309 if (!$text) {
1310 return ' CAST(' . $fieldname . ' AS INT) ';
1311 } else {
1312 return ' CAST(' . $this->sql_compare_text($fieldname) . ' AS INT) ';
1316 public function sql_cast_char2real($fieldname, $text=false) {
1317 if (!$text) {
1318 return ' CAST(' . $fieldname . ' AS REAL) ';
1319 } else {
1320 return ' CAST(' . $this->sql_compare_text($fieldname) . ' AS REAL) ';
1324 public function sql_ceil($fieldname) {
1325 return ' CEILING('.$fieldname.')';
1328 protected function get_collation() {
1329 if (isset($this->collation)) {
1330 return $this->collation;
1332 if (!empty($this->dboptions['dbcollation'])) {
1333 // perf speedup
1334 $this->collation = $this->dboptions['dbcollation'];
1335 return $this->collation;
1338 // make some default
1339 $this->collation = 'Latin1_General_CI_AI';
1341 $sql = "SELECT CAST(DATABASEPROPERTYEX('$this->dbname', 'Collation') AS varchar(255)) AS SQLCollation";
1342 $this->query_start($sql, null, SQL_QUERY_AUX);
1343 $result = sqlsrv_query($this->sqlsrv, $sql);
1344 $this->query_end($result);
1346 if ($result) {
1347 if ($rawcolumn = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
1348 $this->collation = reset($rawcolumn);
1350 $this->free_result($result);
1353 return $this->collation;
1356 public function sql_equal($fieldname, $param, $casesensitive = true, $accentsensitive = true, $notequal = false) {
1357 $equalop = $notequal ? '<>' : '=';
1358 $collation = $this->get_collation();
1360 if ($casesensitive) {
1361 $collation = str_replace('_CI', '_CS', $collation);
1362 } else {
1363 $collation = str_replace('_CS', '_CI', $collation);
1365 if ($accentsensitive) {
1366 $collation = str_replace('_AI', '_AS', $collation);
1367 } else {
1368 $collation = str_replace('_AS', '_AI', $collation);
1371 return "$fieldname COLLATE $collation $equalop $param";
1375 * Returns 'LIKE' part of a query.
1377 * @param string $fieldname usually name of the table column
1378 * @param string $param usually bound query parameter (?, :named)
1379 * @param bool $casesensitive use case sensitive search
1380 * @param bool $accensensitive use accent sensitive search (not all databases support accent insensitive)
1381 * @param bool $notlike true means "NOT LIKE"
1382 * @param string $escapechar escape char for '%' and '_'
1383 * @return string SQL code fragment
1385 public function sql_like($fieldname, $param, $casesensitive = true, $accentsensitive = true, $notlike = false, $escapechar = '\\') {
1386 if (strpos($param, '%') !== false) {
1387 debugging('Potential SQL injection detected, sql_like() expects bound parameters (? or :named)');
1390 $collation = $this->get_collation();
1391 $LIKE = $notlike ? 'NOT LIKE' : 'LIKE';
1393 if ($casesensitive) {
1394 $collation = str_replace('_CI', '_CS', $collation);
1395 } else {
1396 $collation = str_replace('_CS', '_CI', $collation);
1398 if ($accentsensitive) {
1399 $collation = str_replace('_AI', '_AS', $collation);
1400 } else {
1401 $collation = str_replace('_AS', '_AI', $collation);
1404 return "$fieldname COLLATE $collation $LIKE $param ESCAPE '$escapechar'";
1407 public function sql_concat() {
1408 $arr = func_get_args();
1410 foreach ($arr as $key => $ele) {
1411 $arr[$key] = ' CAST('.$ele.' AS NVARCHAR(255)) ';
1413 $s = implode(' + ', $arr);
1415 if ($s === '') {
1416 return " '' ";
1418 return " $s ";
1421 public function sql_concat_join($separator = "' '", $elements = array ()) {
1422 for ($n = count($elements) - 1; $n > 0; $n--) {
1423 array_splice($elements, $n, 0, $separator);
1425 return call_user_func_array(array($this, 'sql_concat'), $elements);
1428 public function sql_isempty($tablename, $fieldname, $nullablefield, $textfield) {
1429 if ($textfield) {
1430 return ' ('.$this->sql_compare_text($fieldname)." = '') ";
1431 } else {
1432 return " ($fieldname = '') ";
1437 * Returns the SQL text to be used to calculate the length in characters of one expression.
1438 * @param string fieldname or expression to calculate its length in characters.
1439 * @return string the piece of SQL code to be used in the statement.
1441 public function sql_length($fieldname) {
1442 return ' LEN('.$fieldname.')';
1445 public function sql_order_by_text($fieldname, $numchars = 32) {
1446 return " CONVERT(varchar({$numchars}), {$fieldname})";
1450 * Returns the SQL for returning searching one string for the location of another.
1452 public function sql_position($needle, $haystack) {
1453 return "CHARINDEX(($needle), ($haystack))";
1457 * Returns the proper substr() SQL text used to extract substrings from DB
1458 * NOTE: this was originally returning only function name
1460 * @param string $expr some string field, no aggregates
1461 * @param mixed $start integer or expression evaluating to int
1462 * @param mixed $length optional integer or expression evaluating to int
1463 * @return string sql fragment
1465 public function sql_substr($expr, $start, $length = false) {
1466 if (count(func_get_args()) < 2) {
1467 throw new coding_exception('moodle_database::sql_substr() requires at least two parameters',
1468 'Originally this function was only returning name of SQL substring function, it now requires all parameters.');
1471 if ($length === false) {
1472 return "SUBSTRING($expr, " . $this->sql_cast_char2int($start) . ", 2^31-1)";
1473 } else {
1474 return "SUBSTRING($expr, " . $this->sql_cast_char2int($start) . ", " . $this->sql_cast_char2int($length) . ")";
1479 * Does this driver support tool_replace?
1481 * @since Moodle 2.6.1
1482 * @return bool
1484 public function replace_all_text_supported() {
1485 return true;
1488 public function session_lock_supported() {
1489 return true;
1493 * Obtain session lock
1494 * @param int $rowid id of the row with session record
1495 * @param int $timeout max allowed time to wait for the lock in seconds
1496 * @return void
1498 public function get_session_lock($rowid, $timeout) {
1499 if (!$this->session_lock_supported()) {
1500 return;
1502 parent::get_session_lock($rowid, $timeout);
1504 $timeoutmilli = $timeout * 1000;
1506 $fullname = $this->dbname.'-'.$this->prefix.'-session-'.$rowid;
1507 // While this may work using proper {call sp_...} calls + binding +
1508 // executing + consuming recordsets, the solution used for the mssql
1509 // driver is working perfectly, so 100% mimic-ing that code.
1510 // $sql = "sp_getapplock '$fullname', 'Exclusive', 'Session', $timeoutmilli";
1511 $sql = "BEGIN
1512 DECLARE @result INT
1513 EXECUTE @result = sp_getapplock @Resource='$fullname',
1514 @LockMode='Exclusive',
1515 @LockOwner='Session',
1516 @LockTimeout='$timeoutmilli'
1517 SELECT @result
1518 END";
1519 $this->query_start($sql, null, SQL_QUERY_AUX);
1520 $result = sqlsrv_query($this->sqlsrv, $sql);
1521 $this->query_end($result);
1523 if ($result) {
1524 $row = sqlsrv_fetch_array($result);
1525 if ($row[0] < 0) {
1526 throw new dml_sessionwait_exception();
1530 $this->free_result($result);
1533 public function release_session_lock($rowid) {
1534 if (!$this->session_lock_supported()) {
1535 return;
1537 if (!$this->used_for_db_sessions) {
1538 return;
1541 parent::release_session_lock($rowid);
1543 $fullname = $this->dbname.'-'.$this->prefix.'-session-'.$rowid;
1544 $sql = "sp_releaseapplock '$fullname', 'Session'";
1545 $this->query_start($sql, null, SQL_QUERY_AUX);
1546 $result = sqlsrv_query($this->sqlsrv, $sql);
1547 $this->query_end($result);
1548 $this->free_result($result);
1552 * Driver specific start of real database transaction,
1553 * this can not be used directly in code.
1554 * @return void
1556 protected function begin_transaction() {
1557 // Recordsets do not work well with transactions in SQL Server,
1558 // let's prefetch the recordsets to memory to work around these problems.
1559 foreach ($this->recordsets as $rs) {
1560 $rs->transaction_starts();
1563 $this->query_start('native sqlsrv_begin_transaction', NULL, SQL_QUERY_AUX);
1564 $result = sqlsrv_begin_transaction($this->sqlsrv);
1565 $this->query_end($result);
1569 * Driver specific commit of real database transaction,
1570 * this can not be used directly in code.
1571 * @return void
1573 protected function commit_transaction() {
1574 $this->query_start('native sqlsrv_commit', NULL, SQL_QUERY_AUX);
1575 $result = sqlsrv_commit($this->sqlsrv);
1576 $this->query_end($result);
1580 * Driver specific abort of real database transaction,
1581 * this can not be used directly in code.
1582 * @return void
1584 protected function rollback_transaction() {
1585 $this->query_start('native sqlsrv_rollback', NULL, SQL_QUERY_AUX);
1586 $result = sqlsrv_rollback($this->sqlsrv);
1587 $this->query_end($result);
1591 * Is fulltext search enabled?.
1593 * @return bool
1595 public function is_fulltext_search_supported() {
1596 global $CFG;
1598 $sql = "SELECT FULLTEXTSERVICEPROPERTY('IsFullTextInstalled')";
1599 $this->query_start($sql, null, SQL_QUERY_AUX);
1600 $result = sqlsrv_query($this->sqlsrv, $sql);
1601 $this->query_end($result);
1602 if ($result) {
1603 if ($row = sqlsrv_fetch_array($result)) {
1604 $property = (bool)reset($row);
1607 $this->free_result($result);
1609 return !empty($property);