Sqlserver.php 22 KB

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