Sqlite.php 15 KB

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