Sqlserver.php 22 KB

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