Sqlserver.php 22 KB

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