PageRenderTime 45ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/Cake/Model/Datasource/Database/Sqlserver.php

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