Sqlserver.php 21 KB

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