Sqlserver.php 21 KB

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