Sqlserver.php 23 KB

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