Sqlserver.php 22 KB

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