Sqlite.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. <?php
  2. /**
  3. * SQLite layer for DBO
  4. *
  5. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  6. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  7. *
  8. * Licensed under The MIT License
  9. * For full copyright and license information, please see the LICENSE.txt
  10. * Redistributions of files must retain the above copyright notice.
  11. *
  12. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  13. * @link http://cakephp.org CakePHP(tm) Project
  14. * @package Cake.Model.Datasource.Database
  15. * @since CakePHP(tm) v 0.9.0
  16. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  17. */
  18. App::uses('DboSource', 'Model/Datasource');
  19. App::uses('String', 'Utility');
  20. /**
  21. * DBO implementation for the SQLite3 DBMS.
  22. *
  23. * A DboSource adapter for SQLite 3 using PDO
  24. *
  25. * @package Cake.Model.Datasource.Database
  26. */
  27. class Sqlite extends DboSource {
  28. /**
  29. * Datasource Description
  30. *
  31. * @var string
  32. */
  33. public $description = "SQLite DBO Driver";
  34. /**
  35. * Quote Start
  36. *
  37. * @var string
  38. */
  39. public $startQuote = '"';
  40. /**
  41. * Quote End
  42. *
  43. * @var string
  44. */
  45. public $endQuote = '"';
  46. /**
  47. * Base configuration settings for SQLite3 driver
  48. *
  49. * @var array
  50. */
  51. protected $_baseConfig = array(
  52. 'persistent' => false,
  53. 'database' => null
  54. );
  55. /**
  56. * SQLite3 column definition
  57. *
  58. * @var array
  59. */
  60. public $columns = array(
  61. 'primary_key' => array('name' => 'integer primary key autoincrement'),
  62. 'string' => array('name' => 'varchar', 'limit' => '255'),
  63. 'text' => array('name' => 'text'),
  64. 'integer' => array('name' => 'integer', 'limit' => null, 'formatter' => 'intval'),
  65. 'biginteger' => array('name' => 'bigint', 'limit' => 20),
  66. 'float' => array('name' => 'float', 'formatter' => 'floatval'),
  67. 'datetime' => array('name' => 'datetime', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
  68. 'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
  69. 'time' => array('name' => 'time', 'format' => 'H:i:s', 'formatter' => 'date'),
  70. 'date' => array('name' => 'date', 'format' => 'Y-m-d', 'formatter' => 'date'),
  71. 'binary' => array('name' => 'blob'),
  72. 'boolean' => array('name' => 'boolean')
  73. );
  74. /**
  75. * List of engine specific additional field parameters used on table creating
  76. *
  77. * @var array
  78. */
  79. public $fieldParameters = array(
  80. 'collate' => array(
  81. 'value' => 'COLLATE',
  82. 'quote' => false,
  83. 'join' => ' ',
  84. 'column' => 'Collate',
  85. 'position' => 'afterDefault',
  86. 'options' => array(
  87. 'BINARY', 'NOCASE', 'RTRIM'
  88. )
  89. ),
  90. );
  91. /**
  92. * Connects to the database using config['database'] as a filename.
  93. *
  94. * @return boolean
  95. * @throws MissingConnectionException
  96. */
  97. public function connect() {
  98. $config = $this->config;
  99. $flags = array(
  100. PDO::ATTR_PERSISTENT => $config['persistent'],
  101. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
  102. );
  103. try {
  104. $this->_connection = new PDO('sqlite:' . $config['database'], null, null, $flags);
  105. $this->connected = true;
  106. } catch(PDOException $e) {
  107. throw new MissingConnectionException(array(
  108. 'class' => get_class($this),
  109. 'message' => $e->getMessage()
  110. ));
  111. }
  112. return $this->connected;
  113. }
  114. /**
  115. * Check whether the SQLite extension is installed/loaded
  116. *
  117. * @return boolean
  118. */
  119. public function enabled() {
  120. return in_array('sqlite', PDO::getAvailableDrivers());
  121. }
  122. /**
  123. * Returns an array of tables in the database. If there are no tables, an error is raised and the application exits.
  124. *
  125. * @param mixed $data
  126. * @return array Array of table names in the database
  127. */
  128. public function listSources($data = null) {
  129. $cache = parent::listSources();
  130. if ($cache) {
  131. return $cache;
  132. }
  133. $result = $this->fetchAll("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;", false);
  134. if (!$result || empty($result)) {
  135. return array();
  136. }
  137. $tables = array();
  138. foreach ($result as $table) {
  139. $tables[] = $table[0]['name'];
  140. }
  141. parent::listSources($tables);
  142. return $tables;
  143. }
  144. /**
  145. * Returns an array of the fields in given table name.
  146. *
  147. * @param Model|string $model Either the model or table name you want described.
  148. * @return array Fields in table. Keys are name and type
  149. */
  150. public function describe($model) {
  151. $table = $this->fullTableName($model, false, false);
  152. $cache = parent::describe($table);
  153. if ($cache) {
  154. return $cache;
  155. }
  156. $fields = array();
  157. $result = $this->_execute(
  158. 'PRAGMA table_info(' . $this->value($table, 'string') . ')'
  159. );
  160. foreach ($result as $column) {
  161. $column = (array)$column;
  162. $default = ($column['dflt_value'] === 'NULL') ? null : trim($column['dflt_value'], "'");
  163. $fields[$column['name']] = array(
  164. 'type' => $this->column($column['type']),
  165. 'null' => !$column['notnull'],
  166. 'default' => $default,
  167. 'length' => $this->length($column['type'])
  168. );
  169. if ($column['pk'] == 1) {
  170. $fields[$column['name']]['key'] = $this->index['PRI'];
  171. $fields[$column['name']]['null'] = false;
  172. if (empty($fields[$column['name']]['length'])) {
  173. $fields[$column['name']]['length'] = 11;
  174. }
  175. }
  176. }
  177. $result->closeCursor();
  178. $this->_cacheDescription($table, $fields);
  179. return $fields;
  180. }
  181. /**
  182. * Generates and executes an SQL UPDATE statement for given model, fields, and values.
  183. *
  184. * @param Model $model
  185. * @param array $fields
  186. * @param array $values
  187. * @param mixed $conditions
  188. * @return array
  189. */
  190. public function update(Model $model, $fields = array(), $values = null, $conditions = null) {
  191. if (empty($values) && !empty($fields)) {
  192. foreach ($fields as $field => $value) {
  193. if (strpos($field, $model->alias . '.') !== false) {
  194. unset($fields[$field]);
  195. $field = str_replace($model->alias . '.', "", $field);
  196. $field = str_replace($model->alias . '.', "", $field);
  197. $fields[$field] = $value;
  198. }
  199. }
  200. }
  201. return parent::update($model, $fields, $values, $conditions);
  202. }
  203. /**
  204. * Deletes all the records in a table and resets the count of the auto-incrementing
  205. * primary key, where applicable.
  206. *
  207. * @param string|Model $table A string or model class representing the table to be truncated
  208. * @return boolean SQL TRUNCATE TABLE statement, false if not applicable.
  209. */
  210. public function truncate($table) {
  211. if (in_array('sqlite_sequence', $this->listSources())) {
  212. $this->_execute('DELETE FROM sqlite_sequence where name=' . $this->startQuote . $this->fullTableName($table, false, false) . $this->endQuote);
  213. }
  214. return $this->execute('DELETE FROM ' . $this->fullTableName($table));
  215. }
  216. /**
  217. * Converts database-layer column types to basic types
  218. *
  219. * @param string $real Real database-layer column type (i.e. "varchar(255)")
  220. * @return string Abstract column type (i.e. "string")
  221. */
  222. public function column($real) {
  223. if (is_array($real)) {
  224. $col = $real['name'];
  225. if (isset($real['limit'])) {
  226. $col .= '(' . $real['limit'] . ')';
  227. }
  228. return $col;
  229. }
  230. $col = strtolower(str_replace(')', '', $real));
  231. $limit = null;
  232. if (strpos($col, '(') !== false) {
  233. list($col, $limit) = explode('(', $col);
  234. }
  235. $standard = array(
  236. 'text',
  237. 'integer',
  238. 'float',
  239. 'boolean',
  240. 'timestamp',
  241. 'date',
  242. 'datetime',
  243. 'time'
  244. );
  245. if (in_array($col, $standard)) {
  246. return $col;
  247. }
  248. if ($col === 'bigint') {
  249. return 'biginteger';
  250. }
  251. if (strpos($col, 'char') !== false) {
  252. return 'string';
  253. }
  254. if (in_array($col, array('blob', 'clob'))) {
  255. return 'binary';
  256. }
  257. if (strpos($col, 'numeric') !== false || strpos($col, 'decimal') !== false) {
  258. return 'float';
  259. }
  260. return 'text';
  261. }
  262. /**
  263. * Generate ResultSet
  264. *
  265. * @param mixed $results
  266. * @return void
  267. */
  268. public function resultSet($results) {
  269. $this->results = $results;
  270. $this->map = array();
  271. $numFields = $results->columnCount();
  272. $index = 0;
  273. $j = 0;
  274. //PDO::getColumnMeta is experimental and does not work with sqlite3,
  275. // so try to figure it out based on the querystring
  276. $querystring = $results->queryString;
  277. if (stripos($querystring, 'SELECT') === 0) {
  278. $last = strripos($querystring, 'FROM');
  279. if ($last !== false) {
  280. $selectpart = substr($querystring, 7, $last - 8);
  281. $selects = String::tokenize($selectpart, ',', '(', ')');
  282. }
  283. } elseif (strpos($querystring, 'PRAGMA table_info') === 0) {
  284. $selects = array('cid', 'name', 'type', 'notnull', 'dflt_value', 'pk');
  285. } elseif (strpos($querystring, 'PRAGMA index_list') === 0) {
  286. $selects = array('seq', 'name', 'unique');
  287. } elseif (strpos($querystring, 'PRAGMA index_info') === 0) {
  288. $selects = array('seqno', 'cid', 'name');
  289. }
  290. while ($j < $numFields) {
  291. if (!isset($selects[$j])) {
  292. $j++;
  293. continue;
  294. }
  295. if (preg_match('/\bAS\s+(.*)/i', $selects[$j], $matches)) {
  296. $columnName = trim($matches[1], '"');
  297. } else {
  298. $columnName = trim(str_replace('"', '', $selects[$j]));
  299. }
  300. if (strpos($selects[$j], 'DISTINCT') === 0) {
  301. $columnName = str_ireplace('DISTINCT', '', $columnName);
  302. }
  303. $metaType = false;
  304. try {
  305. $metaData = (array)$results->getColumnMeta($j);
  306. if (!empty($metaData['sqlite:decl_type'])) {
  307. $metaType = trim($metaData['sqlite:decl_type']);
  308. }
  309. } catch (Exception $e) {
  310. }
  311. if (strpos($columnName, '.')) {
  312. $parts = explode('.', $columnName);
  313. $this->map[$index++] = array(trim($parts[0]), trim($parts[1]), $metaType);
  314. } else {
  315. $this->map[$index++] = array(0, $columnName, $metaType);
  316. }
  317. $j++;
  318. }
  319. }
  320. /**
  321. * Fetches the next row from the current result set
  322. *
  323. * @return mixed array with results fetched and mapped to column names or false if there is no results left to fetch
  324. */
  325. public function fetchResult() {
  326. if ($row = $this->_result->fetch(PDO::FETCH_NUM)) {
  327. $resultRow = array();
  328. foreach ($this->map as $col => $meta) {
  329. list($table, $column, $type) = $meta;
  330. $resultRow[$table][$column] = $row[$col];
  331. if ($type === 'boolean' && $row[$col] !== null) {
  332. $resultRow[$table][$column] = $this->boolean($resultRow[$table][$column]);
  333. }
  334. }
  335. return $resultRow;
  336. }
  337. $this->_result->closeCursor();
  338. return false;
  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 = sprintf(' LIMIT %u', $limit);
  350. if ($offset) {
  351. $rt .= sprintf(' OFFSET %u', $offset);
  352. }
  353. return $rt;
  354. }
  355. return null;
  356. }
  357. /**
  358. * Generate a database-native column schema string
  359. *
  360. * @param array $column An array structured like the following: array('name'=>'value', 'type'=>'value'[, options]),
  361. * where options can be 'default', 'length', or 'key'.
  362. * @return string
  363. */
  364. public function buildColumn($column) {
  365. $name = $type = null;
  366. $column = array_merge(array('null' => true), $column);
  367. extract($column);
  368. if (empty($name) || empty($type)) {
  369. trigger_error(__d('cake_dev', 'Column name or type not defined in schema'), E_USER_WARNING);
  370. return null;
  371. }
  372. if (!isset($this->columns[$type])) {
  373. trigger_error(__d('cake_dev', 'Column type %s does not exist', $type), E_USER_WARNING);
  374. return null;
  375. }
  376. $isPrimary = (isset($column['key']) && $column['key'] === 'primary');
  377. if ($isPrimary && $type === 'integer') {
  378. return $this->name($name) . ' ' . $this->columns['primary_key']['name'];
  379. }
  380. $out = parent::buildColumn($column);
  381. if ($isPrimary && $type === 'biginteger') {
  382. $replacement = 'PRIMARY KEY';
  383. if ($column['null'] === false) {
  384. $replacement = 'NOT NULL ' . $replacement;
  385. }
  386. return str_replace($this->columns['primary_key']['name'], $replacement, $out);
  387. }
  388. return $out;
  389. }
  390. /**
  391. * Sets the database encoding
  392. *
  393. * @param string $enc Database encoding
  394. * @return boolean
  395. */
  396. public function setEncoding($enc) {
  397. if (!in_array($enc, array("UTF-8", "UTF-16", "UTF-16le", "UTF-16be"))) {
  398. return false;
  399. }
  400. return $this->_execute("PRAGMA encoding = \"{$enc}\"") !== false;
  401. }
  402. /**
  403. * Gets the database encoding
  404. *
  405. * @return string The database encoding
  406. */
  407. public function getEncoding() {
  408. return $this->fetchRow('PRAGMA encoding');
  409. }
  410. /**
  411. * Removes redundant primary key indexes, as they are handled in the column def of the key.
  412. *
  413. * @param array $indexes
  414. * @param string $table
  415. * @return string
  416. */
  417. public function buildIndex($indexes, $table = null) {
  418. $join = array();
  419. $table = str_replace('"', '', $table);
  420. list($dbname, $table) = explode('.', $table);
  421. $dbname = $this->name($dbname);
  422. foreach ($indexes as $name => $value) {
  423. if ($name === 'PRIMARY') {
  424. continue;
  425. }
  426. $out = 'CREATE ';
  427. if (!empty($value['unique'])) {
  428. $out .= 'UNIQUE ';
  429. }
  430. if (is_array($value['column'])) {
  431. $value['column'] = implode(', ', array_map(array(&$this, 'name'), $value['column']));
  432. } else {
  433. $value['column'] = $this->name($value['column']);
  434. }
  435. $t = trim($table, '"');
  436. $indexname = $this->name($t . '_' . $name);
  437. $table = $this->name($table);
  438. $out .= "INDEX {$dbname}.{$indexname} ON {$table}({$value['column']});";
  439. $join[] = $out;
  440. }
  441. return $join;
  442. }
  443. /**
  444. * Overrides DboSource::index to handle SQLite index introspection
  445. * Returns an array of the indexes in given table name.
  446. *
  447. * @param string $model Name of model to inspect
  448. * @return array Fields in table. Keys are column and unique
  449. */
  450. public function index($model) {
  451. $index = array();
  452. $table = $this->fullTableName($model, false, false);
  453. if ($table) {
  454. $indexes = $this->query('PRAGMA index_list(' . $table . ')');
  455. if (is_bool($indexes)) {
  456. return array();
  457. }
  458. foreach ($indexes as $info) {
  459. $key = array_pop($info);
  460. $keyInfo = $this->query('PRAGMA index_info("' . $key['name'] . '")');
  461. foreach ($keyInfo as $keyCol) {
  462. if (!isset($index[$key['name']])) {
  463. $col = array();
  464. if (preg_match('/autoindex/', $key['name'])) {
  465. $key['name'] = 'PRIMARY';
  466. }
  467. $index[$key['name']]['column'] = $keyCol[0]['name'];
  468. $index[$key['name']]['unique'] = intval($key['unique'] == 1);
  469. } else {
  470. if (!is_array($index[$key['name']]['column'])) {
  471. $col[] = $index[$key['name']]['column'];
  472. }
  473. $col[] = $keyCol[0]['name'];
  474. $index[$key['name']]['column'] = $col;
  475. }
  476. }
  477. }
  478. }
  479. return $index;
  480. }
  481. /**
  482. * Overrides DboSource::renderStatement to handle schema generation with SQLite-style indexes
  483. *
  484. * @param string $type
  485. * @param array $data
  486. * @return string
  487. */
  488. public function renderStatement($type, $data) {
  489. switch (strtolower($type)) {
  490. case 'schema':
  491. extract($data);
  492. if (is_array($columns)) {
  493. $columns = "\t" . implode(",\n\t", array_filter($columns));
  494. }
  495. if (is_array($indexes)) {
  496. $indexes = "\t" . implode("\n\t", array_filter($indexes));
  497. }
  498. return "CREATE TABLE {$table} (\n{$columns});\n{$indexes}";
  499. default:
  500. return parent::renderStatement($type, $data);
  501. }
  502. }
  503. /**
  504. * PDO deals in objects, not resources, so overload accordingly.
  505. *
  506. * @return boolean
  507. */
  508. public function hasResult() {
  509. return is_object($this->_result);
  510. }
  511. /**
  512. * Generate a "drop table" statement for the given table
  513. *
  514. * @param type $table Name of the table to drop
  515. * @return string Drop table SQL statement
  516. */
  517. protected function _dropTable($table) {
  518. return 'DROP TABLE IF EXISTS ' . $this->fullTableName($table) . ";";
  519. }
  520. /**
  521. * Gets the schema name
  522. *
  523. * @return string The schema name
  524. */
  525. public function getSchemaName() {
  526. return "main"; // Sqlite Datasource does not support multidb
  527. }
  528. /**
  529. * Check if the server support nested transactions
  530. *
  531. * @return boolean
  532. */
  533. public function nestedTransactionSupported() {
  534. return $this->useNestedTransactions && version_compare($this->getVersion(), '3.6.8', '>=');
  535. }
  536. }