PageRenderTime 50ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/dml/mssql_native_moodle_database.php

https://bitbucket.org/synergylearning/campusconnect
PHP | 1373 lines | 908 code | 162 blank | 303 comment | 127 complexity | a4fd8d8f379418e326b11dfd2d7ed8e9 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, LGPL-2.1, Apache-2.0, BSD-3-Clause, AGPL-3.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. // This file is part of Moodle - http://moodle.org/
  3. //
  4. // Moodle is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // Moodle is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * Native mssql class representing moodle database interface.
  18. *
  19. * @package core_dml
  20. * @copyright 2009 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
  21. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  22. */
  23. defined('MOODLE_INTERNAL') || die();
  24. require_once(__DIR__.'/moodle_database.php');
  25. require_once(__DIR__.'/mssql_native_moodle_recordset.php');
  26. require_once(__DIR__.'/mssql_native_moodle_temptables.php');
  27. /**
  28. * Native mssql class representing moodle database interface.
  29. *
  30. * @package core_dml
  31. * @copyright 2009 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
  32. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  33. */
  34. class mssql_native_moodle_database extends moodle_database {
  35. protected $mssql = null;
  36. protected $last_error_reporting; // To handle mssql driver default verbosity
  37. protected $collation; // current DB collation cache
  38. /**
  39. * Detects if all needed PHP stuff installed.
  40. * Note: can be used before connect()
  41. * @return mixed true if ok, string if something
  42. */
  43. public function driver_installed() {
  44. if (!function_exists('mssql_connect')) {
  45. return get_string('mssqlextensionisnotpresentinphp', 'install');
  46. }
  47. return true;
  48. }
  49. /**
  50. * Returns database family type - describes SQL dialect
  51. * Note: can be used before connect()
  52. * @return string db family name (mysql, postgres, mssql, oracle, etc.)
  53. */
  54. public function get_dbfamily() {
  55. return 'mssql';
  56. }
  57. /**
  58. * Returns more specific database driver type
  59. * Note: can be used before connect()
  60. * @return string db type mysqli, pgsql, oci, mssql, sqlsrv
  61. */
  62. protected function get_dbtype() {
  63. return 'mssql';
  64. }
  65. /**
  66. * Returns general database library name
  67. * Note: can be used before connect()
  68. * @return string db type pdo, native
  69. */
  70. protected function get_dblibrary() {
  71. return 'native';
  72. }
  73. /**
  74. * Returns localised database type name
  75. * Note: can be used before connect()
  76. * @return string
  77. */
  78. public function get_name() {
  79. return get_string('nativemssql', 'install');
  80. }
  81. /**
  82. * Returns localised database configuration help.
  83. * Note: can be used before connect()
  84. * @return string
  85. */
  86. public function get_configuration_help() {
  87. return get_string('nativemssqlhelp', 'install');
  88. }
  89. /**
  90. * Connect to db
  91. * Must be called before other methods.
  92. * @param string $dbhost The database host.
  93. * @param string $dbuser The database username.
  94. * @param string $dbpass The database username's password.
  95. * @param string $dbname The name of the database being connected to.
  96. * @param mixed $prefix string means moodle db prefix, false used for external databases where prefix not used
  97. * @param array $dboptions driver specific options
  98. * @return bool true
  99. * @throws dml_connection_exception if error
  100. */
  101. public function connect($dbhost, $dbuser, $dbpass, $dbname, $prefix, array $dboptions=null) {
  102. if ($prefix == '' and !$this->external) {
  103. //Enforce prefixes for everybody but mysql
  104. throw new dml_exception('prefixcannotbeempty', $this->get_dbfamily());
  105. }
  106. $driverstatus = $this->driver_installed();
  107. if ($driverstatus !== true) {
  108. throw new dml_exception('dbdriverproblem', $driverstatus);
  109. }
  110. $this->store_settings($dbhost, $dbuser, $dbpass, $dbname, $prefix, $dboptions);
  111. $dbhost = $this->dbhost;
  112. // Zero shouldn't be used as a port number so doing a check with empty() should be fine.
  113. if (!empty($dboptions['dbport'])) {
  114. if (stristr(PHP_OS, 'win') && !stristr(PHP_OS, 'darwin')) {
  115. $dbhost .= ','.$dboptions['dbport'];
  116. } else {
  117. $dbhost .= ':'.$dboptions['dbport'];
  118. }
  119. }
  120. ob_start();
  121. if (!empty($this->dboptions['dbpersist'])) { // persistent connection
  122. $this->mssql = mssql_pconnect($dbhost, $this->dbuser, $this->dbpass, true);
  123. } else {
  124. $this->mssql = mssql_connect($dbhost, $this->dbuser, $this->dbpass, true);
  125. }
  126. $dberr = ob_get_contents();
  127. ob_end_clean();
  128. if ($this->mssql === false) {
  129. $this->mssql = null;
  130. throw new dml_connection_exception($dberr);
  131. }
  132. // already connected, select database and set some env. variables
  133. $this->query_start("--mssql_select_db", null, SQL_QUERY_AUX);
  134. $result = mssql_select_db($this->dbname, $this->mssql);
  135. $this->query_end($result);
  136. // No need to set charset. It's UTF8, with transparent conversions
  137. // back and forth performed both by FreeTDS or ODBTP
  138. // Allow quoted identifiers
  139. $sql = "SET QUOTED_IDENTIFIER ON";
  140. $this->query_start($sql, null, SQL_QUERY_AUX);
  141. $result = mssql_query($sql, $this->mssql);
  142. $this->query_end($result);
  143. $this->free_result($result);
  144. // Force ANSI nulls so the NULL check was done by IS NULL and NOT IS NULL
  145. // instead of equal(=) and distinct(<>) symbols
  146. $sql = "SET ANSI_NULLS ON";
  147. $this->query_start($sql, null, SQL_QUERY_AUX);
  148. $result = mssql_query($sql, $this->mssql);
  149. $this->query_end($result);
  150. $this->free_result($result);
  151. // Force ANSI warnings so arithmetic/string overflows will be
  152. // returning error instead of transparently truncating data
  153. $sql = "SET ANSI_WARNINGS ON";
  154. $this->query_start($sql, null, SQL_QUERY_AUX);
  155. $result = mssql_query($sql, $this->mssql);
  156. $this->query_end($result);
  157. // Concatenating null with anything MUST return NULL
  158. $sql = "SET CONCAT_NULL_YIELDS_NULL ON";
  159. $this->query_start($sql, null, SQL_QUERY_AUX);
  160. $result = mssql_query($sql, $this->mssql);
  161. $this->query_end($result);
  162. $this->free_result($result);
  163. // Set transactions isolation level to READ_COMMITTED
  164. // prevents dirty reads when using transactions +
  165. // is the default isolation level of MSSQL
  166. // Requires database to run with READ_COMMITTED_SNAPSHOT ON
  167. $sql = "SET TRANSACTION ISOLATION LEVEL READ COMMITTED";
  168. $this->query_start($sql, NULL, SQL_QUERY_AUX);
  169. $result = mssql_query($sql, $this->mssql);
  170. $this->query_end($result);
  171. $this->free_result($result);
  172. // Connection stabilised and configured, going to instantiate the temptables controller
  173. $this->temptables = new mssql_native_moodle_temptables($this);
  174. return true;
  175. }
  176. /**
  177. * Close database connection and release all resources
  178. * and memory (especially circular memory references).
  179. * Do NOT use connect() again, create a new instance if needed.
  180. */
  181. public function dispose() {
  182. parent::dispose(); // Call parent dispose to write/close session and other common stuff before closing connection
  183. if ($this->mssql) {
  184. mssql_close($this->mssql);
  185. $this->mssql = null;
  186. }
  187. }
  188. /**
  189. * Called before each db query.
  190. * @param string $sql
  191. * @param array array of parameters
  192. * @param int $type type of query
  193. * @param mixed $extrainfo driver specific extra information
  194. * @return void
  195. */
  196. protected function query_start($sql, array $params=null, $type, $extrainfo=null) {
  197. parent::query_start($sql, $params, $type, $extrainfo);
  198. // mssql driver tends to send debug to output, we do not need that ;-)
  199. $this->last_error_reporting = error_reporting(0);
  200. }
  201. /**
  202. * Called immediately after each db query.
  203. * @param mixed db specific result
  204. * @return void
  205. */
  206. protected function query_end($result) {
  207. // reset original debug level
  208. error_reporting($this->last_error_reporting);
  209. parent::query_end($result);
  210. }
  211. /**
  212. * Returns database server info array
  213. * @return array Array containing 'description' and 'version' info
  214. */
  215. public function get_server_info() {
  216. static $info;
  217. if (!$info) {
  218. $info = array();
  219. $sql = 'sp_server_info 2';
  220. $this->query_start($sql, null, SQL_QUERY_AUX);
  221. $result = mssql_query($sql, $this->mssql);
  222. $this->query_end($result);
  223. $row = mssql_fetch_row($result);
  224. $info['description'] = $row[2];
  225. $this->free_result($result);
  226. $sql = 'sp_server_info 500';
  227. $this->query_start($sql, null, SQL_QUERY_AUX);
  228. $result = mssql_query($sql, $this->mssql);
  229. $this->query_end($result);
  230. $row = mssql_fetch_row($result);
  231. $info['version'] = $row[2];
  232. $this->free_result($result);
  233. }
  234. return $info;
  235. }
  236. /**
  237. * Converts short table name {tablename} to real table name
  238. * supporting temp tables (#) if detected
  239. *
  240. * @param string sql
  241. * @return string sql
  242. */
  243. protected function fix_table_names($sql) {
  244. if (preg_match_all('/\{([a-z][a-z0-9_]*)\}/', $sql, $matches)) {
  245. foreach($matches[0] as $key=>$match) {
  246. $name = $matches[1][$key];
  247. if ($this->temptables->is_temptable($name)) {
  248. $sql = str_replace($match, $this->temptables->get_correct_name($name), $sql);
  249. } else {
  250. $sql = str_replace($match, $this->prefix.$name, $sql);
  251. }
  252. }
  253. }
  254. return $sql;
  255. }
  256. /**
  257. * Returns supported query parameter types
  258. * @return int bitmask of accepted SQL_PARAMS_*
  259. */
  260. protected function allowed_param_types() {
  261. return SQL_PARAMS_QM; // Not really, but emulated, see emulate_bound_params()
  262. }
  263. /**
  264. * Returns last error reported by database engine.
  265. * @return string error message
  266. */
  267. public function get_last_error() {
  268. return mssql_get_last_message();
  269. }
  270. /**
  271. * Return tables in database WITHOUT current prefix
  272. * @param bool $usecache if true, returns list of cached tables.
  273. * @return array of table names in lowercase and without prefix
  274. */
  275. public function get_tables($usecache=true) {
  276. if ($usecache and $this->tables !== null) {
  277. return $this->tables;
  278. }
  279. $this->tables = array();
  280. $sql = "SELECT table_name
  281. FROM INFORMATION_SCHEMA.TABLES
  282. WHERE table_name LIKE '$this->prefix%'
  283. AND table_type = 'BASE TABLE'";
  284. $this->query_start($sql, null, SQL_QUERY_AUX);
  285. $result = mssql_query($sql, $this->mssql);
  286. $this->query_end($result);
  287. if ($result) {
  288. while ($row = mssql_fetch_row($result)) {
  289. $tablename = reset($row);
  290. if ($this->prefix !== false && $this->prefix !== '') {
  291. if (strpos($tablename, $this->prefix) !== 0) {
  292. continue;
  293. }
  294. $tablename = substr($tablename, strlen($this->prefix));
  295. }
  296. $this->tables[$tablename] = $tablename;
  297. }
  298. $this->free_result($result);
  299. }
  300. // Add the currently available temptables
  301. $this->tables = array_merge($this->tables, $this->temptables->get_temptables());
  302. return $this->tables;
  303. }
  304. /**
  305. * Return table indexes - everything lowercased.
  306. * @param string $table The table we want to get indexes from.
  307. * @return array An associative array of indexes containing 'unique' flag and 'columns' being indexed
  308. */
  309. public function get_indexes($table) {
  310. $indexes = array();
  311. $tablename = $this->prefix.$table;
  312. // Indexes aren't covered by information_schema metatables, so we need to
  313. // go to sys ones. Skipping primary key indexes on purpose.
  314. $sql = "SELECT i.name AS index_name, i.is_unique, ic.index_column_id, c.name AS column_name
  315. FROM sys.indexes i
  316. JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
  317. JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
  318. JOIN sys.tables t ON i.object_id = t.object_id
  319. WHERE t.name = '$tablename'
  320. AND i.is_primary_key = 0
  321. ORDER BY i.name, i.index_id, ic.index_column_id";
  322. $this->query_start($sql, null, SQL_QUERY_AUX);
  323. $result = mssql_query($sql, $this->mssql);
  324. $this->query_end($result);
  325. if ($result) {
  326. $lastindex = '';
  327. $unique = false;
  328. $columns = array();
  329. while ($row = mssql_fetch_assoc($result)) {
  330. if ($lastindex and $lastindex != $row['index_name']) { // Save lastindex to $indexes and reset info
  331. $indexes[$lastindex] = array('unique' => $unique, 'columns' => $columns);
  332. $unique = false;
  333. $columns = array();
  334. }
  335. $lastindex = $row['index_name'];
  336. $unique = empty($row['is_unique']) ? false : true;
  337. $columns[] = $row['column_name'];
  338. }
  339. if ($lastindex ) { // Add the last one if exists
  340. $indexes[$lastindex] = array('unique' => $unique, 'columns' => $columns);
  341. }
  342. $this->free_result($result);
  343. }
  344. return $indexes;
  345. }
  346. /**
  347. * Returns datailed information about columns in table. This information is cached internally.
  348. * @param string $table name
  349. * @param bool $usecache
  350. * @return array array of database_column_info objects indexed with column names
  351. */
  352. public function get_columns($table, $usecache=true) {
  353. if ($usecache) {
  354. $properties = array('dbfamily' => $this->get_dbfamily(), 'settings' => $this->get_settings_hash());
  355. $cache = cache::make('core', 'databasemeta', $properties);
  356. if ($data = $cache->get($table)) {
  357. return $data;
  358. }
  359. }
  360. $structure = array();
  361. if (!$this->temptables->is_temptable($table)) { // normal table, get metadata from own schema
  362. $sql = "SELECT column_name AS name,
  363. data_type AS type,
  364. numeric_precision AS max_length,
  365. character_maximum_length AS char_max_length,
  366. numeric_scale AS scale,
  367. is_nullable AS is_nullable,
  368. columnproperty(object_id(quotename(table_schema) + '.' +
  369. quotename(table_name)), column_name, 'IsIdentity') AS auto_increment,
  370. column_default AS default_value
  371. FROM INFORMATION_SCHEMA.COLUMNS
  372. WHERE table_name = '{" . $table . "}'
  373. ORDER BY ordinal_position";
  374. } else { // temp table, get metadata from tempdb schema
  375. $sql = "SELECT column_name AS name,
  376. data_type AS type,
  377. numeric_precision AS max_length,
  378. character_maximum_length AS char_max_length,
  379. numeric_scale AS scale,
  380. is_nullable AS is_nullable,
  381. columnproperty(object_id(quotename(table_schema) + '.' +
  382. quotename(table_name)), column_name, 'IsIdentity') AS auto_increment,
  383. column_default AS default_value
  384. FROM tempdb.INFORMATION_SCHEMA.COLUMNS
  385. JOIN tempdb..sysobjects ON name = table_name
  386. WHERE id = object_id('tempdb..{" . $table . "}')
  387. ORDER BY ordinal_position";
  388. }
  389. list($sql, $params, $type) = $this->fix_sql_params($sql, null);
  390. $this->query_start($sql, null, SQL_QUERY_AUX);
  391. $result = mssql_query($sql, $this->mssql);
  392. $this->query_end($result);
  393. if (!$result) {
  394. return array();
  395. }
  396. while ($rawcolumn = mssql_fetch_assoc($result)) {
  397. $rawcolumn = (object)$rawcolumn;
  398. $info = new stdClass();
  399. $info->name = $rawcolumn->name;
  400. $info->type = $rawcolumn->type;
  401. $info->meta_type = $this->mssqltype2moodletype($info->type);
  402. // Prepare auto_increment info
  403. $info->auto_increment = $rawcolumn->auto_increment ? true : false;
  404. // Define type for auto_increment columns
  405. $info->meta_type = ($info->auto_increment && $info->meta_type == 'I') ? 'R' : $info->meta_type;
  406. // id columns being auto_incremnt are PK by definition
  407. $info->primary_key = ($info->name == 'id' && $info->meta_type == 'R' && $info->auto_increment);
  408. if ($info->meta_type === 'C' and $rawcolumn->char_max_length == -1) {
  409. // This is NVARCHAR(MAX), not a normal NVARCHAR.
  410. $info->max_length = -1;
  411. $info->meta_type = 'X';
  412. } else {
  413. // Put correct length for character and LOB types
  414. $info->max_length = $info->meta_type == 'C' ? $rawcolumn->char_max_length : $rawcolumn->max_length;
  415. $info->max_length = ($info->meta_type == 'X' || $info->meta_type == 'B') ? -1 : $info->max_length;
  416. }
  417. // Scale
  418. $info->scale = $rawcolumn->scale;
  419. // Prepare not_null info
  420. $info->not_null = $rawcolumn->is_nullable == 'NO' ? true : false;
  421. // Process defaults
  422. $info->has_default = !empty($rawcolumn->default_value);
  423. if ($rawcolumn->default_value === NULL) {
  424. $info->default_value = NULL;
  425. } else {
  426. $info->default_value = preg_replace("/^[\(N]+[']?(.*?)[']?[\)]+$/", '\\1', $rawcolumn->default_value);
  427. }
  428. // Process binary
  429. $info->binary = $info->meta_type == 'B' ? true : false;
  430. $structure[$info->name] = new database_column_info($info);
  431. }
  432. $this->free_result($result);
  433. if ($usecache) {
  434. $cache->set($table, $structure);
  435. }
  436. return $structure;
  437. }
  438. /**
  439. * Normalise values based on varying RDBMS's dependencies (booleans, LOBs...)
  440. *
  441. * @param database_column_info $column column metadata corresponding with the value we are going to normalise
  442. * @param mixed $value value we are going to normalise
  443. * @return mixed the normalised value
  444. */
  445. protected function normalise_value($column, $value) {
  446. $this->detect_objects($value);
  447. if (is_bool($value)) { // Always, convert boolean to int
  448. $value = (int)$value;
  449. } // And continue processing because text columns with numeric info need special handling below
  450. if ($column->meta_type == 'B') { // BLOBs need to be properly "packed", but can be inserted directly if so.
  451. if (!is_null($value)) { // If value not null, unpack it to unquoted hexadecimal byte-string format
  452. $value = unpack('H*hex', $value); // we leave it as array, so emulate_bound_params() can detect it
  453. } // easily and "bind" the param ok.
  454. } else if ($column->meta_type == 'X') { // MSSQL doesn't cast from int to text, so if text column
  455. if (is_numeric($value)) { // and is numeric value then cast to string
  456. $value = array('numstr' => (string)$value); // and put into array, so emulate_bound_params() will know how
  457. } // to "bind" the param ok, avoiding reverse conversion to number
  458. } else if ($value === '') {
  459. if ($column->meta_type == 'I' or $column->meta_type == 'F' or $column->meta_type == 'N') {
  460. $value = 0; // prevent '' problems in numeric fields
  461. }
  462. }
  463. return $value;
  464. }
  465. /**
  466. * Selectively call mssql_free_result(), avoiding some warnings without using the horrible @
  467. *
  468. * @param mssql_resource $resource resource to be freed if possible
  469. */
  470. private function free_result($resource) {
  471. if (!is_bool($resource)) { // true/false resources cannot be freed
  472. mssql_free_result($resource);
  473. }
  474. }
  475. /**
  476. * Provides mapping between mssql native data types and moodle_database - database_column_info - ones)
  477. *
  478. * @param string $mssql_type native mssql data type
  479. * @return string 1-char database_column_info data type
  480. */
  481. private function mssqltype2moodletype($mssql_type) {
  482. $type = null;
  483. switch (strtoupper($mssql_type)) {
  484. case 'BIT':
  485. $type = 'L';
  486. break;
  487. case 'INT':
  488. case 'SMALLINT':
  489. case 'INTEGER':
  490. case 'BIGINT':
  491. $type = 'I';
  492. break;
  493. case 'DECIMAL':
  494. case 'REAL':
  495. case 'FLOAT':
  496. $type = 'N';
  497. break;
  498. case 'VARCHAR':
  499. case 'NVARCHAR':
  500. $type = 'C';
  501. break;
  502. case 'TEXT':
  503. case 'NTEXT':
  504. case 'VARCHAR(MAX)':
  505. case 'NVARCHAR(MAX)':
  506. $type = 'X';
  507. break;
  508. case 'IMAGE':
  509. case 'VARBINARY':
  510. case 'VARBINARY(MAX)':
  511. $type = 'B';
  512. break;
  513. case 'DATETIME':
  514. $type = 'D';
  515. break;
  516. }
  517. if (!$type) {
  518. throw new dml_exception('invalidmssqlnativetype', $mssql_type);
  519. }
  520. return $type;
  521. }
  522. /**
  523. * Do NOT use in code, to be used by database_manager only!
  524. * @param string $sql query
  525. * @return bool true
  526. * @throws dml_exception A DML specific exception is thrown for any errors.
  527. */
  528. public function change_database_structure($sql) {
  529. $this->reset_caches();
  530. $this->query_start($sql, null, SQL_QUERY_STRUCTURE);
  531. $result = mssql_query($sql, $this->mssql);
  532. $this->query_end($result);
  533. return true;
  534. }
  535. /**
  536. * Very ugly hack which emulates bound parameters in queries
  537. * because the mssql driver doesn't support placeholders natively at all
  538. */
  539. protected function emulate_bound_params($sql, array $params=null) {
  540. if (empty($params)) {
  541. return $sql;
  542. }
  543. // ok, we have verified sql statement with ? and correct number of params
  544. $parts = array_reverse(explode('?', $sql));
  545. $return = array_pop($parts);
  546. foreach ($params as $param) {
  547. if (is_bool($param)) {
  548. $return .= (int)$param;
  549. } else if (is_array($param) && isset($param['hex'])) { // detect hex binary, bind it specially
  550. $return .= '0x' . $param['hex'];
  551. } else if (is_array($param) && isset($param['numstr'])) { // detect numerical strings that *must not*
  552. $return .= "N'{$param['numstr']}'"; // be converted back to number params, but bound as strings
  553. } else if (is_null($param)) {
  554. $return .= 'NULL';
  555. } else if (is_number($param)) { // we can not use is_numeric() because it eats leading zeros from strings like 0045646
  556. $return .= "'".$param."'"; //fix for MDL-24863 to prevent auto-cast to int.
  557. } else if (is_float($param)) {
  558. $return .= $param;
  559. } else {
  560. $param = str_replace("'", "''", $param);
  561. $param = str_replace("\0", "", $param);
  562. $return .= "N'$param'";
  563. }
  564. $return .= array_pop($parts);
  565. }
  566. return $return;
  567. }
  568. /**
  569. * Execute general sql query. Should be used only when no other method suitable.
  570. * Do NOT use this to make changes in db structure, use database_manager methods instead!
  571. * @param string $sql query
  572. * @param array $params query parameters
  573. * @return bool true
  574. * @throws dml_exception A DML specific exception is thrown for any errors.
  575. */
  576. public function execute($sql, array $params=null) {
  577. list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
  578. $rawsql = $this->emulate_bound_params($sql, $params);
  579. if (strpos($sql, ';') !== false) {
  580. throw new coding_exception('moodle_database::execute() Multiple sql statements found or bound parameters not used properly in query!');
  581. }
  582. $this->query_start($sql, $params, SQL_QUERY_UPDATE);
  583. $result = mssql_query($rawsql, $this->mssql);
  584. $this->query_end($result);
  585. $this->free_result($result);
  586. return true;
  587. }
  588. /**
  589. * Get a number of records as a moodle_recordset using a SQL statement.
  590. *
  591. * Since this method is a little less readable, use of it should be restricted to
  592. * code where it's possible there might be large datasets being returned. For known
  593. * small datasets use get_records_sql - it leads to simpler code.
  594. *
  595. * The return type is like:
  596. * @see function get_recordset.
  597. *
  598. * @param string $sql the SQL select query to execute.
  599. * @param array $params array of sql parameters
  600. * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
  601. * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
  602. * @return moodle_recordset instance
  603. * @throws dml_exception A DML specific exception is thrown for any errors.
  604. */
  605. public function get_recordset_sql($sql, array $params=null, $limitfrom=0, $limitnum=0) {
  606. $limitfrom = (int)$limitfrom;
  607. $limitnum = (int)$limitnum;
  608. $limitfrom = ($limitfrom < 0) ? 0 : $limitfrom;
  609. $limitnum = ($limitnum < 0) ? 0 : $limitnum;
  610. if ($limitfrom or $limitnum) {
  611. if ($limitnum >= 1) { // Only apply TOP clause if we have any limitnum (limitfrom offset is handled later)
  612. $fetch = $limitfrom + $limitnum;
  613. if (PHP_INT_MAX - $limitnum < $limitfrom) { // Check PHP_INT_MAX overflow
  614. $fetch = PHP_INT_MAX;
  615. }
  616. $sql = preg_replace('/^([\s(])*SELECT([\s]+(DISTINCT|ALL))?(?!\s*TOP\s*\()/i',
  617. "\\1SELECT\\2 TOP $fetch", $sql);
  618. }
  619. }
  620. list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
  621. $rawsql = $this->emulate_bound_params($sql, $params);
  622. $this->query_start($sql, $params, SQL_QUERY_SELECT);
  623. $result = mssql_query($rawsql, $this->mssql);
  624. $this->query_end($result);
  625. if ($limitfrom) { // Skip $limitfrom records
  626. if (!@mssql_data_seek($result, $limitfrom)) {
  627. // Nothing, most probably seek past the end.
  628. mssql_free_result($result);
  629. $result = null;
  630. }
  631. }
  632. return $this->create_recordset($result);
  633. }
  634. protected function create_recordset($result) {
  635. return new mssql_native_moodle_recordset($result);
  636. }
  637. /**
  638. * Get a number of records as an array of objects using a SQL statement.
  639. *
  640. * Return value is like:
  641. * @see function get_records.
  642. *
  643. * @param string $sql the SQL select query to execute. The first column of this SELECT statement
  644. * must be a unique value (usually the 'id' field), as it will be used as the key of the
  645. * returned array.
  646. * @param array $params array of sql parameters
  647. * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
  648. * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
  649. * @return array of objects, or empty array if no records were found
  650. * @throws dml_exception A DML specific exception is thrown for any errors.
  651. */
  652. public function get_records_sql($sql, array $params=null, $limitfrom=0, $limitnum=0) {
  653. $rs = $this->get_recordset_sql($sql, $params, $limitfrom, $limitnum);
  654. $results = array();
  655. foreach ($rs as $row) {
  656. $id = reset($row);
  657. if (isset($results[$id])) {
  658. $colname = key($row);
  659. 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);
  660. }
  661. $results[$id] = $row;
  662. }
  663. $rs->close();
  664. return $results;
  665. }
  666. /**
  667. * Selects records and return values (first field) as an array using a SQL statement.
  668. *
  669. * @param string $sql The SQL query
  670. * @param array $params array of sql parameters
  671. * @return array of values
  672. * @throws dml_exception A DML specific exception is thrown for any errors.
  673. */
  674. public function get_fieldset_sql($sql, array $params=null) {
  675. $rs = $this->get_recordset_sql($sql, $params);
  676. $results = array();
  677. foreach ($rs as $row) {
  678. $results[] = reset($row);
  679. }
  680. $rs->close();
  681. return $results;
  682. }
  683. /**
  684. * Insert new record into database, as fast as possible, no safety checks, lobs not supported.
  685. * @param string $table name
  686. * @param mixed $params data record as object or array
  687. * @param bool $returnit return it of inserted record
  688. * @param bool $bulk true means repeated inserts expected
  689. * @param bool $customsequence true if 'id' included in $params, disables $returnid
  690. * @return bool|int true or new id
  691. * @throws dml_exception A DML specific exception is thrown for any errors.
  692. */
  693. public function insert_record_raw($table, $params, $returnid=true, $bulk=false, $customsequence=false) {
  694. if (!is_array($params)) {
  695. $params = (array)$params;
  696. }
  697. $returning = "";
  698. $isidentity = false;
  699. if ($customsequence) {
  700. if (!isset($params['id'])) {
  701. throw new coding_exception('moodle_database::insert_record_raw() id field must be specified if custom sequences used.');
  702. }
  703. $returnid = false;
  704. $columns = $this->get_columns($table);
  705. if (isset($columns['id']) and $columns['id']->auto_increment) {
  706. $isidentity = true;
  707. }
  708. // Disable IDENTITY column before inserting record with id, only if the
  709. // column is identity, from meta information.
  710. if ($isidentity) {
  711. $sql = 'SET IDENTITY_INSERT {' . $table . '} ON'; // Yes, it' ON!!
  712. list($sql, $xparams, $xtype) = $this->fix_sql_params($sql, null);
  713. $this->query_start($sql, null, SQL_QUERY_AUX);
  714. $result = mssql_query($sql, $this->mssql);
  715. $this->query_end($result);
  716. $this->free_result($result);
  717. }
  718. } else {
  719. unset($params['id']);
  720. if ($returnid) {
  721. $returning = "OUTPUT inserted.id";
  722. }
  723. }
  724. if (empty($params)) {
  725. throw new coding_exception('moodle_database::insert_record_raw() no fields found.');
  726. }
  727. $fields = implode(',', array_keys($params));
  728. $qms = array_fill(0, count($params), '?');
  729. $qms = implode(',', $qms);
  730. $sql = "INSERT INTO {" . $table . "} ($fields) $returning VALUES ($qms)";
  731. list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
  732. $rawsql = $this->emulate_bound_params($sql, $params);
  733. $this->query_start($sql, $params, SQL_QUERY_INSERT);
  734. $result = mssql_query($rawsql, $this->mssql);
  735. // Expected results are:
  736. // - true: insert ok and there isn't returned information.
  737. // - false: insert failed and there isn't returned information.
  738. // - resource: insert executed, need to look for returned (output)
  739. // values to know if the insert was ok or no. Posible values
  740. // are false = failed, integer = insert ok, id returned.
  741. $end = false;
  742. if (is_bool($result)) {
  743. $end = $result;
  744. } else if (is_resource($result)) {
  745. $end = mssql_result($result, 0, 0); // Fetch 1st column from 1st row.
  746. }
  747. $this->query_end($end); // End the query with the calculated $end.
  748. if ($returning !== "") {
  749. $params['id'] = $end;
  750. }
  751. $this->free_result($result);
  752. if ($customsequence) {
  753. // Enable IDENTITY column after inserting record with id, only if the
  754. // column is identity, from meta information.
  755. if ($isidentity) {
  756. $sql = 'SET IDENTITY_INSERT {' . $table . '} OFF'; // Yes, it' OFF!!
  757. list($sql, $xparams, $xtype) = $this->fix_sql_params($sql, null);
  758. $this->query_start($sql, null, SQL_QUERY_AUX);
  759. $result = mssql_query($sql, $this->mssql);
  760. $this->query_end($result);
  761. $this->free_result($result);
  762. }
  763. }
  764. if (!$returnid) {
  765. return true;
  766. }
  767. return (int)$params['id'];
  768. }
  769. /**
  770. * Insert a record into a table and return the "id" field if required.
  771. *
  772. * Some conversions and safety checks are carried out. Lobs are supported.
  773. * If the return ID isn't required, then this just reports success as true/false.
  774. * $data is an object containing needed data
  775. * @param string $table The database table to be inserted into
  776. * @param object $data A data object with values for one or more fields in the record
  777. * @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.
  778. * @return bool|int true or new id
  779. * @throws dml_exception A DML specific exception is thrown for any errors.
  780. */
  781. public function insert_record($table, $dataobject, $returnid=true, $bulk=false) {
  782. $dataobject = (array)$dataobject;
  783. $columns = $this->get_columns($table);
  784. $cleaned = array();
  785. foreach ($dataobject as $field => $value) {
  786. if ($field === 'id') {
  787. continue;
  788. }
  789. if (!isset($columns[$field])) {
  790. continue;
  791. }
  792. $column = $columns[$field];
  793. $cleaned[$field] = $this->normalise_value($column, $value);
  794. }
  795. return $this->insert_record_raw($table, $cleaned, $returnid, $bulk);
  796. }
  797. /**
  798. * Import a record into a table, id field is required.
  799. * Safety checks are NOT carried out. Lobs are supported.
  800. *
  801. * @param string $table name of database table to be inserted into
  802. * @param object $dataobject A data object with values for one or more fields in the record
  803. * @return bool true
  804. * @throws dml_exception A DML specific exception is thrown for any errors.
  805. */
  806. public function import_record($table, $dataobject) {
  807. $dataobject = (array)$dataobject;
  808. $columns = $this->get_columns($table);
  809. $cleaned = array();
  810. foreach ($dataobject as $field => $value) {
  811. if (!isset($columns[$field])) {
  812. continue;
  813. }
  814. $column = $columns[$field];
  815. $cleaned[$field] = $this->normalise_value($column, $value);
  816. }
  817. $this->insert_record_raw($table, $cleaned, false, false, true);
  818. return true;
  819. }
  820. /**
  821. * Update record in database, as fast as possible, no safety checks, lobs not supported.
  822. * @param string $table name
  823. * @param mixed $params data record as object or array
  824. * @param bool true means repeated updates expected
  825. * @return bool true
  826. * @throws dml_exception A DML specific exception is thrown for any errors.
  827. */
  828. public function update_record_raw($table, $params, $bulk=false) {
  829. $params = (array)$params;
  830. if (!isset($params['id'])) {
  831. throw new coding_exception('moodle_database::update_record_raw() id field must be specified.');
  832. }
  833. $id = $params['id'];
  834. unset($params['id']);
  835. if (empty($params)) {
  836. throw new coding_exception('moodle_database::update_record_raw() no fields found.');
  837. }
  838. $sets = array();
  839. foreach ($params as $field=>$value) {
  840. $sets[] = "$field = ?";
  841. }
  842. $params[] = $id; // last ? in WHERE condition
  843. $sets = implode(',', $sets);
  844. $sql = "UPDATE {" . $table . "} SET $sets WHERE id = ?";
  845. list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
  846. $rawsql = $this->emulate_bound_params($sql, $params);
  847. $this->query_start($sql, $params, SQL_QUERY_UPDATE);
  848. $result = mssql_query($rawsql, $this->mssql);
  849. $this->query_end($result);
  850. $this->free_result($result);
  851. return true;
  852. }
  853. /**
  854. * Update a record in a table
  855. *
  856. * $dataobject is an object containing needed data
  857. * Relies on $dataobject having a variable "id" to
  858. * specify the record to update
  859. *
  860. * @param string $table The database table to be checked against.
  861. * @param object $dataobject An object with contents equal to fieldname=>fieldvalue. Must have an entry for 'id' to map to the table specified.
  862. * @param bool true means repeated updates expected
  863. * @return bool true
  864. * @throws dml_exception A DML specific exception is thrown for any errors.
  865. */
  866. public function update_record($table, $dataobject, $bulk=false) {
  867. $dataobject = (array)$dataobject;
  868. $columns = $this->get_columns($table);
  869. $cleaned = array();
  870. foreach ($dataobject as $field => $value) {
  871. if (!isset($columns[$field])) {
  872. continue;
  873. }
  874. $column = $columns[$field];
  875. $cleaned[$field] = $this->normalise_value($column, $value);
  876. }
  877. return $this->update_record_raw($table, $cleaned, $bulk);
  878. }
  879. /**
  880. * Set a single field in every table record which match a particular WHERE clause.
  881. *
  882. * @param string $table The database table to be checked against.
  883. * @param string $newfield the field to set.
  884. * @param string $newvalue the value to set the field to.
  885. * @param string $select A fragment of SQL to be used in a where clause in the SQL call.
  886. * @param array $params array of sql parameters
  887. * @return bool true
  888. * @throws dml_exception A DML specific exception is thrown for any errors.
  889. */
  890. public function set_field_select($table, $newfield, $newvalue, $select, array $params=null) {
  891. if ($select) {
  892. $select = "WHERE $select";
  893. }
  894. if (is_null($params)) {
  895. $params = array();
  896. }
  897. // convert params to ? types
  898. list($select, $params, $type) = $this->fix_sql_params($select, $params);
  899. // Get column metadata
  900. $columns = $this->get_columns($table);
  901. $column = $columns[$newfield];
  902. $newvalue = $this->normalise_value($column, $newvalue);
  903. if (is_null($newvalue)) {
  904. $newfield = "$newfield = NULL";
  905. } else {
  906. $newfield = "$newfield = ?";
  907. array_unshift($params, $newvalue);
  908. }
  909. $sql = "UPDATE {" . $table . "} SET $newfield $select";
  910. list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
  911. $rawsql = $this->emulate_bound_params($sql, $params);
  912. $this->query_start($sql, $params, SQL_QUERY_UPDATE);
  913. $result = mssql_query($rawsql, $this->mssql);
  914. $this->query_end($result);
  915. $this->free_result($result);
  916. return true;
  917. }
  918. /**
  919. * Delete one or more records from a table which match a particular WHERE clause.
  920. *
  921. * @param string $table The database table to be checked against.
  922. * @param string $select A fragment of SQL to be used in a where clause in the SQL call (used to define the selection criteria).
  923. * @param array $params array of sql parameters
  924. * @return bool true
  925. * @throws dml_exception A DML specific exception is thrown for any errors.
  926. */
  927. public function delete_records_select($table, $select, array $params=null) {
  928. if ($select) {
  929. $select = "WHERE $select";
  930. }
  931. $sql = "DELETE FROM {" . $table . "} $select";
  932. list($sql, $params, $type) = $this->fix_sql_params($sql, $params);
  933. $rawsql = $this->emulate_bound_params($sql, $params);
  934. $this->query_start($sql, $params, SQL_QUERY_UPDATE);
  935. $result = mssql_query($rawsql, $this->mssql);
  936. $this->query_end($result);
  937. $this->free_result($result);
  938. return true;
  939. }
  940. public function sql_cast_char2int($fieldname, $text=false) {
  941. if (!$text) {
  942. return ' CAST(' . $fieldname . ' AS INT) ';
  943. } else {
  944. return ' CAST(' . $this->sql_compare_text($fieldname) . ' AS INT) ';
  945. }
  946. }
  947. public function sql_cast_char2real($fieldname, $text=false) {
  948. if (!$text) {
  949. return ' CAST(' . $fieldname . ' AS REAL) ';
  950. } else {
  951. return ' CAST(' . $this->sql_compare_text($fieldname) . ' AS REAL) ';
  952. }
  953. }
  954. public function sql_ceil($fieldname) {
  955. return ' CEILING(' . $fieldname . ')';
  956. }
  957. protected function get_collation() {
  958. if (isset($this->collation)) {
  959. return $this->collation;
  960. }
  961. if (!empty($this->dboptions['dbcollation'])) {
  962. // perf speedup
  963. $this->collation = $this->dboptions['dbcollation'];
  964. return $this->collation;
  965. }
  966. // make some default
  967. $this->collation = 'Latin1_General_CI_AI';
  968. $sql = "SELECT CAST(DATABASEPROPERTYEX('$this->dbname', 'Collation') AS varchar(255)) AS SQLCollation";
  969. $this->query_start($sql, null, SQL_QUERY_AUX);
  970. $result = mssql_query($sql, $this->mssql);
  971. $this->query_end($result);
  972. if ($result) {
  973. if ($rawcolumn = mssql_fetch_assoc($result)) {
  974. $this->collation = reset($rawcolumn);
  975. }
  976. $this->free_result($result);
  977. }
  978. return $this->collation;
  979. }
  980. /**
  981. * Returns 'LIKE' part of a query.
  982. *
  983. * @param string $fieldname usually name of the table column
  984. * @param string $param usually bound query parameter (?, :named)
  985. * @param bool $casesensitive use case sensitive search
  986. * @param bool $accensensitive use accent sensitive search (not all databases support accent insensitive)
  987. * @param bool $notlike true means "NOT LIKE"
  988. * @param string $escapechar escape char for '%' and '_'
  989. * @return string SQL code fragment
  990. */
  991. public function sql_like($fieldname, $param, $casesensitive = true, $accentsensitive = true, $notlike = false, $escapechar = '\\') {
  992. if (strpos($param, '%') !== false) {
  993. debugging('Potential SQL injection detected, sql_like() expects bound parameters (? or :named)');
  994. }
  995. $collation = $this->get_collation();
  996. if ($casesensitive) {
  997. $collation = str_replace('_CI', '_CS', $collation);
  998. } else {
  999. $collation = str_replace('_CS', '_CI', $collation);
  1000. }
  1001. if ($accentsensitive) {
  1002. $collation = str_replace('_AI', '_AS', $collation);
  1003. } else {
  1004. $collation = str_replace('_AS', '_AI', $collation);
  1005. }
  1006. $LIKE = $notlike ? 'NOT LIKE' : 'LIKE';
  1007. return "$fieldname COLLATE $collation $LIKE $param ESCAPE '$escapechar'";
  1008. }
  1009. public function sql_concat() {
  1010. $arr = func_get_args();
  1011. foreach ($arr as $key => $ele) {
  1012. $arr[$key] = ' CAST(' . $ele . ' AS NVARCHAR(255)) ';
  1013. }
  1014. $s = implode(' + ', $arr);
  1015. if ($s === '') {
  1016. return " '' ";
  1017. }
  1018. return " $s ";
  1019. }
  1020. public function sql_concat_join($separator="' '", $elements=array()) {
  1021. for ($n=count($elements)-1; $n > 0 ; $n--) {
  1022. array_splice($elements, $n, 0, $separator);
  1023. }
  1024. $s = implode(' + ', $elements);
  1025. if ($s === '') {
  1026. return " '' ";
  1027. }
  1028. return " $s ";
  1029. }
  1030. public function sql_isempty($tablename, $fieldname, $nullablefield, $textfield) {
  1031. if ($textfield) {
  1032. return ' (' . $this->sql_compare_text($fieldname) . " = '') ";
  1033. } else {
  1034. return " ($fieldname = '') ";
  1035. }
  1036. }
  1037. /**
  1038. * Returns the SQL text to be used to calculate the length in characters of one expression.
  1039. * @param string fieldname or expression to calculate its length in characters.
  1040. * @return string the piece of SQL code to be used in the statement.
  1041. */
  1042. public function sql_length($fieldname) {
  1043. return ' LEN(' . $fieldname . ')';
  1044. }
  1045. public function sql_order_by_text($fieldname, $numchars=32) {
  1046. return " CONVERT(varchar({$numchars}), {$fieldname})";
  1047. }
  1048. /**
  1049. * Returns the SQL for returning searching one string for the location of another.
  1050. */
  1051. public function sql_position($needle, $haystack) {
  1052. return "CHARINDEX(($needle), ($haystack))";
  1053. }
  1054. /**
  1055. * Returns the proper substr() SQL text used to extract substrings from DB
  1056. * NOTE: this was originally returning only function name
  1057. *
  1058. * @param string $expr some string field, no aggregates
  1059. * @param mixed $start integer or expression evaluating to int
  1060. * @param mixed $length optional integer or expression evaluating to int
  1061. * @return string sql fragment
  1062. */
  1063. public function sql_substr($expr, $start, $length=false) {
  1064. if (count(func_get_args()) < 2) {
  1065. throw new coding_exception('moodle_database::sql_substr() requires at least two parameters', 'Originaly this function wa
  1066. s only returning name of SQL substring function, it now requires all parameters.');
  1067. }
  1068. if ($length === false) {
  1069. return "SUBSTRING($expr, $start, (LEN($expr) - $start + 1))";
  1070. } else {
  1071. return "SUBSTRING($expr, $start, $length)";
  1072. }
  1073. }
  1074. /**
  1075. * Does this driver support tool_replace?
  1076. *
  1077. * @since 2.6.1
  1078. * @return bool
  1079. */
  1080. public function replace_all_text_supported() {
  1081. return true;
  1082. }
  1083. public function session_lock_supported() {
  1084. return true;
  1085. }
  1086. /**
  1087. * Obtain session lock
  1088. * @param int $rowid id of the row with session record
  1089. * @param int $timeout max allowed time to wait for the lock in seconds
  1090. * @return bool success
  1091. */
  1092. public function get_session_lock($rowid, $timeout) {
  1093. if (!$this->session_lock_supported()) {
  1094. return;
  1095. }
  1096. parent::get_session_lock($rowid, $timeout);
  1097. $timeoutmilli = $timeout * 1000;
  1098. $fullname = $this->dbname.'-'.$this->prefix.'-session-'.$rowid;
  1099. // There is one bug in PHP/freetds (both reproducible with mssql_query()
  1100. // and its mssql_init()/mssql_bind()/mssql_execute() alternative) for
  1101. // stored procedures, causing scalar results of the execution
  1102. // to be cast to boolean (true/fals). Here there is one
  1103. // workaround that forces the return of one recordset resource.
  1104. // $sql = "sp_getapplock '$fullname', 'Exclusive', 'Session', $timeoutmilli";
  1105. $sql = "BEGIN
  1106. DECLARE @result INT
  1107. EXECUTE @result = sp_getapplock @Resource='$fullname',
  1108. @LockMode='Exclusive',
  1109. @LockOwner='Session',
  1110. @LockTimeout='$timeoutmilli'
  1111. SELECT @result
  1112. END";
  1113. $this->query_start($sql, null, SQL_QUERY_AUX);
  1114. $result = mssql_query($sql, $this->mssql);
  1115. $this->query_end($result);
  1116. if ($result) {
  1117. $row = mssql_fetch_row($result);
  1118. if ($row[0] < 0) {
  1119. throw new dml_sessionwait_exception();
  1120. }
  1121. }
  1122. $this->free_result($result);
  1123. }
  1124. public function release_session_lock($rowid) {
  1125. if (!$this->session_lock_supported()) {
  1126. return;
  1127. }
  1128. if (!$this->used_for_db_sessions) {
  1129. return;
  1130. }
  1131. parent::release_session_lock($rowid);
  1132. $fullname = $this->dbname.'-'.$this->prefix.'-session-'.$rowid;
  1133. $sql = "sp_releaseapplock '$fullname', 'Session…

Large files files are truncated, but you can click here to view the full file