Sqlite.php 15 KB

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