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