Sqlserver.php 22 KB

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