You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

369 lines
11 KiB

7 years ago
  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 - 2017, 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 - 2017, 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 3.0.0
  36. * @filesource
  37. */
  38. defined('BASEPATH') OR exit('No direct script access allowed');
  39. /**
  40. * PDO SQLSRV 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_pdo_sqlsrv_driver extends CI_DB_pdo_driver {
  53. /**
  54. * Sub-driver
  55. *
  56. * @var string
  57. */
  58. public $subdriver = 'sqlsrv';
  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;
  75. // --------------------------------------------------------------------
  76. /**
  77. * Class constructor
  78. *
  79. * Builds the DSN if not already set.
  80. *
  81. * @param array $params
  82. * @return void
  83. */
  84. public function __construct($params)
  85. {
  86. parent::__construct($params);
  87. if (empty($this->dsn))
  88. {
  89. $this->dsn = 'sqlsrv:Server='.(empty($this->hostname) ? '127.0.0.1' : $this->hostname);
  90. empty($this->port) OR $this->dsn .= ','.$this->port;
  91. empty($this->database) OR $this->dsn .= ';Database='.$this->database;
  92. // Some custom options
  93. if (isset($this->QuotedId))
  94. {
  95. $this->dsn .= ';QuotedId='.$this->QuotedId;
  96. $this->_quoted_identifier = (bool) $this->QuotedId;
  97. }
  98. if (isset($this->ConnectionPooling))
  99. {
  100. $this->dsn .= ';ConnectionPooling='.$this->ConnectionPooling;
  101. }
  102. if ($this->encrypt === TRUE)
  103. {
  104. $this->dsn .= ';Encrypt=1';
  105. }
  106. if (isset($this->TraceOn))
  107. {
  108. $this->dsn .= ';TraceOn='.$this->TraceOn;
  109. }
  110. if (isset($this->TrustServerCertificate))
  111. {
  112. $this->dsn .= ';TrustServerCertificate='.$this->TrustServerCertificate;
  113. }
  114. empty($this->APP) OR $this->dsn .= ';APP='.$this->APP;
  115. empty($this->Failover_Partner) OR $this->dsn .= ';Failover_Partner='.$this->Failover_Partner;
  116. empty($this->LoginTimeout) OR $this->dsn .= ';LoginTimeout='.$this->LoginTimeout;
  117. empty($this->MultipleActiveResultSets) OR $this->dsn .= ';MultipleActiveResultSets='.$this->MultipleActiveResultSets;
  118. empty($this->TraceFile) OR $this->dsn .= ';TraceFile='.$this->TraceFile;
  119. empty($this->WSID) OR $this->dsn .= ';WSID='.$this->WSID;
  120. }
  121. elseif (preg_match('/QuotedId=(0|1)/', $this->dsn, $match))
  122. {
  123. $this->_quoted_identifier = (bool) $match[1];
  124. }
  125. }
  126. // --------------------------------------------------------------------
  127. /**
  128. * Database connection
  129. *
  130. * @param bool $persistent
  131. * @return object
  132. */
  133. public function db_connect($persistent = FALSE)
  134. {
  135. if ( ! empty($this->char_set) && preg_match('/utf[^8]*8/i', $this->char_set))
  136. {
  137. $this->options[PDO::SQLSRV_ENCODING_UTF8] = 1;
  138. }
  139. $this->conn_id = parent::db_connect($persistent);
  140. if ( ! is_object($this->conn_id) OR is_bool($this->_quoted_identifier))
  141. {
  142. return $this->conn_id;
  143. }
  144. // Determine how identifiers are escaped
  145. $query = $this->query('SELECT CASE WHEN (@@OPTIONS | 256) = @@OPTIONS THEN 1 ELSE 0 END AS qi');
  146. $query = $query->row_array();
  147. $this->_quoted_identifier = empty($query) ? FALSE : (bool) $query['qi'];
  148. $this->_escape_char = ($this->_quoted_identifier) ? '"' : array('[', ']');
  149. return $this->conn_id;
  150. }
  151. // --------------------------------------------------------------------
  152. /**
  153. * Show table query
  154. *
  155. * Generates a platform-specific query string so that the table names can be fetched
  156. *
  157. * @param bool $prefix_limit
  158. * @return string
  159. */
  160. protected function _list_tables($prefix_limit = FALSE)
  161. {
  162. $sql = 'SELECT '.$this->escape_identifiers('name')
  163. .' FROM '.$this->escape_identifiers('sysobjects')
  164. .' WHERE '.$this->escape_identifiers('type')." = 'U'";
  165. if ($prefix_limit === TRUE && $this->dbprefix !== '')
  166. {
  167. $sql .= ' AND '.$this->escape_identifiers('name')." LIKE '".$this->escape_like_str($this->dbprefix)."%' "
  168. .sprintf($this->_like_escape_str, $this->_like_escape_chr);
  169. }
  170. return $sql.' ORDER BY '.$this->escape_identifiers('name');
  171. }
  172. // --------------------------------------------------------------------
  173. /**
  174. * Show column query
  175. *
  176. * Generates a platform-specific query string so that the column names can be fetched
  177. *
  178. * @param string $table
  179. * @return string
  180. */
  181. protected function _list_columns($table = '')
  182. {
  183. return 'SELECT COLUMN_NAME
  184. FROM INFORMATION_SCHEMA.Columns
  185. WHERE UPPER(TABLE_NAME) = '.$this->escape(strtoupper($table));
  186. }
  187. // --------------------------------------------------------------------
  188. /**
  189. * Returns an object with field data
  190. *
  191. * @param string $table
  192. * @return array
  193. */
  194. public function field_data($table)
  195. {
  196. $sql = 'SELECT COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION, COLUMN_DEFAULT
  197. FROM INFORMATION_SCHEMA.Columns
  198. WHERE UPPER(TABLE_NAME) = '.$this->escape(strtoupper($table));
  199. if (($query = $this->query($sql)) === FALSE)
  200. {
  201. return FALSE;
  202. }
  203. $query = $query->result_object();
  204. $retval = array();
  205. for ($i = 0, $c = count($query); $i < $c; $i++)
  206. {
  207. $retval[$i] = new stdClass();
  208. $retval[$i]->name = $query[$i]->COLUMN_NAME;
  209. $retval[$i]->type = $query[$i]->DATA_TYPE;
  210. $retval[$i]->max_length = ($query[$i]->CHARACTER_MAXIMUM_LENGTH > 0) ? $query[$i]->CHARACTER_MAXIMUM_LENGTH : $query[$i]->NUMERIC_PRECISION;
  211. $retval[$i]->default = $query[$i]->COLUMN_DEFAULT;
  212. }
  213. return $retval;
  214. }
  215. // --------------------------------------------------------------------
  216. /**
  217. * Update statement
  218. *
  219. * Generates a platform-specific update string from the supplied data
  220. *
  221. * @param string $table
  222. * @param array $values
  223. * @return string
  224. */
  225. protected function _update($table, $values)
  226. {
  227. $this->qb_limit = FALSE;
  228. $this->qb_orderby = array();
  229. return parent::_update($table, $values);
  230. }
  231. // --------------------------------------------------------------------
  232. /**
  233. * Delete statement
  234. *
  235. * Generates a platform-specific delete string from the supplied data
  236. *
  237. * @param string $table
  238. * @return string
  239. */
  240. protected function _delete($table)
  241. {
  242. if ($this->qb_limit)
  243. {
  244. return 'WITH ci_delete AS (SELECT TOP '.$this->qb_limit.' * FROM '.$table.$this->_compile_wh('qb_where').') DELETE FROM ci_delete';
  245. }
  246. return parent::_delete($table);
  247. }
  248. // --------------------------------------------------------------------
  249. /**
  250. * LIMIT
  251. *
  252. * Generates a platform-specific LIMIT clause
  253. *
  254. * @param string $sql SQL Query
  255. * @return string
  256. */
  257. protected function _limit($sql)
  258. {
  259. // As of SQL Server 2012 (11.0.*) OFFSET is supported
  260. if (version_compare($this->version(), '11', '>='))
  261. {
  262. // SQL Server OFFSET-FETCH can be used only with the ORDER BY clause
  263. empty($this->qb_orderby) && $sql .= ' ORDER BY 1';
  264. return $sql.' OFFSET '.(int) $this->qb_offset.' ROWS FETCH NEXT '.$this->qb_limit.' ROWS ONLY';
  265. }
  266. $limit = $this->qb_offset + $this->qb_limit;
  267. // An ORDER BY clause is required for ROW_NUMBER() to work
  268. if ($this->qb_offset && ! empty($this->qb_orderby))
  269. {
  270. $orderby = $this->_compile_order_by();
  271. // We have to strip the ORDER BY clause
  272. $sql = trim(substr($sql, 0, strrpos($sql, $orderby)));
  273. // Get the fields to select from our subquery, so that we can avoid CI_rownum appearing in the actual results
  274. if (count($this->qb_select) === 0)
  275. {
  276. $select = '*'; // Inevitable
  277. }
  278. else
  279. {
  280. // Use only field names and their aliases, everything else is out of our scope.
  281. $select = array();
  282. $field_regexp = ($this->_quoted_identifier)
  283. ? '("[^\"]+")' : '(\[[^\]]+\])';
  284. for ($i = 0, $c = count($this->qb_select); $i < $c; $i++)
  285. {
  286. $select[] = preg_match('/(?:\s|\.)'.$field_regexp.'$/i', $this->qb_select[$i], $m)
  287. ? $m[1] : $this->qb_select[$i];
  288. }
  289. $select = implode(', ', $select);
  290. }
  291. return 'SELECT '.$select." FROM (\n\n"
  292. .preg_replace('/^(SELECT( DISTINCT)?)/i', '\\1 ROW_NUMBER() OVER('.trim($orderby).') AS '.$this->escape_identifiers('CI_rownum').', ', $sql)
  293. ."\n\n) ".$this->escape_identifiers('CI_subquery')
  294. ."\nWHERE ".$this->escape_identifiers('CI_rownum').' BETWEEN '.($this->qb_offset + 1).' AND '.$limit;
  295. }
  296. return preg_replace('/(^\SELECT (DISTINCT)?)/i','\\1 TOP '.$limit.' ', $sql);
  297. }
  298. // --------------------------------------------------------------------
  299. /**
  300. * Insert batch statement
  301. *
  302. * Generates a platform-specific insert string from the supplied data.
  303. *
  304. * @param string $table Table name
  305. * @param array $keys INSERT keys
  306. * @param array $values INSERT values
  307. * @return string|bool
  308. */
  309. protected function _insert_batch($table, $keys, $values)
  310. {
  311. // Multiple-value inserts are only supported as of SQL Server 2008
  312. if (version_compare($this->version(), '10', '>='))
  313. {
  314. return parent::_insert_batch($table, $keys, $values);
  315. }
  316. return ($this->db_debug) ? $this->display_error('db_unsupported_feature') : FALSE;
  317. }
  318. }