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