PageRenderTime 41ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/fp_ci/system/database/drivers/mssql/mssql_driver.php

https://gitlab.com/jLKisni/furandpaw-frontend
PHP | 518 lines | 433 code | 8 blank | 77 comment | 1 complexity | 4227fbb8f9d5f0304958bc1c9b886435 MD5 | raw file
  1. <?php
  2. /**
  3. * CodeIgniter
  4. *
  5. * An open source application development framework for PHP
  6. *
  7. * This content is released under the MIT License (MIT)
  8. *
  9. * Copyright (c) 2014 - 2016, British Columbia Institute of Technology
  10. *
  11. * Permission is hereby granted, free of charge, to any person obtaining a copy
  12. * of this software and associated documentation files (the "Software"), to deal
  13. * in the Software without restriction, including without limitation the rights
  14. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15. * copies of the Software, and to permit persons to whom the Software is
  16. * furnished to do so, subject to the following conditions:
  17. *
  18. * The above copyright notice and this permission notice shall be included in
  19. * all copies or substantial portions of the Software.
  20. *
  21. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  22. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  23. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  24. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  25. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  26. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  27. * THE SOFTWARE.
  28. *
  29. * @package CodeIgniter
  30. * @author EllisLab Dev Team
  31. * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
  32. * @copyright Copyright (c) 2014 - 2016, British Columbia Institute of Technology (http://bcit.ca/)
  33. * @license http://opensource.org/licenses/MIT MIT License
  34. * @link https://codeigniter.com
  35. * @since Version 1.3.0
  36. * @filesource
  37. */
  38. defined('BASEPATH') OR exit('No direct script access allowed');
  39. /**
  40. * MS SQL Database Adapter Class
  41. *
  42. * Note: _DB is an extender class that the app controller
  43. * creates dynamically based on whether the query builder
  44. * class is being used or not.
  45. *
  46. * @package CodeIgniter
  47. * @subpackage Drivers
  48. * @category Database
  49. * @author EllisLab Dev Team
  50. * @link https://codeigniter.com/user_guide/database/
  51. */
  52. class CI_DB_mssql_driver extends CI_DB {
  53. /**
  54. * Database driver
  55. *
  56. * @var string
  57. */
  58. public $dbdriver = 'mssql';
  59. // --------------------------------------------------------------------
  60. /**
  61. * ORDER BY random keyword
  62. *
  63. * @var array
  64. */
  65. protected $_random_keyword = array('NEWID()', 'RAND(%d)');
  66. /**
  67. * Quoted identifier flag
  68. *
  69. * Whether to use SQL-92 standard quoted identifier
  70. * (double quotes) or brackets for identifier escaping.
  71. *
  72. * @var bool
  73. */
  74. protected $_quoted_identifier = TRUE;
  75. // --------------------------------------------------------------------
  76. /**
  77. * Class constructor
  78. *
  79. * Appends the port number to the hostname, if needed.
  80. *
  81. * @param array $params
  82. * @return void
  83. */
  84. public function __construct($params)
  85. {
  86. parent::__construct($params);
  87. if ( ! empty($this->port))
  88. {
  89. $this->hostname .= (DIRECTORY_SEPARATOR === '\\' ? ',' : ':').$this->port;
  90. }
  91. }
  92. // --------------------------------------------------------------------
  93. /**
  94. * Non-persistent database connection
  95. *
  96. * @param bool $persistent
  97. * @return resource
  98. */
  99. public function db_connect($persistent = FALSE)
  100. {
  101. $this->conn_id = ($persistent)
  102. ? mssql_pconnect($this->hostname, $this->username, $this->password)
  103. : mssql_connect($this->hostname, $this->username, $this->password);
  104. if ( ! $this->conn_id)
  105. {
  106. return FALSE;
  107. }
  108. // ----------------------------------------------------------------
  109. // Select the DB... assuming a database name is specified in the config file
  110. if ($this->database !== '' && ! $this->db_select())
  111. {
  112. log_message('error', 'Unable to select database: '.$this->database);
  113. return ($this->db_debug === TRUE)
  114. ? $this->display_error('db_unable_to_select', $this->database)
  115. : FALSE;
  116. }
  117. // Determine how identifiers are escaped
  118. $query = $this->query('SELECT CASE WHEN (@@OPTIONS | 256) = @@OPTIONS THEN 1 ELSE 0 END AS qi');
  119. $query = $query->row_array();
  120. $this->_quoted_identifier = empty($query) ? FALSE : (bool) $query['qi'];
  121. $this->_escape_char = ($this->_quoted_identifier) ? '"' : array('[', ']');
  122. return $this->conn_id;
  123. }
  124. // --------------------------------------------------------------------
  125. /**
  126. * Select the database
  127. *
  128. * @param string $database
  129. * @return bool
  130. */
  131. public function db_select($database = '')
  132. {
  133. if ($database === '')
  134. {
  135. $database = $this->database;
  136. }
  137. // Note: Escaping is required in the event that the DB name
  138. // contains reserved characters.
  139. if (mssql_select_db('['.$database.']', $this->conn_id))
  140. {
  141. $this->database = $database;
  142. $this->data_cache = array();
  143. return TRUE;
  144. }
  145. return FALSE;
  146. }
  147. // --------------------------------------------------------------------
  148. /**
  149. * Execute the query
  150. *
  151. * @param string $sql an SQL query
  152. * @return mixed resource if rows are returned, bool otherwise
  153. */
  154. protected function _execute($sql)
  155. {
  156. return mssql_query($sql, $this->conn_id);
  157. }
  158. // --------------------------------------------------------------------
  159. /**
  160. * Begin Transaction
  161. *
  162. * @return bool
  163. */
  164. protected function _trans_begin()
  165. {
  166. return $this->simple_query('BEGIN TRAN');
  167. }
  168. // --------------------------------------------------------------------
  169. /**
  170. * Commit Transaction
  171. *
  172. * @return bool
  173. */
  174. protected function _trans_commit()
  175. {
  176. return $this->simple_query('COMMIT TRAN');
  177. }
  178. // --------------------------------------------------------------------
  179. /**
  180. * Rollback Transaction
  181. *
  182. * @return bool
  183. */
  184. protected function _trans_rollback()
  185. {
  186. return $this->simple_query('ROLLBACK TRAN');
  187. }
  188. // --------------------------------------------------------------------
  189. /**
  190. * Affected Rows
  191. *
  192. * @return int
  193. */
  194. public function affected_rows()
  195. {
  196. return mssql_rows_affected($this->conn_id);
  197. }
  198. // --------------------------------------------------------------------
  199. /**
  200. * Insert ID
  201. *
  202. * Returns the last id created in the Identity column.
  203. *
  204. * @return string
  205. */
  206. public function insert_id()
  207. {
  208. $query = version_compare($this->version(), '8', '>=')
  209. ? 'SELECT SCOPE_IDENTITY() AS last_id'
  210. : 'SELECT @@IDENTITY AS last_id';
  211. $query = $this->query($query);
  212. $query = $query->row();
  213. return $query->last_id;
  214. }
  215. // --------------------------------------------------------------------
  216. /**
  217. * Set client character set
  218. *
  219. * @param string $charset
  220. * @return bool
  221. */
  222. protected function _db_set_charset($charset)
  223. {
  224. return (ini_set('mssql.charset', $charset) !== FALSE);
  225. }
  226. // --------------------------------------------------------------------
  227. /**
  228. * Version number query string
  229. *
  230. * @return string
  231. */
  232. protected function _version()
  233. {
  234. return "SELECT SERVERPROPERTY('ProductVersion') AS ver";
  235. }
  236. // --------------------------------------------------------------------
  237. /**
  238. * List table query
  239. *
  240. * Generates a platform-specific query string so that the table names can be fetched
  241. *
  242. * @param bool $prefix_limit
  243. * @return string
  244. */
  245. protected function _list_tables($prefix_limit = FALSE)
  246. {
  247. $sql = 'SELECT '.$this->escape_identifiers('name')
  248. .' FROM '.$this->escape_identifiers('sysobjects')
  249. .' WHERE '.$this->escape_identifiers('type')." = 'U'";
  250. if ($prefix_limit !== FALSE && $this->dbprefix !== '')
  251. {
  252. $sql .= ' AND '.$this->escape_identifiers('name')." LIKE '".$this->escape_like_str($this->dbprefix)."%' "
  253. .sprintf($this->_like_escape_str, $this->_like_escape_chr);
  254. }
  255. return $sql.' ORDER BY '.$this->escape_identifiers('name');
  256. }
  257. // --------------------------------------------------------------------
  258. /**
  259. * List column query
  260. *
  261. * Generates a platform-specific query string so that the column names can be fetched
  262. *
  263. * @param string $table
  264. * @return string
  265. */
  266. protected function _list_columns($table = '')
  267. {
  268. return 'SELECT COLUMN_NAME
  269. FROM INFORMATION_SCHEMA.Columns
  270. WHERE UPPER(TABLE_NAME) = '.$this->escape(strtoupper($table));
  271. }
  272. // --------------------------------------------------------------------
  273. /**
  274. * Returns an object with field data
  275. *
  276. * @param string $table
  277. * @return array
  278. */
  279. public function field_data($table)
  280. {
  281. $sql = 'SELECT COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION, COLUMN_DEFAULT
  282. FROM INFORMATION_SCHEMA.Columns
  283. WHERE UPPER(TABLE_NAME) = '.$this->escape(strtoupper($table));
  284. if (($query = $this->query($sql)) === FALSE)
  285. {
  286. return FALSE;
  287. }
  288. $query = $query->result_object();
  289. $retval = array();
  290. for ($i = 0, $c = count($query); $i < $c; $i++)
  291. {
  292. $retval[$i] = new stdClass();
  293. $retval[$i]->name = $query[$i]->COLUMN_NAME;
  294. $retval[$i]->type = $query[$i]->DATA_TYPE;
  295. $retval[$i]->max_length = ($query[$i]->CHARACTER_MAXIMUM_LENGTH > 0) ? $query[$i]->CHARACTER_MAXIMUM_LENGTH : $query[$i]->NUMERIC_PRECISION;
  296. $retval[$i]->default = $query[$i]->COLUMN_DEFAULT;
  297. }
  298. return $retval;
  299. }
  300. // --------------------------------------------------------------------
  301. /**
  302. * Error
  303. *
  304. * Returns an array containing code and message of the last
  305. * database error that has occured.
  306. *
  307. * @return array
  308. */
  309. public function error()
  310. {
  311. // We need this because the error info is discarded by the
  312. // server the first time you request it, and query() already
  313. // calls error() once for logging purposes when a query fails.
  314. static $error = array('code' => 0, 'message' => NULL);
  315. $message = mssql_get_last_message();
  316. if ( ! empty($message))
  317. {
  318. $error['code'] = $this->query('SELECT @@ERROR AS code')->row()->code;
  319. $error['message'] = $message;
  320. }
  321. return $error;
  322. }
  323. // --------------------------------------------------------------------
  324. /**
  325. * Update statement
  326. *
  327. * Generates a platform-specific update string from the supplied data
  328. *
  329. * @param string $table
  330. * @param array $values
  331. * @return string
  332. */
  333. protected function _update($table, $values)
  334. {
  335. $this->qb_limit = FALSE;
  336. $this->qb_orderby = array();
  337. return parent::_update($table, $values);
  338. }
  339. // --------------------------------------------------------------------
  340. /**
  341. * Truncate statement
  342. *
  343. * Generates a platform-specific truncate string from the supplied data
  344. *
  345. * If the database does not support the TRUNCATE statement,
  346. * then this method maps to 'DELETE FROM table'
  347. *
  348. * @param string $table
  349. * @return string
  350. */
  351. protected function _truncate($table)
  352. {
  353. return 'TRUNCATE TABLE '.$table;
  354. }
  355. // --------------------------------------------------------------------
  356. /**
  357. * Delete statement
  358. *
  359. * Generates a platform-specific delete string from the supplied data
  360. *
  361. * @param string $table
  362. * @return string
  363. */
  364. protected function _delete($table)
  365. {
  366. if ($this->qb_limit)
  367. {
  368. return 'WITH ci_delete AS (SELECT TOP '.$this->qb_limit.' * FROM '.$table.$this->_compile_wh('qb_where').') DELETE FROM ci_delete';
  369. }
  370. return parent::_delete($table);
  371. }
  372. // --------------------------------------------------------------------
  373. /**
  374. * LIMIT
  375. *
  376. * Generates a platform-specific LIMIT clause
  377. *
  378. * @param string $sql SQL Query
  379. * @return string
  380. */
  381. protected function _limit($sql)
  382. {
  383. $limit = $this->qb_offset + $this->qb_limit;
  384. // As of SQL Server 2005 (9.0.*) ROW_NUMBER() is supported,
  385. // however an ORDER BY clause is required for it to work
  386. if (version_compare($this->version(), '9', '>=') && $this->qb_offset && ! empty($this->qb_orderby))
  387. {
  388. $orderby = $this->_compile_order_by();
  389. // We have to strip the ORDER BY clause
  390. $sql = trim(substr($sql, 0, strrpos($sql, $orderby)));
  391. // Get the fields to select from our subquery, so that we can avoid CI_rownum appearing in the actual results
  392. if (count($this->qb_select) === 0)
  393. {
  394. $select = '*'; // Inevitable
  395. }
  396. else
  397. {
  398. // Use only field names and their aliases, everything else is out of our scope.
  399. $select = array();
  400. $field_regexp = ($this->_quoted_identifier)
  401. ? '("[^\"]+")' : '(\[[^\]]+\])';
  402. for ($i = 0, $c = count($this->qb_select); $i < $c; $i++)
  403. {
  404. $select[] = preg_match('/(?:\s|\.)'.$field_regexp.'$/i', $this->qb_select[$i], $m)
  405. ? $m[1] : $this->qb_select[$i];
  406. }
  407. $select = implode(', ', $select);
  408. }
  409. return 'SELECT '.$select." FROM (\n\n"
  410. .preg_replace('/^(SELECT( DISTINCT)?)/i', '\\1 ROW_NUMBER() OVER('.trim($orderby).') AS '.$this->escape_identifiers('CI_rownum').', ', $sql)
  411. ."\n\n) ".$this->escape_identifiers('CI_subquery')
  412. ."\nWHERE ".$this->escape_identifiers('CI_rownum').' BETWEEN '.($this->qb_offset + 1).' AND '.$limit;
  413. }
  414. return preg_replace('/(^\SELECT (DISTINCT)?)/i','\\1 TOP '.$limit.' ', $sql);
  415. }
  416. // --------------------------------------------------------------------
  417. /**
  418. * Insert batch statement
  419. *
  420. * Generates a platform-specific insert string from the supplied data.
  421. *
  422. * @param string $table Table name
  423. * @param array $keys INSERT keys
  424. * @param array $values INSERT values
  425. * @return string|bool
  426. */
  427. protected function _insert_batch($table, $keys, $values)
  428. {
  429. // Multiple-value inserts are only supported as of SQL Server 2008
  430. if (version_compare($this->version(), '10', '>='))
  431. {
  432. return parent::_insert_batch($table, $keys, $values);
  433. }
  434. return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE;
  435. }
  436. // --------------------------------------------------------------------
  437. /**
  438. * Close DB Connection
  439. *
  440. * @return void
  441. */
  442. protected function _close()
  443. {
  444. mssql_close($this->conn_id);
  445. }
  446. }