Sqlserver.php 22 KB

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