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.

337 lines
9.5 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 DBLIB 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_dblib_driver extends CI_DB_pdo_driver {
  53. /**
  54. * Sub-driver
  55. *
  56. * @var string
  57. */
  58. public $subdriver = 'dblib';
  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 = $params['subdriver'].':host='.(empty($this->hostname) ? '127.0.0.1' : $this->hostname);
  90. if ( ! empty($this->port))
  91. {
  92. $this->dsn .= (DIRECTORY_SEPARATOR === '\\' ? ',' : ':').$this->port;
  93. }
  94. empty($this->database) OR $this->dsn .= ';dbname='.$this->database;
  95. empty($this->char_set) OR $this->dsn .= ';charset='.$this->char_set;
  96. empty($this->appname) OR $this->dsn .= ';appname='.$this->appname;
  97. }
  98. else
  99. {
  100. if ( ! empty($this->char_set) && strpos($this->dsn, 'charset=', 6) === FALSE)
  101. {
  102. $this->dsn .= ';charset='.$this->char_set;
  103. }
  104. $this->subdriver = 'dblib';
  105. }
  106. }
  107. // --------------------------------------------------------------------
  108. /**
  109. * Database connection
  110. *
  111. * @param bool $persistent
  112. * @return object
  113. */
  114. public function db_connect($persistent = FALSE)
  115. {
  116. if ($persistent === TRUE)
  117. {
  118. log_message('debug', "dblib driver doesn't support persistent connections");
  119. }
  120. $this->conn_id = parent::db_connect(FALSE);
  121. if ( ! is_object($this->conn_id))
  122. {
  123. return $this->conn_id;
  124. }
  125. // Determine how identifiers are escaped
  126. $query = $this->query('SELECT CASE WHEN (@@OPTIONS | 256) = @@OPTIONS THEN 1 ELSE 0 END AS qi');
  127. $query = $query->row_array();
  128. $this->_quoted_identifier = empty($query) ? FALSE : (bool) $query['qi'];
  129. $this->_escape_char = ($this->_quoted_identifier) ? '"' : array('[', ']');
  130. return $this->conn_id;
  131. }
  132. // --------------------------------------------------------------------
  133. /**
  134. * Show table query
  135. *
  136. * Generates a platform-specific query string so that the table names can be fetched
  137. *
  138. * @param bool $prefix_limit
  139. * @return string
  140. */
  141. protected function _list_tables($prefix_limit = FALSE)
  142. {
  143. $sql = 'SELECT '.$this->escape_identifiers('name')
  144. .' FROM '.$this->escape_identifiers('sysobjects')
  145. .' WHERE '.$this->escape_identifiers('type')." = 'U'";
  146. if ($prefix_limit === TRUE && $this->dbprefix !== '')
  147. {
  148. $sql .= ' AND '.$this->escape_identifiers('name')." LIKE '".$this->escape_like_str($this->dbprefix)."%' "
  149. .sprintf($this->_like_escape_str, $this->_like_escape_chr);
  150. }
  151. return $sql.' ORDER BY '.$this->escape_identifiers('name');
  152. }
  153. // --------------------------------------------------------------------
  154. /**
  155. * Show column query
  156. *
  157. * Generates a platform-specific query string so that the column names can be fetched
  158. *
  159. * @param string $table
  160. * @return string
  161. */
  162. protected function _list_columns($table = '')
  163. {
  164. return 'SELECT COLUMN_NAME
  165. FROM INFORMATION_SCHEMA.Columns
  166. WHERE UPPER(TABLE_NAME) = '.$this->escape(strtoupper($table));
  167. }
  168. // --------------------------------------------------------------------
  169. /**
  170. * Returns an object with field data
  171. *
  172. * @param string $table
  173. * @return array
  174. */
  175. public function field_data($table)
  176. {
  177. $sql = 'SELECT COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION, COLUMN_DEFAULT
  178. FROM INFORMATION_SCHEMA.Columns
  179. WHERE UPPER(TABLE_NAME) = '.$this->escape(strtoupper($table));
  180. if (($query = $this->query($sql)) === FALSE)
  181. {
  182. return FALSE;
  183. }
  184. $query = $query->result_object();
  185. $retval = array();
  186. for ($i = 0, $c = count($query); $i < $c; $i++)
  187. {
  188. $retval[$i] = new stdClass();
  189. $retval[$i]->name = $query[$i]->COLUMN_NAME;
  190. $retval[$i]->type = $query[$i]->DATA_TYPE;
  191. $retval[$i]->max_length = ($query[$i]->CHARACTER_MAXIMUM_LENGTH > 0) ? $query[$i]->CHARACTER_MAXIMUM_LENGTH : $query[$i]->NUMERIC_PRECISION;
  192. $retval[$i]->default = $query[$i]->COLUMN_DEFAULT;
  193. }
  194. return $retval;
  195. }
  196. // --------------------------------------------------------------------
  197. /**
  198. * Update statement
  199. *
  200. * Generates a platform-specific update string from the supplied data
  201. *
  202. * @param string $table
  203. * @param array $values
  204. * @return string
  205. */
  206. protected function _update($table, $values)
  207. {
  208. $this->qb_limit = FALSE;
  209. $this->qb_orderby = array();
  210. return parent::_update($table, $values);
  211. }
  212. // --------------------------------------------------------------------
  213. /**
  214. * Delete statement
  215. *
  216. * Generates a platform-specific delete string from the supplied data
  217. *
  218. * @param string $table
  219. * @return string
  220. */
  221. protected function _delete($table)
  222. {
  223. if ($this->qb_limit)
  224. {
  225. return 'WITH ci_delete AS (SELECT TOP '.$this->qb_limit.' * FROM '.$table.$this->_compile_wh('qb_where').') DELETE FROM ci_delete';
  226. }
  227. return parent::_delete($table);
  228. }
  229. // --------------------------------------------------------------------
  230. /**
  231. * LIMIT
  232. *
  233. * Generates a platform-specific LIMIT clause
  234. *
  235. * @param string $sql SQL Query
  236. * @return string
  237. */
  238. protected function _limit($sql)
  239. {
  240. $limit = $this->qb_offset + $this->qb_limit;
  241. // As of SQL Server 2005 (9.0.*) ROW_NUMBER() is supported,
  242. // however an ORDER BY clause is required for it to work
  243. if (version_compare($this->version(), '9', '>=') && $this->qb_offset && ! empty($this->qb_orderby))
  244. {
  245. $orderby = $this->_compile_order_by();
  246. // We have to strip the ORDER BY clause
  247. $sql = trim(substr($sql, 0, strrpos($sql, $orderby)));
  248. // Get the fields to select from our subquery, so that we can avoid CI_rownum appearing in the actual results
  249. if (count($this->qb_select) === 0)
  250. {
  251. $select = '*'; // Inevitable
  252. }
  253. else
  254. {
  255. // Use only field names and their aliases, everything else is out of our scope.
  256. $select = array();
  257. $field_regexp = ($this->_quoted_identifier)
  258. ? '("[^\"]+")' : '(\[[^\]]+\])';
  259. for ($i = 0, $c = count($this->qb_select); $i < $c; $i++)
  260. {
  261. $select[] = preg_match('/(?:\s|\.)'.$field_regexp.'$/i', $this->qb_select[$i], $m)
  262. ? $m[1] : $this->qb_select[$i];
  263. }
  264. $select = implode(', ', $select);
  265. }
  266. return 'SELECT '.$select." FROM (\n\n"
  267. .preg_replace('/^(SELECT( DISTINCT)?)/i', '\\1 ROW_NUMBER() OVER('.trim($orderby).') AS '.$this->escape_identifiers('CI_rownum').', ', $sql)
  268. ."\n\n) ".$this->escape_identifiers('CI_subquery')
  269. ."\nWHERE ".$this->escape_identifiers('CI_rownum').' BETWEEN '.($this->qb_offset + 1).' AND '.$limit;
  270. }
  271. return preg_replace('/(^\SELECT (DISTINCT)?)/i','\\1 TOP '.$limit.' ', $sql);
  272. }
  273. // --------------------------------------------------------------------
  274. /**
  275. * Insert batch statement
  276. *
  277. * Generates a platform-specific insert string from the supplied data.
  278. *
  279. * @param string $table Table name
  280. * @param array $keys INSERT keys
  281. * @param array $values INSERT values
  282. * @return string|bool
  283. */
  284. protected function _insert_batch($table, $keys, $values)
  285. {
  286. // Multiple-value inserts are only supported as of SQL Server 2008
  287. if (version_compare($this->version(), '10', '>='))
  288. {
  289. return parent::_insert_batch($table, $keys, $values);
  290. }
  291. return ($this->db_debug) ? $this->display_error('db_unsupported_feature') : FALSE;
  292. }
  293. }