PageRenderTime 65ms CodeModel.GetById 35ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/dml/mssql_native_moodle_database.php

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

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