Sqlserver.php 23 KB

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