Sqlite.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  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. $this->_execute('DELETE FROM sqlite_sequence where name=' . $this->startQuote . $this->fullTableName($table, false, false) . $this->endQuote);
  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. }