Sqlserver.php 23 KB

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