Sqlserver.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  1. <?php
  2. /**
  3. * MS SQL Server layer for DBO
  4. *
  5. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  6. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  7. *
  8. * Licensed under The MIT License
  9. * For full copyright and license information, please see the LICENSE.txt
  10. * Redistributions of files must retain the above copyright notice.
  11. *
  12. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  13. * @link http://cakephp.org CakePHP(tm) Project
  14. * @package Cake.Model.Datasource.Database
  15. * @since CakePHP(tm) v 0.10.5.1790
  16. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  17. */
  18. App::uses('DboSource', 'Model/Datasource');
  19. /**
  20. * Dbo layer for Microsoft's official SQLServer driver
  21. *
  22. * A Dbo layer for MS SQL Server 2005 and higher. Requires the
  23. * `pdo_sqlsrv` extension to be enabled.
  24. *
  25. * @link http://www.php.net/manual/en/ref.pdo-sqlsrv.php
  26. *
  27. * @package Cake.Model.Datasource.Database
  28. */
  29. class Sqlserver extends DboSource {
  30. /**
  31. * Driver description
  32. *
  33. * @var string
  34. */
  35. public $description = "SQL Server DBO Driver";
  36. /**
  37. * Starting quote character for quoted identifiers
  38. *
  39. * @var string
  40. */
  41. public $startQuote = "[";
  42. /**
  43. * Ending quote character for quoted identifiers
  44. *
  45. * @var string
  46. */
  47. public $endQuote = "]";
  48. /**
  49. * Creates a map between field aliases and numeric indexes. Workaround for the
  50. * SQL Server driver's 30-character column name limitation.
  51. *
  52. * @var array
  53. */
  54. protected $_fieldMappings = array();
  55. /**
  56. * Storing the last affected value
  57. *
  58. * @var mixed
  59. */
  60. protected $_lastAffected = false;
  61. /**
  62. * Base configuration settings for MS SQL driver
  63. *
  64. * @var array
  65. */
  66. protected $_baseConfig = array(
  67. 'persistent' => true,
  68. 'host' => 'localhost\SQLEXPRESS',
  69. 'login' => '',
  70. 'password' => '',
  71. 'database' => 'cake',
  72. 'schema' => '',
  73. );
  74. /**
  75. * MS SQL column definition
  76. *
  77. * @var array
  78. */
  79. public $columns = array(
  80. 'primary_key' => array('name' => 'IDENTITY (1, 1) NOT NULL'),
  81. 'string' => array('name' => 'nvarchar', 'limit' => '255'),
  82. 'text' => array('name' => 'nvarchar', 'limit' => 'MAX'),
  83. 'integer' => array('name' => 'int', 'formatter' => 'intval'),
  84. 'biginteger' => array('name' => 'bigint'),
  85. 'float' => array('name' => 'numeric', 'formatter' => 'floatval'),
  86. 'datetime' => array('name' => 'datetime', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
  87. 'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
  88. 'time' => array('name' => 'datetime', 'format' => 'H:i:s', 'formatter' => 'date'),
  89. 'date' => array('name' => 'datetime', 'format' => 'Y-m-d', 'formatter' => 'date'),
  90. 'binary' => array('name' => 'varbinary'),
  91. 'boolean' => array('name' => 'bit')
  92. );
  93. /**
  94. * Magic column name used to provide pagination support for SQLServer 2008
  95. * which lacks proper limit/offset support.
  96. */
  97. const ROW_COUNTER = '_cake_page_rownum_';
  98. /**
  99. * Connects to the database using options in the given configuration array.
  100. *
  101. * @return boolean True if the database could be connected, else false
  102. * @throws MissingConnectionException
  103. */
  104. public function connect() {
  105. $config = $this->config;
  106. $this->connected = false;
  107. $flags = array(
  108. PDO::ATTR_PERSISTENT => $config['persistent'],
  109. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
  110. );
  111. if (!empty($config['encoding'])) {
  112. $flags[PDO::SQLSRV_ATTR_ENCODING] = $config['encoding'];
  113. }
  114. try {
  115. $this->_connection = new PDO(
  116. "sqlsrv:server={$config['host']};Database={$config['database']}",
  117. $config['login'],
  118. $config['password'],
  119. $flags
  120. );
  121. $this->connected = true;
  122. if (!empty($config['settings'])) {
  123. foreach ($config['settings'] as $key => $value) {
  124. $this->_execute("SET $key $value");
  125. }
  126. }
  127. } catch (PDOException $e) {
  128. throw new MissingConnectionException(array(
  129. 'class' => get_class($this),
  130. 'message' => $e->getMessage()
  131. ));
  132. }
  133. return $this->connected;
  134. }
  135. /**
  136. * Check that PDO SQL Server is installed/loaded
  137. *
  138. * @return boolean
  139. */
  140. public function enabled() {
  141. return in_array('sqlsrv', PDO::getAvailableDrivers());
  142. }
  143. /**
  144. * Returns an array of sources (tables) in the database.
  145. *
  146. * @param mixed $data
  147. * @return array Array of table names in the database
  148. */
  149. public function listSources($data = null) {
  150. $cache = parent::listSources();
  151. if ($cache !== null) {
  152. return $cache;
  153. }
  154. $result = $this->_execute("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES");
  155. if (!$result) {
  156. $result->closeCursor();
  157. return array();
  158. }
  159. $tables = array();
  160. while ($line = $result->fetch(PDO::FETCH_NUM)) {
  161. $tables[] = $line[0];
  162. }
  163. $result->closeCursor();
  164. parent::listSources($tables);
  165. return $tables;
  166. }
  167. /**
  168. * Returns an array of the fields in given table name.
  169. *
  170. * @param Model|string $model Model object to describe, or a string table name.
  171. * @return array Fields in table. Keys are name and type
  172. * @throws CakeException
  173. */
  174. public function describe($model) {
  175. $table = $this->fullTableName($model, false);
  176. $cache = parent::describe($table);
  177. if ($cache) {
  178. return $cache;
  179. }
  180. $fields = array();
  181. $table = $this->fullTableName($model, false);
  182. $cols = $this->_execute(
  183. "SELECT
  184. COLUMN_NAME as Field,
  185. DATA_TYPE as Type,
  186. COL_LENGTH('" . $table . "', COLUMN_NAME) as Length,
  187. IS_NULLABLE As [Null],
  188. COLUMN_DEFAULT as [Default],
  189. COLUMNPROPERTY(OBJECT_ID('" . $table . "'), COLUMN_NAME, 'IsIdentity') as [Key],
  190. NUMERIC_SCALE as Size
  191. FROM INFORMATION_SCHEMA.COLUMNS
  192. WHERE TABLE_NAME = '" . $table . "'"
  193. );
  194. if (!$cols) {
  195. throw new CakeException(__d('cake_dev', 'Could not describe table for %s', $table));
  196. }
  197. while ($column = $cols->fetch(PDO::FETCH_OBJ)) {
  198. $field = $column->Field;
  199. $fields[$field] = array(
  200. 'type' => $this->column($column),
  201. 'null' => ($column->Null === 'YES' ? true : false),
  202. 'default' => $column->Default,
  203. 'length' => $this->length($column),
  204. 'key' => ($column->Key == '1') ? 'primary' : false
  205. );
  206. if ($fields[$field]['default'] === 'null') {
  207. $fields[$field]['default'] = null;
  208. }
  209. if ($fields[$field]['default'] !== null) {
  210. $fields[$field]['default'] = preg_replace(
  211. "/^[(]{1,2}'?([^')]*)?'?[)]{1,2}$/",
  212. "$1",
  213. $fields[$field]['default']
  214. );
  215. $this->value($fields[$field]['default'], $fields[$field]['type']);
  216. }
  217. if ($fields[$field]['key'] !== false && $fields[$field]['type'] === 'integer') {
  218. $fields[$field]['length'] = 11;
  219. } elseif ($fields[$field]['key'] === false) {
  220. unset($fields[$field]['key']);
  221. }
  222. if (in_array($fields[$field]['type'], array('date', 'time', 'datetime', 'timestamp'))) {
  223. $fields[$field]['length'] = null;
  224. }
  225. if ($fields[$field]['type'] === 'float' && !empty($column->Size)) {
  226. $fields[$field]['length'] = $fields[$field]['length'] . ',' . $column->Size;
  227. }
  228. }
  229. $this->_cacheDescription($table, $fields);
  230. $cols->closeCursor();
  231. return $fields;
  232. }
  233. /**
  234. * Generates the fields list of an SQL query.
  235. *
  236. * @param Model $model
  237. * @param string $alias Alias table name
  238. * @param array $fields
  239. * @param boolean $quote
  240. * @return array
  241. */
  242. public function fields(Model $model, $alias = null, $fields = array(), $quote = true) {
  243. if (empty($alias)) {
  244. $alias = $model->alias;
  245. }
  246. $fields = parent::fields($model, $alias, $fields, false);
  247. $count = count($fields);
  248. if ($count >= 1 && strpos($fields[0], 'COUNT(*)') === false) {
  249. $result = array();
  250. for ($i = 0; $i < $count; $i++) {
  251. $prepend = '';
  252. if (strpos($fields[$i], 'DISTINCT') !== false && strpos($fields[$i], 'COUNT') === false) {
  253. $prepend = 'DISTINCT ';
  254. $fields[$i] = trim(str_replace('DISTINCT', '', $fields[$i]));
  255. }
  256. if (!preg_match('/\s+AS\s+/i', $fields[$i])) {
  257. if (substr($fields[$i], -1) === '*') {
  258. if (strpos($fields[$i], '.') !== false && $fields[$i] != $alias . '.*') {
  259. $build = explode('.', $fields[$i]);
  260. $AssociatedModel = $model->{$build[0]};
  261. } else {
  262. $AssociatedModel = $model;
  263. }
  264. $_fields = $this->fields($AssociatedModel, $AssociatedModel->alias, array_keys($AssociatedModel->schema()));
  265. $result = array_merge($result, $_fields);
  266. continue;
  267. }
  268. if (strpos($fields[$i], '.') === false) {
  269. $this->_fieldMappings[$alias . '__' . $fields[$i]] = $alias . '.' . $fields[$i];
  270. $fieldName = $this->name($alias . '.' . $fields[$i]);
  271. $fieldAlias = $this->name($alias . '__' . $fields[$i]);
  272. } else {
  273. $build = explode('.', $fields[$i]);
  274. $build[0] = trim($build[0], '[]');
  275. $build[1] = trim($build[1], '[]');
  276. $name = $build[0] . '.' . $build[1];
  277. $alias = $build[0] . '__' . $build[1];
  278. $this->_fieldMappings[$alias] = $name;
  279. $fieldName = $this->name($name);
  280. $fieldAlias = $this->name($alias);
  281. }
  282. if ($model->getColumnType($fields[$i]) === 'datetime') {
  283. $fieldName = "CONVERT(VARCHAR(20), {$fieldName}, 20)";
  284. }
  285. $fields[$i] = "{$fieldName} AS {$fieldAlias}";
  286. }
  287. $result[] = $prepend . $fields[$i];
  288. }
  289. return $result;
  290. }
  291. return $fields;
  292. }
  293. /**
  294. * Generates and executes an SQL INSERT statement for given model, fields, and values.
  295. * Removes Identity (primary key) column from update data before returning to parent, if
  296. * value is empty.
  297. *
  298. * @param Model $model
  299. * @param array $fields
  300. * @param array $values
  301. * @return array
  302. */
  303. public function create(Model $model, $fields = null, $values = null) {
  304. if (!empty($values)) {
  305. $fields = array_combine($fields, $values);
  306. }
  307. $primaryKey = $this->_getPrimaryKey($model);
  308. if (array_key_exists($primaryKey, $fields)) {
  309. if (empty($fields[$primaryKey])) {
  310. unset($fields[$primaryKey]);
  311. } else {
  312. $this->_execute('SET IDENTITY_INSERT ' . $this->fullTableName($model) . ' ON');
  313. }
  314. }
  315. $result = parent::create($model, array_keys($fields), array_values($fields));
  316. if (array_key_exists($primaryKey, $fields) && !empty($fields[$primaryKey])) {
  317. $this->_execute('SET IDENTITY_INSERT ' . $this->fullTableName($model) . ' OFF');
  318. }
  319. return $result;
  320. }
  321. /**
  322. * Generates and executes an SQL UPDATE statement for given model, fields, and values.
  323. * Removes Identity (primary key) column from update data before returning to parent.
  324. *
  325. * @param Model $model
  326. * @param array $fields
  327. * @param array $values
  328. * @param mixed $conditions
  329. * @return array
  330. */
  331. public function update(Model $model, $fields = array(), $values = null, $conditions = null) {
  332. if (!empty($values)) {
  333. $fields = array_combine($fields, $values);
  334. }
  335. if (isset($fields[$model->primaryKey])) {
  336. unset($fields[$model->primaryKey]);
  337. }
  338. if (empty($fields)) {
  339. return true;
  340. }
  341. return parent::update($model, array_keys($fields), array_values($fields), $conditions);
  342. }
  343. /**
  344. * Returns a limit statement in the correct format for the particular database.
  345. *
  346. * @param integer $limit Limit of results returned
  347. * @param integer $offset Offset from which to start results
  348. * @return string SQL limit/offset statement
  349. */
  350. public function limit($limit, $offset = null) {
  351. if ($limit) {
  352. $rt = '';
  353. if (!strpos(strtolower($limit), 'top') || strpos(strtolower($limit), 'top') === 0) {
  354. $rt = ' TOP';
  355. }
  356. $rt .= sprintf(' %u', $limit);
  357. if (is_int($offset) && $offset > 0) {
  358. $rt = sprintf(' OFFSET %u ROWS FETCH FIRST %u ROWS ONLY', $offset, $limit);
  359. }
  360. return $rt;
  361. }
  362. return null;
  363. }
  364. /**
  365. * Converts database-layer column types to basic types
  366. *
  367. * @param mixed $real Either the string value of the fields type.
  368. * or the Result object from Sqlserver::describe()
  369. * @return string Abstract column type (i.e. "string")
  370. */
  371. public function column($real) {
  372. $limit = null;
  373. $col = $real;
  374. if (is_object($real) && isset($real->Field)) {
  375. $limit = $real->Length;
  376. $col = $real->Type;
  377. }
  378. if ($col === 'datetime2') {
  379. return 'datetime';
  380. }
  381. if (in_array($col, array('date', 'time', 'datetime', 'timestamp'))) {
  382. return $col;
  383. }
  384. if ($col === 'bit') {
  385. return 'boolean';
  386. }
  387. if (strpos($col, 'bigint') !== false) {
  388. return 'biginteger';
  389. }
  390. if (strpos($col, 'int') !== false) {
  391. return 'integer';
  392. }
  393. if (strpos($col, 'char') !== false && $limit == -1) {
  394. return 'text';
  395. }
  396. if (strpos($col, 'char') !== false) {
  397. return 'string';
  398. }
  399. if (strpos($col, 'text') !== false) {
  400. return 'text';
  401. }
  402. if (strpos($col, 'binary') !== false || $col === 'image') {
  403. return 'binary';
  404. }
  405. if (in_array($col, array('float', 'real', 'decimal', 'numeric'))) {
  406. return 'float';
  407. }
  408. return 'text';
  409. }
  410. /**
  411. * Handle SQLServer specific length properties.
  412. * SQLServer handles text types as nvarchar/varchar with a length of -1.
  413. *
  414. * @param mixed $length Either the length as a string, or a Column descriptor object.
  415. * @return mixed null|integer with length of column.
  416. */
  417. public function length($length) {
  418. if (is_object($length) && isset($length->Length)) {
  419. if ($length->Length == -1 && strpos($length->Type, 'char') !== false) {
  420. return null;
  421. }
  422. if (in_array($length->Type, array('nchar', 'nvarchar'))) {
  423. return floor($length->Length / 2);
  424. }
  425. return $length->Length;
  426. }
  427. return parent::length($length);
  428. }
  429. /**
  430. * Builds a map of the columns contained in a result
  431. *
  432. * @param PDOStatement $results
  433. * @return void
  434. */
  435. public function resultSet($results) {
  436. $this->map = array();
  437. $numFields = $results->columnCount();
  438. $index = 0;
  439. while ($numFields-- > 0) {
  440. $column = $results->getColumnMeta($index);
  441. $name = $column['name'];
  442. if (strpos($name, '__')) {
  443. if (isset($this->_fieldMappings[$name]) && strpos($this->_fieldMappings[$name], '.')) {
  444. $map = explode('.', $this->_fieldMappings[$name]);
  445. } elseif (isset($this->_fieldMappings[$name])) {
  446. $map = array(0, $this->_fieldMappings[$name]);
  447. } else {
  448. $map = array(0, $name);
  449. }
  450. } else {
  451. $map = array(0, $name);
  452. }
  453. $map[] = ($column['sqlsrv:decl_type'] === 'bit') ? 'boolean' : $column['native_type'];
  454. $this->map[$index++] = $map;
  455. }
  456. }
  457. /**
  458. * Builds final SQL statement
  459. *
  460. * @param string $type Query type
  461. * @param array $data Query data
  462. * @return string
  463. */
  464. public function renderStatement($type, $data) {
  465. switch (strtolower($type)) {
  466. case 'select':
  467. extract($data);
  468. $fields = trim($fields);
  469. if (strpos($limit, 'TOP') !== false && strpos($fields, 'DISTINCT ') === 0) {
  470. $limit = 'DISTINCT ' . trim($limit);
  471. $fields = substr($fields, 9);
  472. }
  473. // hack order as SQLServer requires an order if there is a limit.
  474. if ($limit && !$order) {
  475. $order = 'ORDER BY (SELECT NULL)';
  476. }
  477. // For older versions use the subquery version of pagination.
  478. if (version_compare($this->getVersion(), '11', '<') && preg_match('/FETCH\sFIRST\s+([0-9]+)/i', $limit, $offset)) {
  479. preg_match('/OFFSET\s*(\d+)\s*.*?(\d+)\s*ROWS/', $limit, $limitOffset);
  480. $limit = 'TOP ' . intval($limitOffset[2]);
  481. $page = intval($limitOffset[1] / $limitOffset[2]);
  482. $offset = intval($limitOffset[2] * $page);
  483. $rowCounter = self::ROW_COUNTER;
  484. $sql = "SELECT {$limit} * FROM (
  485. SELECT {$fields}, ROW_NUMBER() OVER ({$order}) AS {$rowCounter}
  486. FROM {$table} {$alias} {$joins} {$conditions} {$group}
  487. ) AS _cake_paging_
  488. WHERE _cake_paging_.{$rowCounter} > {$offset}
  489. ORDER BY _cake_paging_.{$rowCounter}
  490. ";
  491. return trim($sql);
  492. }
  493. if (strpos($limit, 'FETCH') !== false) {
  494. return trim("SELECT {$fields} FROM {$table} {$alias} {$joins} {$conditions} {$group} {$order} {$limit}");
  495. }
  496. return trim("SELECT {$limit} {$fields} FROM {$table} {$alias} {$joins} {$conditions} {$group} {$order}");
  497. case "schema":
  498. extract($data);
  499. foreach ($indexes as $i => $index) {
  500. if (preg_match('/PRIMARY KEY/', $index)) {
  501. unset($indexes[$i]);
  502. break;
  503. }
  504. }
  505. foreach (array('columns', 'indexes') as $var) {
  506. if (is_array(${$var})) {
  507. ${$var} = "\t" . implode(",\n\t", array_filter(${$var}));
  508. }
  509. }
  510. return trim("CREATE TABLE {$table} (\n{$columns});\n{$indexes}");
  511. default:
  512. return parent::renderStatement($type, $data);
  513. }
  514. }
  515. /**
  516. * Returns a quoted and escaped string of $data for use in an SQL statement.
  517. *
  518. * @param string $data String to be prepared for use in an SQL statement
  519. * @param string $column The column into which this data will be inserted
  520. * @return string Quoted and escaped data
  521. */
  522. public function value($data, $column = null) {
  523. if ($data === null || is_array($data) || is_object($data)) {
  524. return parent::value($data, $column);
  525. }
  526. if (in_array($data, array('{$__cakeID__$}', '{$__cakeForeignKey__$}'), true)) {
  527. return $data;
  528. }
  529. if (empty($column)) {
  530. $column = $this->introspectType($data);
  531. }
  532. switch ($column) {
  533. case 'string':
  534. case 'text':
  535. return 'N' . $this->_connection->quote($data, PDO::PARAM_STR);
  536. default:
  537. return parent::value($data, $column);
  538. }
  539. }
  540. /**
  541. * Returns an array of all result rows for a given SQL query.
  542. * Returns false if no rows matched.
  543. *
  544. * @param Model $model
  545. * @param array $queryData
  546. * @param integer $recursive
  547. * @return array|false Array of resultset rows, or false if no rows matched
  548. */
  549. public function read(Model $model, $queryData = array(), $recursive = null) {
  550. $results = parent::read($model, $queryData, $recursive);
  551. $this->_fieldMappings = array();
  552. return $results;
  553. }
  554. /**
  555. * Fetches the next row from the current result set.
  556. * Eats the magic ROW_COUNTER variable.
  557. *
  558. * @return mixed
  559. */
  560. public function fetchResult() {
  561. if ($row = $this->_result->fetch(PDO::FETCH_NUM)) {
  562. $resultRow = array();
  563. foreach ($this->map as $col => $meta) {
  564. list($table, $column, $type) = $meta;
  565. if ($table === 0 && $column === self::ROW_COUNTER) {
  566. continue;
  567. }
  568. $resultRow[$table][$column] = $row[$col];
  569. if ($type === 'boolean' && $row[$col] !== null) {
  570. $resultRow[$table][$column] = $this->boolean($resultRow[$table][$column]);
  571. }
  572. }
  573. return $resultRow;
  574. }
  575. $this->_result->closeCursor();
  576. return false;
  577. }
  578. /**
  579. * Inserts multiple values into a table
  580. *
  581. * @param string $table
  582. * @param string $fields
  583. * @param array $values
  584. * @return void
  585. */
  586. public function insertMulti($table, $fields, $values) {
  587. $primaryKey = $this->_getPrimaryKey($table);
  588. $hasPrimaryKey = $primaryKey && (
  589. (is_array($fields) && in_array($primaryKey, $fields)
  590. || (is_string($fields) && strpos($fields, $this->startQuote . $primaryKey . $this->endQuote) !== false))
  591. );
  592. if ($hasPrimaryKey) {
  593. $this->_execute('SET IDENTITY_INSERT ' . $this->fullTableName($table) . ' ON');
  594. }
  595. parent::insertMulti($table, $fields, $values);
  596. if ($hasPrimaryKey) {
  597. $this->_execute('SET IDENTITY_INSERT ' . $this->fullTableName($table) . ' OFF');
  598. }
  599. }
  600. /**
  601. * Generate a database-native column schema string
  602. *
  603. * @param array $column An array structured like the
  604. * following: array('name'=>'value', 'type'=>'value'[, options]),
  605. * where options can be 'default', 'length', or 'key'.
  606. * @return string
  607. */
  608. public function buildColumn($column) {
  609. $result = parent::buildColumn($column);
  610. $result = preg_replace('/(bigint|int|integer)\([0-9]+\)/i', '$1', $result);
  611. $result = preg_replace('/(bit)\([0-9]+\)/i', '$1', $result);
  612. if (strpos($result, 'DEFAULT NULL') !== false) {
  613. if (isset($column['default']) && $column['default'] === '') {
  614. $result = str_replace('DEFAULT NULL', "DEFAULT ''", $result);
  615. } else {
  616. $result = str_replace('DEFAULT NULL', 'NULL', $result);
  617. }
  618. } elseif (array_keys($column) == array('type', 'name')) {
  619. $result .= ' NULL';
  620. } elseif (strpos($result, "DEFAULT N'")) {
  621. $result = str_replace("DEFAULT N'", "DEFAULT '", $result);
  622. }
  623. return $result;
  624. }
  625. /**
  626. * Format indexes for create table
  627. *
  628. * @param array $indexes
  629. * @param string $table
  630. * @return string
  631. */
  632. public function buildIndex($indexes, $table = null) {
  633. $join = array();
  634. foreach ($indexes as $name => $value) {
  635. if ($name === 'PRIMARY') {
  636. $join[] = 'PRIMARY KEY (' . $this->name($value['column']) . ')';
  637. } elseif (isset($value['unique']) && $value['unique']) {
  638. $out = "ALTER TABLE {$table} ADD CONSTRAINT {$name} UNIQUE";
  639. if (is_array($value['column'])) {
  640. $value['column'] = implode(', ', array_map(array(&$this, 'name'), $value['column']));
  641. } else {
  642. $value['column'] = $this->name($value['column']);
  643. }
  644. $out .= "({$value['column']});";
  645. $join[] = $out;
  646. }
  647. }
  648. return $join;
  649. }
  650. /**
  651. * Makes sure it will return the primary key
  652. *
  653. * @param Model|string $model Model instance of table name
  654. * @return string
  655. */
  656. protected function _getPrimaryKey($model) {
  657. $schema = $this->describe($model);
  658. foreach ($schema as $field => $props) {
  659. if (isset($props['key']) && $props['key'] === 'primary') {
  660. return $field;
  661. }
  662. }
  663. return null;
  664. }
  665. /**
  666. * Returns number of affected rows in previous database operation. If no previous operation exists,
  667. * this returns false.
  668. *
  669. * @param mixed $source
  670. * @return integer Number of affected rows
  671. */
  672. public function lastAffected($source = null) {
  673. $affected = parent::lastAffected();
  674. if ($affected === null && $this->_lastAffected !== false) {
  675. return $this->_lastAffected;
  676. }
  677. return $affected;
  678. }
  679. /**
  680. * Executes given SQL statement.
  681. *
  682. * @param string $sql SQL statement
  683. * @param array $params list of params to be bound to query (supported only in select)
  684. * @param array $prepareOptions Options to be used in the prepare statement
  685. * @return mixed PDOStatement if query executes with no problem, true as the result of a successful, false on error
  686. * query returning no rows, such as a CREATE statement, false otherwise
  687. * @throws PDOException
  688. */
  689. protected function _execute($sql, $params = array(), $prepareOptions = array()) {
  690. $this->_lastAffected = false;
  691. if (strncasecmp($sql, 'SELECT', 6) === 0 || preg_match('/^EXEC(?:UTE)?\s/mi', $sql) > 0) {
  692. $prepareOptions += array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL);
  693. return parent::_execute($sql, $params, $prepareOptions);
  694. }
  695. try {
  696. $this->_lastAffected = $this->_connection->exec($sql);
  697. if ($this->_lastAffected === false) {
  698. $this->_results = null;
  699. $error = $this->_connection->errorInfo();
  700. $this->error = $error[2];
  701. return false;
  702. }
  703. return true;
  704. } catch (PDOException $e) {
  705. if (isset($query->queryString)) {
  706. $e->queryString = $query->queryString;
  707. } else {
  708. $e->queryString = $sql;
  709. }
  710. throw $e;
  711. }
  712. }
  713. /**
  714. * Generate a "drop table" statement for the given table
  715. *
  716. * @param type $table Name of the table to drop
  717. * @return string Drop table SQL statement
  718. */
  719. protected function _dropTable($table) {
  720. return "IF OBJECT_ID('" . $this->fullTableName($table, false) . "', 'U') IS NOT NULL DROP TABLE " . $this->fullTableName($table) . ";";
  721. }
  722. /**
  723. * Gets the schema name
  724. *
  725. * @return string The schema name
  726. */
  727. public function getSchemaName() {
  728. return $this->config['schema'];
  729. }
  730. }