PageRenderTime 38ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/Model/Datasource/Database/Sqlite.php

https://bitbucket.org/udeshika/fake_twitter
PHP | 547 lines | 455 code | 15 blank | 77 comment | 7 complexity | 375881806c9e59ef40fcd0cd2bac0b00 MD5 | raw file
  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. 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 MySQL 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. return array();
  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. $cache = parent::describe($model);
  151. if ($cache != null) {
  152. return $cache;
  153. }
  154. $table = $this->fullTableName($model, false);
  155. $fields = array();
  156. $result = $this->_execute('PRAGMA table_info(' . $table . ')');
  157. foreach ($result as $column) {
  158. $column = (array) $column;
  159. $default = ($column['dflt_value'] === 'NULL') ? null : trim($column['dflt_value'], "'");
  160. $fields[$column['name']] = array(
  161. 'type' => $this->column($column['type']),
  162. 'null' => !$column['notnull'],
  163. 'default' => $default,
  164. 'length' => $this->length($column['type'])
  165. );
  166. if ($column['pk'] == 1) {
  167. $fields[$column['name']]['key'] = $this->index['PRI'];
  168. $fields[$column['name']]['null'] = false;
  169. if (empty($fields[$column['name']]['length'])) {
  170. $fields[$column['name']]['length'] = 11;
  171. }
  172. }
  173. }
  174. $result->closeCursor();
  175. $this->_cacheDescription($table, $fields);
  176. return $fields;
  177. }
  178. /**
  179. * Generates and executes an SQL UPDATE statement for given model, fields, and values.
  180. *
  181. * @param Model $model
  182. * @param array $fields
  183. * @param array $values
  184. * @param mixed $conditions
  185. * @return array
  186. */
  187. public function update(Model $model, $fields = array(), $values = null, $conditions = null) {
  188. if (empty($values) && !empty($fields)) {
  189. foreach ($fields as $field => $value) {
  190. if (strpos($field, $model->alias . '.') !== false) {
  191. unset($fields[$field]);
  192. $field = str_replace($model->alias . '.', "", $field);
  193. $field = str_replace($model->alias . '.', "", $field);
  194. $fields[$field] = $value;
  195. }
  196. }
  197. }
  198. return parent::update($model, $fields, $values, $conditions);
  199. }
  200. /**
  201. * Deletes all the records in a table and resets the count of the auto-incrementing
  202. * primary key, where applicable.
  203. *
  204. * @param mixed $table A string or model class representing the table to be truncated
  205. * @return boolean SQL TRUNCATE TABLE statement, false if not applicable.
  206. */
  207. public function truncate($table) {
  208. $this->_execute('DELETE FROM sqlite_sequence where name=' . $this->fullTableName($table));
  209. return $this->execute('DELETE FROM ' . $this->fullTableName($table));
  210. }
  211. /**
  212. * Converts database-layer column types to basic types
  213. *
  214. * @param string $real Real database-layer column type (i.e. "varchar(255)")
  215. * @return string Abstract column type (i.e. "string")
  216. */
  217. public function column($real) {
  218. if (is_array($real)) {
  219. $col = $real['name'];
  220. if (isset($real['limit'])) {
  221. $col .= '(' . $real['limit'] . ')';
  222. }
  223. return $col;
  224. }
  225. $col = strtolower(str_replace(')', '', $real));
  226. $limit = null;
  227. @list($col, $limit) = explode('(', $col);
  228. if (in_array($col, array('text', 'integer', 'float', 'boolean', 'timestamp', 'date', 'datetime', 'time'))) {
  229. return $col;
  230. }
  231. if (strpos($col, 'char') !== false) {
  232. return 'string';
  233. }
  234. if (in_array($col, array('blob', 'clob'))) {
  235. return 'binary';
  236. }
  237. if (strpos($col, 'numeric') !== false || strpos($col, 'decimal') !== false) {
  238. return 'float';
  239. }
  240. return 'text';
  241. }
  242. /**
  243. * Generate ResultSet
  244. *
  245. * @param mixed $results
  246. * @return void
  247. */
  248. public function resultSet($results) {
  249. $this->results = $results;
  250. $this->map = array();
  251. $num_fields = $results->columnCount();
  252. $index = 0;
  253. $j = 0;
  254. //PDO::getColumnMeta is experimental and does not work with sqlite3,
  255. // so try to figure it out based on the querystring
  256. $querystring = $results->queryString;
  257. if (stripos($querystring, 'SELECT') === 0) {
  258. $last = strripos($querystring, 'FROM');
  259. if ($last !== false) {
  260. $selectpart = substr($querystring, 7, $last - 8);
  261. $selects = String::tokenize($selectpart, ',', '(', ')');
  262. }
  263. } elseif (strpos($querystring, 'PRAGMA table_info') === 0) {
  264. $selects = array('cid', 'name', 'type', 'notnull', 'dflt_value', 'pk');
  265. } elseif (strpos($querystring, 'PRAGMA index_list') === 0) {
  266. $selects = array('seq', 'name', 'unique');
  267. } elseif (strpos($querystring, 'PRAGMA index_info') === 0) {
  268. $selects = array('seqno', 'cid', 'name');
  269. }
  270. while ($j < $num_fields) {
  271. if (!isset($selects[$j])) {
  272. $j++;
  273. continue;
  274. }
  275. if (preg_match('/\bAS\s+(.*)/i', $selects[$j], $matches)) {
  276. $columnName = trim($matches[1], '"');
  277. } else {
  278. $columnName = trim(str_replace('"', '', $selects[$j]));
  279. }
  280. if (strpos($selects[$j], 'DISTINCT') === 0) {
  281. $columnName = str_ireplace('DISTINCT', '', $columnName);
  282. }
  283. $metaType = false;
  284. try {
  285. $metaData = (array)$results->getColumnMeta($j);
  286. if (!empty($metaData['sqlite:decl_type'])) {
  287. $metaType = trim($metaData['sqlite:decl_type']);
  288. }
  289. } catch (Exception $e) {}
  290. if (strpos($columnName, '.')) {
  291. $parts = explode('.', $columnName);
  292. $this->map[$index++] = array(trim($parts[0]), trim($parts[1]), $metaType);
  293. } else {
  294. $this->map[$index++] = array(0, $columnName, $metaType);
  295. }
  296. $j++;
  297. }
  298. }
  299. /**
  300. * Fetches the next row from the current result set
  301. *
  302. * @return mixed array with results fetched and mapped to column names or false if there is no results left to fetch
  303. */
  304. public function fetchResult() {
  305. if ($row = $this->_result->fetch(PDO::FETCH_NUM)) {
  306. $resultRow = array();
  307. foreach ($this->map as $col => $meta) {
  308. list($table, $column, $type) = $meta;
  309. $resultRow[$table][$column] = $row[$col];
  310. if ($type == 'boolean' && !is_null($row[$col])) {
  311. $resultRow[$table][$column] = $this->boolean($resultRow[$table][$column]);
  312. }
  313. }
  314. return $resultRow;
  315. } else {
  316. $this->_result->closeCursor();
  317. return false;
  318. }
  319. }
  320. /**
  321. * Returns a limit statement in the correct format for the particular database.
  322. *
  323. * @param integer $limit Limit of results returned
  324. * @param integer $offset Offset from which to start results
  325. * @return string SQL limit/offset statement
  326. */
  327. public function limit($limit, $offset = null) {
  328. if ($limit) {
  329. $rt = '';
  330. if (!strpos(strtolower($limit), 'limit') || strpos(strtolower($limit), 'limit') === 0) {
  331. $rt = ' LIMIT';
  332. }
  333. $rt .= ' ' . $limit;
  334. if ($offset) {
  335. $rt .= ' OFFSET ' . $offset;
  336. }
  337. return $rt;
  338. }
  339. return null;
  340. }
  341. /**
  342. * Generate a database-native column schema string
  343. *
  344. * @param array $column An array structured like the following: array('name'=>'value', 'type'=>'value'[, options]),
  345. * where options can be 'default', 'length', or 'key'.
  346. * @return string
  347. */
  348. public function buildColumn($column) {
  349. $name = $type = null;
  350. $column = array_merge(array('null' => true), $column);
  351. extract($column);
  352. if (empty($name) || empty($type)) {
  353. trigger_error(__d('cake_dev', 'Column name or type not defined in schema'), E_USER_WARNING);
  354. return null;
  355. }
  356. if (!isset($this->columns[$type])) {
  357. trigger_error(__d('cake_dev', 'Column type %s does not exist', $type), E_USER_WARNING);
  358. return null;
  359. }
  360. $real = $this->columns[$type];
  361. $out = $this->name($name) . ' ' . $real['name'];
  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. foreach ($indexes as $name => $value) {
  397. if ($name == 'PRIMARY') {
  398. continue;
  399. }
  400. $out = 'CREATE ';
  401. if (!empty($value['unique'])) {
  402. $out .= 'UNIQUE ';
  403. }
  404. if (is_array($value['column'])) {
  405. $value['column'] = join(', ', array_map(array(&$this, 'name'), $value['column']));
  406. } else {
  407. $value['column'] = $this->name($value['column']);
  408. }
  409. $t = trim($table, '"');
  410. $out .= "INDEX {$t}_{$name} ON {$table}({$value['column']});";
  411. $join[] = $out;
  412. }
  413. return $join;
  414. }
  415. /**
  416. * Overrides DboSource::index to handle SQLite index introspection
  417. * Returns an array of the indexes in given table name.
  418. *
  419. * @param string $model Name of model to inspect
  420. * @return array Fields in table. Keys are column and unique
  421. */
  422. public function index($model) {
  423. $index = array();
  424. $table = $this->fullTableName($model);
  425. if ($table) {
  426. $indexes = $this->query('PRAGMA index_list(' . $table . ')');
  427. if (is_bool($indexes)) {
  428. return array();
  429. }
  430. foreach ($indexes as $i => $info) {
  431. $key = array_pop($info);
  432. $keyInfo = $this->query('PRAGMA index_info("' . $key['name'] . '")');
  433. foreach ($keyInfo as $keyCol) {
  434. if (!isset($index[$key['name']])) {
  435. $col = array();
  436. if (preg_match('/autoindex/', $key['name'])) {
  437. $key['name'] = 'PRIMARY';
  438. }
  439. $index[$key['name']]['column'] = $keyCol[0]['name'];
  440. $index[$key['name']]['unique'] = intval($key['unique'] == 1);
  441. } else {
  442. if (!is_array($index[$key['name']]['column'])) {
  443. $col[] = $index[$key['name']]['column'];
  444. }
  445. $col[] = $keyCol[0]['name'];
  446. $index[$key['name']]['column'] = $col;
  447. }
  448. }
  449. }
  450. }
  451. return $index;
  452. }
  453. /**
  454. * Overrides DboSource::renderStatement to handle schema generation with SQLite-style indexes
  455. *
  456. * @param string $type
  457. * @param array $data
  458. * @return string
  459. */
  460. public function renderStatement($type, $data) {
  461. switch (strtolower($type)) {
  462. case 'schema':
  463. extract($data);
  464. if (is_array($columns)) {
  465. $columns = "\t" . join(",\n\t", array_filter($columns));
  466. }
  467. if (is_array($indexes)) {
  468. $indexes = "\t" . join("\n\t", array_filter($indexes));
  469. }
  470. return "CREATE TABLE {$table} (\n{$columns});\n{$indexes}";
  471. break;
  472. default:
  473. return parent::renderStatement($type, $data);
  474. break;
  475. }
  476. }
  477. /**
  478. * PDO deals in objects, not resources, so overload accordingly.
  479. *
  480. * @return boolean
  481. */
  482. public function hasResult() {
  483. return is_object($this->_result);
  484. }
  485. /**
  486. * Generate a "drop table" statement for the given Schema object
  487. *
  488. * @param CakeSchema $schema An instance of a subclass of CakeSchema
  489. * @param string $table Optional. If specified only the table name given will be generated.
  490. * Otherwise, all tables defined in the schema are generated.
  491. * @return string
  492. */
  493. public function dropSchema(CakeSchema $schema, $table = null) {
  494. $out = '';
  495. foreach ($schema->tables as $curTable => $columns) {
  496. if (!$table || $table == $curTable) {
  497. $out .= 'DROP TABLE IF EXISTS ' . $this->fullTableName($curTable) . ";\n";
  498. }
  499. }
  500. return $out;
  501. }
  502. }