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