Sqlserver.php 21 KB

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