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