Sqlserver.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775
  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.libs.model.datasources.dbo
  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. * MS SQL layer for DBO
  22. *
  23. * Long description for class
  24. *
  25. * @package cake.libs.model.datasources.dbo
  26. */
  27. class Sqlserver extends DboSource {
  28. /**
  29. * Driver description
  30. *
  31. * @var string
  32. */
  33. public $description = "SQL Server DBO Driver";
  34. /**
  35. * Starting quote character for quoted identifiers
  36. *
  37. * @var string
  38. */
  39. public $startQuote = "[";
  40. /**
  41. * Ending quote character for quoted identifiers
  42. *
  43. * @var string
  44. */
  45. public $endQuote = "]";
  46. /**
  47. * Creates a map between field aliases and numeric indexes. Workaround for the
  48. * SQL Server driver's 30-character column name limitation.
  49. *
  50. * @var array
  51. */
  52. protected $_fieldMappings = array();
  53. /**
  54. * Storing the last affected value
  55. *
  56. * @var mixed
  57. */
  58. protected $_lastAffected = false;
  59. /**
  60. * Base configuration settings for MS SQL driver
  61. *
  62. * @var array
  63. */
  64. protected $_baseConfig = array(
  65. 'persistent' => true,
  66. 'host' => '(local)\sqlexpress',
  67. 'login' => '',
  68. 'password' => '',
  69. 'database' => 'cake'
  70. );
  71. /**
  72. * MS SQL column definition
  73. *
  74. * @var array
  75. */
  76. public $columns = array(
  77. 'primary_key' => array('name' => 'IDENTITY (1, 1) NOT NULL'),
  78. 'string' => array('name' => 'varchar', 'limit' => '255'),
  79. 'text' => array('name' => 'text'),
  80. 'integer' => array('name' => 'int', 'formatter' => 'intval'),
  81. 'float' => array('name' => 'numeric', 'formatter' => 'floatval'),
  82. 'datetime' => array('name' => 'datetime', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
  83. 'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
  84. 'time' => array('name' => 'datetime', 'format' => 'H:i:s', 'formatter' => 'date'),
  85. 'date' => array('name' => 'datetime', 'format' => 'Y-m-d', 'formatter' => 'date'),
  86. 'binary' => array('name' => 'varbinary'),
  87. 'boolean' => array('name' => 'bit')
  88. );
  89. /**
  90. * Index of basic SQL commands
  91. *
  92. * @var array
  93. */
  94. protected $_commands = array(
  95. 'begin' => 'BEGIN TRANSACTION',
  96. 'commit' => 'COMMIT',
  97. 'rollback' => 'ROLLBACK'
  98. );
  99. /**
  100. * Define if the last query had error
  101. *
  102. * @var string
  103. */
  104. private $__lastQueryHadError = false;
  105. /**
  106. * Connects to the database using options in the given configuration array.
  107. *
  108. * @return boolean True if the database could be connected, else false
  109. */
  110. public function connect() {
  111. $config = $this->config;
  112. $this->connected = false;
  113. try {
  114. $flags = array(PDO::ATTR_PERSISTENT => $config['persistent']);
  115. if (!empty($config['encoding'])) {
  116. $flags[PDO::SQLSRV_ATTR_ENCODING] = $config['encoding'];
  117. }
  118. $this->_connection = new PDO(
  119. "sqlsrv:server={$config['host']};Database={$config['database']}",
  120. $config['login'],
  121. $config['password'],
  122. $flags
  123. );
  124. $this->connected = true;
  125. } catch (PDOException $e) {
  126. throw new MissingConnectionException(array('class' => $e->getMessage()));
  127. }
  128. // $this->_execute("SET DATEFORMAT ymd");
  129. return $this->connected;
  130. }
  131. /**
  132. * Check that PDO SQL Server is installed/loaded
  133. *
  134. * @return boolean
  135. */
  136. public function enabled() {
  137. return in_array('sqlsrv', PDO::getAvailableDrivers());
  138. }
  139. /**
  140. * Returns an array of sources (tables) in the database.
  141. *
  142. * @return array Array of tablenames in the database
  143. */
  144. public function listSources() {
  145. $cache = parent::listSources();
  146. if ($cache !== null) {
  147. return $cache;
  148. }
  149. $result = $this->_execute("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'");
  150. if (!$result) {
  151. $result->closeCursor();
  152. return array();
  153. } else {
  154. $tables = array();
  155. while ($line = $result->fetch()) {
  156. $tables[] = $line[0];
  157. }
  158. $result->closeCursor();
  159. parent::listSources($tables);
  160. return $tables;
  161. }
  162. }
  163. /**
  164. * Returns an array of the fields in given table name.
  165. *
  166. * @param Model $model Model object to describe
  167. * @return array Fields in table. Keys are name and type
  168. */
  169. public function describe($model) {
  170. $cache = parent::describe($model);
  171. if ($cache != null) {
  172. return $cache;
  173. }
  174. $fields = false;
  175. $table = $this->fullTableName($model, false);
  176. $cols = $this->_execute("SELECT COLUMN_NAME as Field, DATA_TYPE as Type, COL_LENGTH('" . $table . "', COLUMN_NAME) as Length, IS_NULLABLE As [Null], COLUMN_DEFAULT as [Default], COLUMNPROPERTY(OBJECT_ID('" . $table . "'), COLUMN_NAME, 'IsIdentity') as [Key], NUMERIC_SCALE as Size FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" . $table . "'");
  177. if (!$cols) {
  178. throw new CakeException(__d('cake_dev', 'Could not describe table for %s', $model->name));
  179. }
  180. foreach ($cols as $column) {
  181. $field = $column->Field;
  182. $fields[$field] = array(
  183. 'type' => $this->column($column->Type),
  184. 'null' => ($column->Null === 'YES' ? true : false),
  185. 'default' => preg_replace("/^[(]{1,2}'?([^')]*)?'?[)]{1,2}$/", "$1", $column->Default),
  186. 'length' => intval($column->Length),
  187. 'key' => ($column->Key == '1') ? 'primary' : false
  188. );
  189. if ($fields[$field]['default'] === 'null') {
  190. $fields[$field]['default'] = null;
  191. } else {
  192. $this->value($fields[$field]['default'], $fields[$field]['type']);
  193. }
  194. if ($fields[$field]['key'] !== false && $fields[$field]['type'] == 'integer') {
  195. $fields[$field]['length'] = 11;
  196. } elseif ($fields[$field]['key'] === false) {
  197. unset($fields[$field]['key']);
  198. }
  199. if (in_array($fields[$field]['type'], array('date', 'time', 'datetime', 'timestamp'))) {
  200. $fields[$field]['length'] = null;
  201. }
  202. if ($fields[$field]['type'] == 'float' && !empty($column->Size)) {
  203. $fields[$field]['length'] = $fields[$field]['length'] . ',' . $column->Size;
  204. }
  205. }
  206. $this->__cacheDescription($table, $fields);
  207. $cols->closeCursor();
  208. return $fields;
  209. }
  210. /**
  211. * Returns a quoted and escaped string of $data for use in an SQL statement.
  212. *
  213. * @param string $data String to be prepared for use in an SQL statement
  214. * @param string $column The column into which this data will be inserted
  215. * @param boolean $safe Whether or not numeric data should be handled automagically if no column data is provided
  216. * @return string Quoted and escaped data
  217. */
  218. public function value($data, $column = null, $safe = false) {
  219. $parent = parent::value($data, $column, $safe);
  220. if ($column === 'float' && strpos($data, '.') !== false) {
  221. return rtrim($data, '0');
  222. }
  223. if ($parent === "''" && ($column === null || $column !== 'string')) {
  224. return 'NULL';
  225. }
  226. if ($parent != null) {
  227. return $parent;
  228. }
  229. if ($data === null) {
  230. return 'NULL';
  231. }
  232. if (in_array($column, array('integer', 'float', 'binary')) && $data === '') {
  233. return 'NULL';
  234. }
  235. if ($data === '') {
  236. return "''";
  237. }
  238. switch ($column) {
  239. case 'boolean':
  240. $data = $this->boolean((bool)$data);
  241. break;
  242. default:
  243. if (get_magic_quotes_gpc()) {
  244. $data = stripslashes(str_replace("'", "''", $data));
  245. } else {
  246. $data = str_replace("'", "''", $data);
  247. }
  248. break;
  249. }
  250. if (in_array($column, array('integer', 'float', 'binary')) && is_numeric($data)) {
  251. return $data;
  252. }
  253. return "'" . $data . "'";
  254. }
  255. /**
  256. * Generates the fields list of an SQL query.
  257. *
  258. * @param Model $model
  259. * @param string $alias Alias tablename
  260. * @param mixed $fields
  261. * @return array
  262. */
  263. public function fields($model, $alias = null, $fields = array(), $quote = true) {
  264. if (empty($alias)) {
  265. $alias = $model->alias;
  266. }
  267. $fields = parent::fields($model, $alias, $fields, false);
  268. $count = count($fields);
  269. if ($count >= 1 && strpos($fields[0], 'COUNT(*)') === false) {
  270. $result = array();
  271. for ($i = 0; $i < $count; $i++) {
  272. $prepend = '';
  273. if (strpos($fields[$i], 'DISTINCT') !== false) {
  274. $prepend = 'DISTINCT ';
  275. $fields[$i] = trim(str_replace('DISTINCT', '', $fields[$i]));
  276. }
  277. $fieldAlias = count($this->_fieldMappings);
  278. if (!preg_match('/\s+AS\s+/i', $fields[$i])) {
  279. if (substr($fields[$i], -1) == '*') {
  280. if (strpos($fields[$i], '.') !== false && $fields[$i] != $alias . '.*') {
  281. $build = explode('.', $fields[$i]);
  282. $AssociatedModel = $model->{$build[0]};
  283. } else {
  284. $AssociatedModel = $model;
  285. }
  286. $_fields = $this->fields($AssociatedModel, $AssociatedModel->alias, array_keys($AssociatedModel->schema()));
  287. $result = array_merge($result, $_fields);
  288. continue;
  289. }
  290. if (strpos($fields[$i], '.') === false) {
  291. $this->_fieldMappings[$alias . '__' . $fieldAlias] = $alias . '.' . $fields[$i];
  292. $fieldName = $this->name($alias . '.' . $fields[$i]);
  293. $fieldAlias = $this->name($alias . '__' . $fieldAlias);
  294. } else {
  295. $build = explode('.', $fields[$i]);
  296. $this->_fieldMappings[$build[0] . '__' . $fieldAlias] = $fields[$i];
  297. $fieldName = $this->name($build[0] . '.' . $build[1]);
  298. $fieldAlias = $this->name(preg_replace("/^\[(.+)\]$/", "$1", $build[0]) . '__' . $fieldAlias);
  299. }
  300. if ($model->getColumnType($fields[$i]) == 'datetime') {
  301. $fieldName = "CONVERT(VARCHAR(20), {$fieldName}, 20)";
  302. }
  303. $fields[$i] = "{$fieldName} AS {$fieldAlias}";
  304. }
  305. $result[] = $prepend . $fields[$i];
  306. }
  307. return $result;
  308. } else {
  309. return $fields;
  310. }
  311. }
  312. /**
  313. * Generates and executes an SQL INSERT statement for given model, fields, and values.
  314. * Removes Identity (primary key) column from update data before returning to parent, if
  315. * value is empty.
  316. *
  317. * @param Model $model
  318. * @param array $fields
  319. * @param array $values
  320. * @param mixed $conditions
  321. * @return array
  322. */
  323. public function create($model, $fields = null, $values = null) {
  324. if (!empty($values)) {
  325. $fields = array_combine($fields, $values);
  326. }
  327. $primaryKey = $this->_getPrimaryKey($model);
  328. if (array_key_exists($primaryKey, $fields)) {
  329. if (empty($fields[$primaryKey])) {
  330. unset($fields[$primaryKey]);
  331. } else {
  332. $this->_execute('SET IDENTITY_INSERT ' . $this->fullTableName($model) . ' ON');
  333. }
  334. }
  335. $result = parent::create($model, array_keys($fields), array_values($fields));
  336. if (array_key_exists($primaryKey, $fields) && !empty($fields[$primaryKey])) {
  337. $this->_execute('SET IDENTITY_INSERT ' . $this->fullTableName($model) . ' OFF');
  338. }
  339. return $result;
  340. }
  341. /**
  342. * Generates and executes an SQL UPDATE statement for given model, fields, and values.
  343. * Removes Identity (primary key) column from update data before returning to parent.
  344. *
  345. * @param Model $model
  346. * @param array $fields
  347. * @param array $values
  348. * @param mixed $conditions
  349. * @return array
  350. */
  351. public function update($model, $fields = array(), $values = null, $conditions = null) {
  352. if (!empty($values)) {
  353. $fields = array_combine($fields, $values);
  354. }
  355. if (isset($fields[$model->primaryKey])) {
  356. unset($fields[$model->primaryKey]);
  357. }
  358. if (empty($fields)) {
  359. return true;
  360. }
  361. return parent::update($model, array_keys($fields), array_values($fields), $conditions);
  362. }
  363. /**
  364. * Returns a limit statement in the correct format for the particular database.
  365. *
  366. * @param integer $limit Limit of results returned
  367. * @param integer $offset Offset from which to start results
  368. * @return string SQL limit/offset statement
  369. */
  370. public function limit($limit, $offset = null) {
  371. if ($limit) {
  372. $rt = '';
  373. if (!strpos(strtolower($limit), 'top') || strpos(strtolower($limit), 'top') === 0) {
  374. $rt = ' TOP';
  375. }
  376. $rt .= ' ' . $limit;
  377. if (is_int($offset) && $offset > 0) {
  378. $rt .= ' OFFSET ' . $offset;
  379. }
  380. return $rt;
  381. }
  382. return null;
  383. }
  384. /**
  385. * Converts database-layer column types to basic types
  386. *
  387. * @param string $real Real database-layer column type (i.e. "varchar(255)")
  388. * @return string Abstract column type (i.e. "string")
  389. */
  390. public function column($real) {
  391. if (is_array($real)) {
  392. $col = $real['name'];
  393. if (isset($real['limit'])) {
  394. $col .= '(' . $real['limit'] . ')';
  395. }
  396. return $col;
  397. }
  398. $col = str_replace(')', '', $real);
  399. $limit = null;
  400. if (strpos($col, '(') !== false) {
  401. list($col, $limit) = explode('(', $col);
  402. }
  403. if (in_array($col, array('date', 'time', 'datetime', 'timestamp'))) {
  404. return $col;
  405. }
  406. if ($col == 'bit') {
  407. return 'boolean';
  408. }
  409. if (strpos($col, 'int') !== false) {
  410. return 'integer';
  411. }
  412. if (strpos($col, 'char') !== false) {
  413. return 'string';
  414. }
  415. if (strpos($col, 'text') !== false) {
  416. return 'text';
  417. }
  418. if (strpos($col, 'binary') !== false || $col == 'image') {
  419. return 'binary';
  420. }
  421. if (in_array($col, array('float', 'real', 'decimal', 'numeric'))) {
  422. return 'float';
  423. }
  424. return 'text';
  425. }
  426. /**
  427. * Builds a map of the columns contained in a result
  428. *
  429. * @param PDOStatement $results
  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. if (preg_match('/offset\s+([0-9]+)/i', $limit, $offset)) {
  470. $limit = preg_replace('/\s*offset.*$/i', '', $limit);
  471. preg_match('/top\s+([0-9]+)/i', $limit, $limitVal);
  472. $offset = intval($offset[1]) + intval($limitVal[1]);
  473. $rOrder = $this->__switchSort($order);
  474. list($order2, $rOrder) = array($this->__mapFields($order), $this->__mapFields($rOrder));
  475. return "SELECT * FROM (SELECT {$limit} * FROM (SELECT TOP {$offset} {$fields} FROM {$table} {$alias} {$joins} {$conditions} {$group} {$order}) AS Set1 {$rOrder}) AS Set2 {$order2}";
  476. } else {
  477. return "SELECT {$limit} {$fields} FROM {$table} {$alias} {$joins} {$conditions} {$group} {$order}";
  478. }
  479. break;
  480. case "schema":
  481. extract($data);
  482. foreach ($indexes as $i => $index) {
  483. if (preg_match('/PRIMARY KEY/', $index)) {
  484. unset($indexes[$i]);
  485. break;
  486. }
  487. }
  488. foreach (array('columns', 'indexes') as $var) {
  489. if (is_array(${$var})) {
  490. ${$var} = "\t" . implode(",\n\t", array_filter(${$var}));
  491. }
  492. }
  493. return "CREATE TABLE {$table} (\n{$columns});\n{$indexes}";
  494. break;
  495. default:
  496. return parent::renderStatement($type, $data);
  497. break;
  498. }
  499. }
  500. /**
  501. * Reverses the sort direction of ORDER statements to get paging offsets to work correctly
  502. *
  503. * @param string $order
  504. * @return string
  505. */
  506. private function __switchSort($order) {
  507. $order = preg_replace('/\s+ASC/i', '__tmp_asc__', $order);
  508. $order = preg_replace('/\s+DESC/i', ' ASC', $order);
  509. return preg_replace('/__tmp_asc__/', ' DESC', $order);
  510. }
  511. /**
  512. * Translates field names used for filtering and sorting to shortened names using the field map
  513. *
  514. * @param string $sql A snippet of SQL representing an ORDER or WHERE statement
  515. * @return string The value of $sql with field names replaced
  516. */
  517. private function __mapFields($sql) {
  518. if (empty($sql) || empty($this->_fieldMappings)) {
  519. return $sql;
  520. }
  521. foreach ($this->_fieldMappings as $key => $val) {
  522. $sql = preg_replace('/' . preg_quote($val) . '/', $this->name($key), $sql);
  523. $sql = preg_replace('/' . preg_quote($this->name($val)) . '/', $this->name($key), $sql);
  524. }
  525. return $sql;
  526. }
  527. /**
  528. * Returns an array of all result rows for a given SQL query.
  529. * Returns false if no rows matched.
  530. *
  531. * @param string $sql SQL statement
  532. * @param boolean $cache Enables returning/storing cached query results
  533. * @return array Array of resultset rows, or false if no rows matched
  534. */
  535. public function read($model, $queryData = array(), $recursive = null) {
  536. $results = parent::read($model, $queryData, $recursive);
  537. $this->_fieldMappings = array();
  538. return $results;
  539. }
  540. /**
  541. * Fetches the next row from the current result set
  542. *
  543. * @return mixed
  544. */
  545. public function fetchResult() {
  546. if ($row = $this->_result->fetch()) {
  547. $resultRow = array();
  548. foreach ($this->map as $col => $meta) {
  549. list($table, $column, $type) = $meta;
  550. $resultRow[$table][$column] = $row[$col];
  551. if ($type === 'boolean' && !is_null($row[$col])) {
  552. $resultRow[$table][$column] = $this->boolean($resultRow[$table][$column]);
  553. }
  554. }
  555. return $resultRow;
  556. }
  557. $this->_result->closeCursor();
  558. return false;
  559. }
  560. /**
  561. * Inserts multiple values into a table
  562. *
  563. * @param string $table
  564. * @param string $fields
  565. * @param array $values
  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. $table = $this->fullTableName($table);
  577. $fields = implode(', ', array_map(array(&$this, 'name'), $fields));
  578. $this->begin();
  579. foreach ($values as $value) {
  580. $holder = implode(', ', array_map(array(&$this, 'value'), $value));
  581. $this->_execute("INSERT INTO {$table} ({$fields}) VALUES ({$holder})");
  582. }
  583. $this->commit();
  584. if ($hasPrimaryKey) {
  585. $this->_execute('SET IDENTITY_INSERT ' . $this->fullTableName($table) . ' OFF');
  586. }
  587. }
  588. /**
  589. * Generate a database-native column schema string
  590. *
  591. * @param array $column An array structured like the following: array('name'=>'value', 'type'=>'value'[, options]),
  592. * where options can be 'default', 'length', or 'key'.
  593. * @return string
  594. */
  595. public function buildColumn($column) {
  596. $result = preg_replace('/(int|integer)\([0-9]+\)/i', '$1', parent::buildColumn($column));
  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. } else if (array_keys($column) == array('type', 'name')) {
  604. $result .= ' NULL';
  605. }
  606. return $result;
  607. }
  608. /**
  609. * Format indexes for create table
  610. *
  611. * @param array $indexes
  612. * @param string $table
  613. * @return string
  614. */
  615. public function buildIndex($indexes, $table = null) {
  616. $join = array();
  617. foreach ($indexes as $name => $value) {
  618. if ($name == 'PRIMARY') {
  619. $join[] = 'PRIMARY KEY (' . $this->name($value['column']) . ')';
  620. } else if (isset($value['unique']) && $value['unique']) {
  621. $out = "ALTER TABLE {$table} ADD CONSTRAINT {$name} UNIQUE";
  622. if (is_array($value['column'])) {
  623. $value['column'] = implode(', ', array_map(array(&$this, 'name'), $value['column']));
  624. } else {
  625. $value['column'] = $this->name($value['column']);
  626. }
  627. $out .= "({$value['column']});";
  628. $join[] = $out;
  629. }
  630. }
  631. return $join;
  632. }
  633. /**
  634. * Makes sure it will return the primary key
  635. *
  636. * @param mixed $model Model instance of table name
  637. * @return string
  638. */
  639. protected function _getPrimaryKey($model) {
  640. if (!is_object($model)) {
  641. $model = new Model(false, $model);
  642. }
  643. $schema = $this->describe($model);
  644. foreach ($schema as $field => $props) {
  645. if (isset($props['key']) && $props['key'] == 'primary') {
  646. return $field;
  647. }
  648. }
  649. return null;
  650. }
  651. /**
  652. * Returns number of affected rows in previous database operation. If no previous operation exists,
  653. * this returns false.
  654. *
  655. * @return integer Number of affected rows
  656. */
  657. public function lastAffected() {
  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 succesfull, false on error
  671. * query returning no rows, suchs as a CREATE statement, false otherwise
  672. */
  673. protected function _execute($sql, $params = array(), $prepareOptions = array()) {
  674. $this->_lastAffected = false;
  675. if (strncasecmp($sql, 'SELECT', 6) == 0) {
  676. $prepareOptions += array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL);
  677. return parent::_execute($sql, $params, $prepareOptions);
  678. }
  679. try {
  680. $this->_lastAffected = $this->_connection->exec($sql);
  681. if ($this->_lastAffected === false) {
  682. $this->_results = null;
  683. $error = $this->_connection->errorInfo();
  684. $this->error = $error[2];
  685. return false;
  686. }
  687. return true;
  688. } catch (PDOException $e) {
  689. $this->_results = null;
  690. $this->error = $e->getMessage();
  691. return false;
  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. $t = $this->fullTableName($curTable);
  707. $out .= "IF OBJECT_ID('" . $this->fullTableName($curTable, false). "', 'U') IS NOT NULL DROP TABLE " . $this->fullTableName($curTable) . ";\n";
  708. }
  709. }
  710. return $out;
  711. }
  712. }