Sqlite.php 16 KB

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