Sqlserver.php 23 KB

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