Merge branch 'MDL-67410-37' of https://github.com/felicemcc/moodle into MOODLE_37_STABLE
[moodle.git] / lib / dml / sqlsrv_native_moodle_database.php
bloba91317dc71d10640a6b73e4719c5ed13d6143fe1
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 * Whether the given SQL statement has the ORDER BY clause in the main query.
847 * @param string $sql the SQL statement
848 * @return bool true if the main query has the ORDER BY clause; otherwise, false.
850 protected static function has_query_order_by(string $sql) {
851 $sqltoupper = strtoupper($sql);
852 // Fail fast if there is no ORDER BY clause in the original query.
853 if (strpos($sqltoupper, 'ORDER BY') === false) {
854 return false;
857 // Search for an ORDER BY clause in the main query, not in any subquery (not always allowed in MSSQL)
858 // or in clauses like OVER with a window function e.g. ROW_NUMBER() OVER (ORDER BY ...) or RANK() OVER (ORDER BY ...):
859 // use PHP PCRE recursive patterns to remove everything found within round brackets.
860 $mainquery = preg_replace('/\(((?>[^()]+)|(?R))*\)/', '()', $sqltoupper);
861 if (strpos($mainquery, 'ORDER BY') !== false) {
862 return true;
865 return false;
869 * Get a number of records as a moodle_recordset using a SQL statement.
871 * Since this method is a little less readable, use of it should be restricted to
872 * code where it's possible there might be large datasets being returned. For known
873 * small datasets use get_records_sql - it leads to simpler code.
875 * The return type is like:
876 * @see function get_recordset.
878 * @param string $sql the SQL select query to execute.
879 * @param array $params array of sql parameters
880 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
881 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
882 * @return moodle_recordset instance
883 * @throws dml_exception A DML specific exception is thrown for any errors.
885 public function get_recordset_sql($sql, array $params = null, $limitfrom = 0, $limitnum = 0) {
887 list($limitfrom, $limitnum) = $this->normalise_limit_from_num($limitfrom, $limitnum);
888 $needscrollable = (bool)$limitfrom; // To determine if we'll need to perform scroll to $limitfrom.
890 if ($limitfrom or $limitnum) {
891 if (!$this->supportsoffsetfetch) {
892 if ($limitnum >= 1) { // Only apply TOP clause if we have any limitnum (limitfrom offset is handled later).
893 $fetch = $limitfrom + $limitnum;
894 if (PHP_INT_MAX - $limitnum < $limitfrom) { // Check PHP_INT_MAX overflow.
895 $fetch = PHP_INT_MAX;
897 $sql = preg_replace('/^([\s(])*SELECT([\s]+(DISTINCT|ALL))?(?!\s*TOP\s*\()/i',
898 "\\1SELECT\\2 TOP $fetch", $sql);
900 } else {
901 $needscrollable = false; // Using supported fetch/offset, no need to scroll anymore.
902 $sql = (substr($sql, -1) === ';') ? substr($sql, 0, -1) : $sql;
903 // We need ORDER BY to use FETCH/OFFSET.
904 // Ordering by first column shouldn't break anything if there was no order in the first place.
905 if (!self::has_query_order_by($sql)) {
906 $sql .= " ORDER BY 1";
909 $sql .= " OFFSET ".$limitfrom." ROWS ";
911 if ($limitnum > 0) {
912 $sql .= " FETCH NEXT ".$limitnum." ROWS ONLY";
917 // Add WITH (NOLOCK) to any temp tables.
918 $sql = $this->add_no_lock_to_temp_tables($sql);
920 $result = $this->do_query($sql, $params, SQL_QUERY_SELECT, false, $needscrollable);
922 if ($needscrollable) { // Skip $limitfrom records.
923 sqlsrv_fetch($result, SQLSRV_SCROLL_ABSOLUTE, $limitfrom - 1);
925 return $this->create_recordset($result);
929 * Use NOLOCK on any temp tables. Since it's a temp table and uncommitted reads are low risk anyway.
931 * @param string $sql the SQL select query to execute.
932 * @return string The SQL, with WITH (NOLOCK) added to all temp tables
934 protected function add_no_lock_to_temp_tables($sql) {
935 return preg_replace_callback('/(\{([a-z][a-z0-9_]*)\})(\s+(\w+))?/', function($matches) {
936 $table = $matches[1]; // With the braces, so we can put it back in the query.
937 $name = $matches[2]; // Without the braces, so we can check if it's a temptable.
938 $tail = isset($matches[3]) ? $matches[3] : ''; // Catch the next word afterwards so that we can check if it's an alias.
939 $replacement = $matches[0]; // The table and the word following it, so we can replace it back if no changes are needed.
941 if ($this->temptables && $this->temptables->is_temptable($name)) {
942 if (!empty($tail)) {
943 if (in_array(strtolower(trim($tail)), $this->reservewords)) {
944 // If the table is followed by a reserve word, it's not an alias so put the WITH (NOLOCK) in between.
945 return $table . ' WITH (NOLOCK)' . $tail;
948 // If the table is not followed by a reserve word, put the WITH (NOLOCK) after the whole match.
949 return $replacement . ' WITH (NOLOCK)';
950 } else {
951 return $replacement;
953 }, $sql);
957 * Create a record set and initialize with first row
959 * @param mixed $result
960 * @return sqlsrv_native_moodle_recordset
962 protected function create_recordset($result) {
963 $rs = new sqlsrv_native_moodle_recordset($result, $this);
964 $this->recordsets[] = $rs;
965 return $rs;
969 * Do not use outside of recordset class.
970 * @internal
971 * @param sqlsrv_native_moodle_recordset $rs
973 public function recordset_closed(sqlsrv_native_moodle_recordset $rs) {
974 if ($key = array_search($rs, $this->recordsets, true)) {
975 unset($this->recordsets[$key]);
980 * Get a number of records as an array of objects using a SQL statement.
982 * Return value is like:
983 * @see function get_records.
985 * @param string $sql the SQL select query to execute. The first column of this SELECT statement
986 * must be a unique value (usually the 'id' field), as it will be used as the key of the
987 * returned array.
988 * @param array $params array of sql parameters
989 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
990 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
991 * @return array of objects, or empty array if no records were found
992 * @throws dml_exception A DML specific exception is thrown for any errors.
994 public function get_records_sql($sql, array $params = null, $limitfrom = 0, $limitnum = 0) {
996 $rs = $this->get_recordset_sql($sql, $params, $limitfrom, $limitnum);
998 $results = array();
1000 foreach ($rs as $row) {
1001 $id = reset($row);
1003 if (isset($results[$id])) {
1004 $colname = key($row);
1005 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);
1007 $results[$id] = (object)$row;
1009 $rs->close();
1011 return $results;
1015 * Selects records and return values (first field) as an array using a SQL statement.
1017 * @param string $sql The SQL query
1018 * @param array $params array of sql parameters
1019 * @return array of values
1020 * @throws dml_exception A DML specific exception is thrown for any errors.
1022 public function get_fieldset_sql($sql, array $params = null) {
1024 $rs = $this->get_recordset_sql($sql, $params);
1026 $results = array ();
1028 foreach ($rs as $row) {
1029 $results[] = reset($row);
1031 $rs->close();
1033 return $results;
1037 * Insert new record into database, as fast as possible, no safety checks, lobs not supported.
1038 * @param string $table name
1039 * @param mixed $params data record as object or array
1040 * @param bool $returnit return it of inserted record
1041 * @param bool $bulk true means repeated inserts expected
1042 * @param bool $customsequence true if 'id' included in $params, disables $returnid
1043 * @return bool|int true or new id
1044 * @throws dml_exception A DML specific exception is thrown for any errors.
1046 public function insert_record_raw($table, $params, $returnid=true, $bulk=false, $customsequence=false) {
1047 if (!is_array($params)) {
1048 $params = (array)$params;
1051 $isidentity = false;
1053 if ($customsequence) {
1054 if (!isset($params['id'])) {
1055 throw new coding_exception('moodle_database::insert_record_raw() id field must be specified if custom sequences used.');
1058 $returnid = false;
1059 $columns = $this->get_columns($table);
1060 if (isset($columns['id']) and $columns['id']->auto_increment) {
1061 $isidentity = true;
1064 // Disable IDENTITY column before inserting record with id, only if the
1065 // column is identity, from meta information.
1066 if ($isidentity) {
1067 $sql = 'SET IDENTITY_INSERT {'.$table.'} ON'; // Yes, it' ON!!
1068 $this->do_query($sql, null, SQL_QUERY_AUX);
1071 } else {
1072 unset($params['id']);
1075 if (empty($params)) {
1076 throw new coding_exception('moodle_database::insert_record_raw() no fields found.');
1078 $fields = implode(',', array_keys($params));
1079 $qms = array_fill(0, count($params), '?');
1080 $qms = implode(',', $qms);
1081 $sql = "INSERT INTO {" . $table . "} ($fields) VALUES($qms)";
1082 $query_id = $this->do_query($sql, $params, SQL_QUERY_INSERT);
1084 if ($customsequence) {
1085 // Enable IDENTITY column after inserting record with id, only if the
1086 // column is identity, from meta information.
1087 if ($isidentity) {
1088 $sql = 'SET IDENTITY_INSERT {'.$table.'} OFF'; // Yes, it' OFF!!
1089 $this->do_query($sql, null, SQL_QUERY_AUX);
1093 if ($returnid) {
1094 $id = $this->sqlsrv_fetch_id();
1095 return $id;
1096 } else {
1097 return true;
1102 * Get the ID of the current action
1104 * @return mixed ID
1106 private function sqlsrv_fetch_id() {
1107 $query_id = sqlsrv_query($this->sqlsrv, 'SELECT SCOPE_IDENTITY()');
1108 if ($query_id === false) {
1109 $dberr = $this->get_last_error();
1110 return false;
1112 $row = $this->sqlsrv_fetchrow($query_id);
1113 return (int)$row[0];
1117 * Fetch a single row into an numbered array
1119 * @param mixed $query_id
1121 private function sqlsrv_fetchrow($query_id) {
1122 $row = sqlsrv_fetch_array($query_id, SQLSRV_FETCH_NUMERIC);
1123 if ($row === false) {
1124 $dberr = $this->get_last_error();
1125 return false;
1128 foreach ($row as $key => $value) {
1129 $row[$key] = ($value === ' ' || $value === NULL) ? '' : $value;
1131 return $row;
1135 * Insert a record into a table and return the "id" field if required.
1137 * Some conversions and safety checks are carried out. Lobs are supported.
1138 * If the return ID isn't required, then this just reports success as true/false.
1139 * $data is an object containing needed data
1140 * @param string $table The database table to be inserted into
1141 * @param object $data A data object with values for one or more fields in the record
1142 * @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.
1143 * @return bool|int true or new id
1144 * @throws dml_exception A DML specific exception is thrown for any errors.
1146 public function insert_record($table, $dataobject, $returnid = true, $bulk = false) {
1147 $dataobject = (array)$dataobject;
1149 $columns = $this->get_columns($table);
1150 if (empty($columns)) {
1151 throw new dml_exception('ddltablenotexist', $table);
1154 $cleaned = array ();
1156 foreach ($dataobject as $field => $value) {
1157 if ($field === 'id') {
1158 continue;
1160 if (!isset($columns[$field])) {
1161 continue;
1163 $column = $columns[$field];
1164 $cleaned[$field] = $this->normalise_value($column, $value);
1167 return $this->insert_record_raw($table, $cleaned, $returnid, $bulk);
1171 * Import a record into a table, id field is required.
1172 * Safety checks are NOT carried out. Lobs are supported.
1174 * @param string $table name of database table to be inserted into
1175 * @param object $dataobject A data object with values for one or more fields in the record
1176 * @return bool true
1177 * @throws dml_exception A DML specific exception is thrown for any errors.
1179 public function import_record($table, $dataobject) {
1180 if (!is_object($dataobject)) {
1181 $dataobject = (object)$dataobject;
1184 $columns = $this->get_columns($table);
1185 $cleaned = array ();
1187 foreach ($dataobject as $field => $value) {
1188 if (!isset($columns[$field])) {
1189 continue;
1191 $column = $columns[$field];
1192 $cleaned[$field] = $this->normalise_value($column, $value);
1195 $this->insert_record_raw($table, $cleaned, false, false, true);
1197 return true;
1201 * Update record in database, as fast as possible, no safety checks, lobs not supported.
1202 * @param string $table name
1203 * @param mixed $params data record as object or array
1204 * @param bool true means repeated updates expected
1205 * @return bool true
1206 * @throws dml_exception A DML specific exception is thrown for any errors.
1208 public function update_record_raw($table, $params, $bulk = false) {
1209 $params = (array)$params;
1211 if (!isset($params['id'])) {
1212 throw new coding_exception('moodle_database::update_record_raw() id field must be specified.');
1214 $id = $params['id'];
1215 unset($params['id']);
1217 if (empty($params)) {
1218 throw new coding_exception('moodle_database::update_record_raw() no fields found.');
1221 $sets = array ();
1223 foreach ($params as $field => $value) {
1224 $sets[] = "$field = ?";
1227 $params[] = $id; // last ? in WHERE condition
1229 $sets = implode(',', $sets);
1230 $sql = "UPDATE {".$table."} SET $sets WHERE id = ?";
1232 $this->do_query($sql, $params, SQL_QUERY_UPDATE);
1234 return true;
1238 * Update a record in a table
1240 * $dataobject is an object containing needed data
1241 * Relies on $dataobject having a variable "id" to
1242 * specify the record to update
1244 * @param string $table The database table to be checked against.
1245 * @param object $dataobject An object with contents equal to fieldname=>fieldvalue. Must have an entry for 'id' to map to the table specified.
1246 * @param bool true means repeated updates expected
1247 * @return bool true
1248 * @throws dml_exception A DML specific exception is thrown for any errors.
1250 public function update_record($table, $dataobject, $bulk = false) {
1251 $dataobject = (array)$dataobject;
1253 $columns = $this->get_columns($table);
1254 $cleaned = array ();
1256 foreach ($dataobject as $field => $value) {
1257 if (!isset($columns[$field])) {
1258 continue;
1260 $column = $columns[$field];
1261 $cleaned[$field] = $this->normalise_value($column, $value);
1264 return $this->update_record_raw($table, $cleaned, $bulk);
1268 * Set a single field in every table record which match a particular WHERE clause.
1270 * @param string $table The database table to be checked against.
1271 * @param string $newfield the field to set.
1272 * @param string $newvalue the value to set the field to.
1273 * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
1274 * @param array $params array of sql parameters
1275 * @return bool true
1276 * @throws dml_exception A DML specific exception is thrown for any errors.
1278 public function set_field_select($table, $newfield, $newvalue, $select, array $params = null) {
1279 if ($select) {
1280 $select = "WHERE $select";
1283 if (is_null($params)) {
1284 $params = array ();
1287 // convert params to ? types
1288 list($select, $params, $type) = $this->fix_sql_params($select, $params);
1290 // Get column metadata
1291 $columns = $this->get_columns($table);
1292 $column = $columns[$newfield];
1294 $newvalue = $this->normalise_value($column, $newvalue);
1296 if (is_null($newvalue)) {
1297 $newfield = "$newfield = NULL";
1298 } else {
1299 $newfield = "$newfield = ?";
1300 array_unshift($params, $newvalue);
1302 $sql = "UPDATE {".$table."} SET $newfield $select";
1304 $this->do_query($sql, $params, SQL_QUERY_UPDATE);
1306 return true;
1310 * Delete one or more records from a table which match a particular WHERE clause.
1312 * @param string $table The database table to be checked against.
1313 * @param string $select A fragment of SQL to be used in a where clause in the SQL call (used to define the selection criteria).
1314 * @param array $params array of sql parameters
1315 * @return bool true
1316 * @throws dml_exception A DML specific exception is thrown for any errors.
1318 public function delete_records_select($table, $select, array $params = null) {
1319 if ($select) {
1320 $select = "WHERE $select";
1323 $sql = "DELETE FROM {".$table."} $select";
1325 // we use SQL_QUERY_UPDATE because we do not know what is in general SQL, delete constant would not be accurate
1326 $this->do_query($sql, $params, SQL_QUERY_UPDATE);
1328 return true;
1332 public function sql_cast_char2int($fieldname, $text = false) {
1333 if (!$text) {
1334 return ' CAST(' . $fieldname . ' AS INT) ';
1335 } else {
1336 return ' CAST(' . $this->sql_compare_text($fieldname) . ' AS INT) ';
1340 public function sql_cast_char2real($fieldname, $text=false) {
1341 if (!$text) {
1342 return ' CAST(' . $fieldname . ' AS REAL) ';
1343 } else {
1344 return ' CAST(' . $this->sql_compare_text($fieldname) . ' AS REAL) ';
1348 public function sql_ceil($fieldname) {
1349 return ' CEILING('.$fieldname.')';
1352 protected function get_collation() {
1353 if (isset($this->collation)) {
1354 return $this->collation;
1356 if (!empty($this->dboptions['dbcollation'])) {
1357 // perf speedup
1358 $this->collation = $this->dboptions['dbcollation'];
1359 return $this->collation;
1362 // make some default
1363 $this->collation = 'Latin1_General_CI_AI';
1365 $sql = "SELECT CAST(DATABASEPROPERTYEX('$this->dbname', 'Collation') AS varchar(255)) AS SQLCollation";
1366 $this->query_start($sql, null, SQL_QUERY_AUX);
1367 $result = sqlsrv_query($this->sqlsrv, $sql);
1368 $this->query_end($result);
1370 if ($result) {
1371 if ($rawcolumn = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
1372 $this->collation = reset($rawcolumn);
1374 $this->free_result($result);
1377 return $this->collation;
1380 public function sql_equal($fieldname, $param, $casesensitive = true, $accentsensitive = true, $notequal = false) {
1381 $equalop = $notequal ? '<>' : '=';
1382 $collation = $this->get_collation();
1384 if ($casesensitive) {
1385 $collation = str_replace('_CI', '_CS', $collation);
1386 } else {
1387 $collation = str_replace('_CS', '_CI', $collation);
1389 if ($accentsensitive) {
1390 $collation = str_replace('_AI', '_AS', $collation);
1391 } else {
1392 $collation = str_replace('_AS', '_AI', $collation);
1395 return "$fieldname COLLATE $collation $equalop $param";
1399 * Returns 'LIKE' part of a query.
1401 * @param string $fieldname usually name of the table column
1402 * @param string $param usually bound query parameter (?, :named)
1403 * @param bool $casesensitive use case sensitive search
1404 * @param bool $accensensitive use accent sensitive search (not all databases support accent insensitive)
1405 * @param bool $notlike true means "NOT LIKE"
1406 * @param string $escapechar escape char for '%' and '_'
1407 * @return string SQL code fragment
1409 public function sql_like($fieldname, $param, $casesensitive = true, $accentsensitive = true, $notlike = false, $escapechar = '\\') {
1410 if (strpos($param, '%') !== false) {
1411 debugging('Potential SQL injection detected, sql_like() expects bound parameters (? or :named)');
1414 $collation = $this->get_collation();
1415 $LIKE = $notlike ? 'NOT LIKE' : 'LIKE';
1417 if ($casesensitive) {
1418 $collation = str_replace('_CI', '_CS', $collation);
1419 } else {
1420 $collation = str_replace('_CS', '_CI', $collation);
1422 if ($accentsensitive) {
1423 $collation = str_replace('_AI', '_AS', $collation);
1424 } else {
1425 $collation = str_replace('_AS', '_AI', $collation);
1428 return "$fieldname COLLATE $collation $LIKE $param ESCAPE '$escapechar'";
1431 public function sql_concat() {
1432 $arr = func_get_args();
1434 foreach ($arr as $key => $ele) {
1435 $arr[$key] = ' CAST('.$ele.' AS NVARCHAR(255)) ';
1437 $s = implode(' + ', $arr);
1439 if ($s === '') {
1440 return " '' ";
1442 return " $s ";
1445 public function sql_concat_join($separator = "' '", $elements = array ()) {
1446 for ($n = count($elements) - 1; $n > 0; $n--) {
1447 array_splice($elements, $n, 0, $separator);
1449 return call_user_func_array(array($this, 'sql_concat'), $elements);
1452 public function sql_isempty($tablename, $fieldname, $nullablefield, $textfield) {
1453 if ($textfield) {
1454 return ' ('.$this->sql_compare_text($fieldname)." = '') ";
1455 } else {
1456 return " ($fieldname = '') ";
1461 * Returns the SQL text to be used to calculate the length in characters of one expression.
1462 * @param string fieldname or expression to calculate its length in characters.
1463 * @return string the piece of SQL code to be used in the statement.
1465 public function sql_length($fieldname) {
1466 return ' LEN('.$fieldname.')';
1469 public function sql_order_by_text($fieldname, $numchars = 32) {
1470 return " CONVERT(varchar({$numchars}), {$fieldname})";
1474 * Returns the SQL for returning searching one string for the location of another.
1476 public function sql_position($needle, $haystack) {
1477 return "CHARINDEX(($needle), ($haystack))";
1481 * Returns the proper substr() SQL text used to extract substrings from DB
1482 * NOTE: this was originally returning only function name
1484 * @param string $expr some string field, no aggregates
1485 * @param mixed $start integer or expression evaluating to int
1486 * @param mixed $length optional integer or expression evaluating to int
1487 * @return string sql fragment
1489 public function sql_substr($expr, $start, $length = false) {
1490 if (count(func_get_args()) < 2) {
1491 throw new coding_exception('moodle_database::sql_substr() requires at least two parameters',
1492 'Originally this function was only returning name of SQL substring function, it now requires all parameters.');
1495 if ($length === false) {
1496 return "SUBSTRING($expr, " . $this->sql_cast_char2int($start) . ", 2^31-1)";
1497 } else {
1498 return "SUBSTRING($expr, " . $this->sql_cast_char2int($start) . ", " . $this->sql_cast_char2int($length) . ")";
1503 * Does this driver support tool_replace?
1505 * @since Moodle 2.6.1
1506 * @return bool
1508 public function replace_all_text_supported() {
1509 return true;
1512 public function session_lock_supported() {
1513 return true;
1517 * Obtain session lock
1518 * @param int $rowid id of the row with session record
1519 * @param int $timeout max allowed time to wait for the lock in seconds
1520 * @return void
1522 public function get_session_lock($rowid, $timeout) {
1523 if (!$this->session_lock_supported()) {
1524 return;
1526 parent::get_session_lock($rowid, $timeout);
1528 $timeoutmilli = $timeout * 1000;
1530 $fullname = $this->dbname.'-'.$this->prefix.'-session-'.$rowid;
1531 // While this may work using proper {call sp_...} calls + binding +
1532 // executing + consuming recordsets, the solution used for the mssql
1533 // driver is working perfectly, so 100% mimic-ing that code.
1534 // $sql = "sp_getapplock '$fullname', 'Exclusive', 'Session', $timeoutmilli";
1535 $sql = "BEGIN
1536 DECLARE @result INT
1537 EXECUTE @result = sp_getapplock @Resource='$fullname',
1538 @LockMode='Exclusive',
1539 @LockOwner='Session',
1540 @LockTimeout='$timeoutmilli'
1541 SELECT @result
1542 END";
1543 $this->query_start($sql, null, SQL_QUERY_AUX);
1544 $result = sqlsrv_query($this->sqlsrv, $sql);
1545 $this->query_end($result);
1547 if ($result) {
1548 $row = sqlsrv_fetch_array($result);
1549 if ($row[0] < 0) {
1550 throw new dml_sessionwait_exception();
1554 $this->free_result($result);
1557 public function release_session_lock($rowid) {
1558 if (!$this->session_lock_supported()) {
1559 return;
1561 if (!$this->used_for_db_sessions) {
1562 return;
1565 parent::release_session_lock($rowid);
1567 $fullname = $this->dbname.'-'.$this->prefix.'-session-'.$rowid;
1568 $sql = "sp_releaseapplock '$fullname', 'Session'";
1569 $this->query_start($sql, null, SQL_QUERY_AUX);
1570 $result = sqlsrv_query($this->sqlsrv, $sql);
1571 $this->query_end($result);
1572 $this->free_result($result);
1576 * Driver specific start of real database transaction,
1577 * this can not be used directly in code.
1578 * @return void
1580 protected function begin_transaction() {
1581 // Recordsets do not work well with transactions in SQL Server,
1582 // let's prefetch the recordsets to memory to work around these problems.
1583 foreach ($this->recordsets as $rs) {
1584 $rs->transaction_starts();
1587 $this->query_start('native sqlsrv_begin_transaction', NULL, SQL_QUERY_AUX);
1588 $result = sqlsrv_begin_transaction($this->sqlsrv);
1589 $this->query_end($result);
1593 * Driver specific commit of real database transaction,
1594 * this can not be used directly in code.
1595 * @return void
1597 protected function commit_transaction() {
1598 $this->query_start('native sqlsrv_commit', NULL, SQL_QUERY_AUX);
1599 $result = sqlsrv_commit($this->sqlsrv);
1600 $this->query_end($result);
1604 * Driver specific abort of real database transaction,
1605 * this can not be used directly in code.
1606 * @return void
1608 protected function rollback_transaction() {
1609 $this->query_start('native sqlsrv_rollback', NULL, SQL_QUERY_AUX);
1610 $result = sqlsrv_rollback($this->sqlsrv);
1611 $this->query_end($result);
1615 * Is fulltext search enabled?.
1617 * @return bool
1619 public function is_fulltext_search_supported() {
1620 global $CFG;
1622 $sql = "SELECT FULLTEXTSERVICEPROPERTY('IsFullTextInstalled')";
1623 $this->query_start($sql, null, SQL_QUERY_AUX);
1624 $result = sqlsrv_query($this->sqlsrv, $sql);
1625 $this->query_end($result);
1626 if ($result) {
1627 if ($row = sqlsrv_fetch_array($result)) {
1628 $property = (bool)reset($row);
1631 $this->free_result($result);
1633 return !empty($property);