Sqlite.php 15 KB

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