PageRenderTime 55ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/dml/mssql_native_moodle_database.php

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