Sqlite.php 15 KB

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