Sqlite.php 15 KB

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