Sqlite3.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. <?php
  2. /**
  3. * Lithium: the most rad php framework
  4. *
  5. * @copyright Copyright 2013, Union of RAD (http://union-of-rad.org)
  6. * @license http://opensource.org/licenses/bsd-license.php The BSD License
  7. *
  8. */
  9. namespace lithium\data\source\database\adapter;
  10. use PDOException;
  11. use lithium\core\ConfigException;
  12. /**
  13. * Sqlite database driver
  14. *
  15. * @todo fix encoding methods to use class query methods instead of sqlite3 natives
  16. */
  17. class Sqlite3 extends \lithium\data\source\Database {
  18. /**
  19. * Pair of opening and closing quote characters used for quoting identifiers in queries.
  20. *
  21. * @link http://www.sqlite.org/lang_keywords.html
  22. * @var array
  23. */
  24. protected $_quotes = array('"', '"');
  25. /**
  26. * Sqlite column type definitions.
  27. *
  28. * @var array
  29. */
  30. protected $_columns = array(
  31. 'primary_key' => array('name' => 'primary key autoincrement'),
  32. 'string' => array('name' => 'varchar', 'length' => 255),
  33. 'text' => array('name' => 'text'),
  34. 'integer' => array('name' => 'integer', 'formatter' => 'intval'),
  35. 'float' => array('name' => 'float', 'formatter' => 'floatval'),
  36. 'datetime' => array('name' => 'datetime', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
  37. 'timestamp' => array(
  38. 'name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'
  39. ),
  40. 'time' => array('name' => 'time', 'format' => 'H:i:s', 'formatter' => 'date'),
  41. 'date' => array('name' => 'date', 'format' => 'Y-m-d', 'formatter' => 'date'),
  42. 'binary' => array('name' => 'blob'),
  43. 'boolean' => array('name' => 'boolean')
  44. );
  45. /**
  46. * Holds commonly regular expressions used in this class.
  47. *
  48. * @see lithium\data\source\database\adapter\Sqlite3::describe()
  49. * @see lithium\data\source\database\adapter\Sqlite3::_column()
  50. * @var array
  51. */
  52. protected $_regex = array(
  53. 'column' => '(?P<type>[^(]+)(?:\((?P<length>[^)]+)\))?'
  54. );
  55. /**
  56. * Constructs the Sqlite adapter
  57. *
  58. * @see lithium\data\source\Database::__construct()
  59. * @see lithium\data\Source::__construct()
  60. * @see lithium\data\Connections::add()
  61. * @param array $config Configuration options for this class. For additional configuration,
  62. * see `lithium\data\source\Database` and `lithium\data\Source`. Available options
  63. * defined by this class:
  64. * - `'database'` _string_: database name. Defaults to none
  65. * - `'flags'` _integer_: Optional flags used to determine how to open the SQLite
  66. * database. By default, open uses SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE.
  67. * - `'key'` _string_: An optional encryption key used when encrypting and decrypting
  68. * an SQLite database.
  69. *
  70. * Typically, these parameters are set in `Connections::add()`, when adding the adapter to the
  71. * list of active connections.
  72. */
  73. public function __construct(array $config = array()) {
  74. $defaults = array('database' => ':memory:', 'encoding' => null);
  75. parent::__construct($config + $defaults);
  76. }
  77. /**
  78. * Check for required PHP extension, or supported database feature.
  79. *
  80. * @param string $feature Test for support for a specific feature, i.e. `'transactions'`.
  81. * @return boolean Returns `true` if the particular feature (or if Sqlite) support is enabled,
  82. * otherwise `false`.
  83. */
  84. public static function enabled($feature = null) {
  85. if (!$feature) {
  86. return extension_loaded('pdo_sqlite');
  87. }
  88. $features = array(
  89. 'arrays' => false,
  90. 'transactions' => false,
  91. 'booleans' => true,
  92. 'relationships' => true
  93. );
  94. return isset($features[$feature]) ? $features[$feature] : null;
  95. }
  96. /**
  97. * Connects to the database using options provided to the class constructor.
  98. *
  99. * @return boolean True if the database could be connected, else false
  100. */
  101. public function connect() {
  102. if (!$this->_config['database']) {
  103. throw new ConfigException('No Database configured');
  104. }
  105. if (empty($this->_config['dsn'])) {
  106. $this->_config['dsn'] = sprintf("sqlite:%s", $this->_config['database']);
  107. }
  108. return parent::connect();
  109. }
  110. /**
  111. * Disconnects the adapter from the database.
  112. *
  113. * @return boolean True on success, else false.
  114. */
  115. public function disconnect() {
  116. if ($this->_isConnected) {
  117. unset($this->connection);
  118. $this->_isConnected = false;
  119. }
  120. return true;
  121. }
  122. /**
  123. * Returns the list of tables in the currently-connected database.
  124. *
  125. * @param string $model The fully-name-spaced class name of the model object making the request.
  126. * @return array Returns an array of objects to which models can connect.
  127. * @filter This method can be filtered.
  128. */
  129. public function sources($model = null) {
  130. $config = $this->_config;
  131. return $this->_filter(__METHOD__, compact('model'), function($self, $params) use ($config) {
  132. $sql = "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;";
  133. $result = $self->invokeMethod('_execute', array($sql));
  134. $sources = array();
  135. while ($data = $result->next()) {
  136. $sources[] = reset($data);
  137. }
  138. return $sources;
  139. });
  140. }
  141. /**
  142. * Gets the column schema for a given Sqlite3 table.
  143. *
  144. * A column type may not always be available, i.e. when during creation of
  145. * the column no type was declared. Those columns are internally treated
  146. * by SQLite3 as having a `NONE` affinity. The final schema will contain no
  147. * information about type and length of such columns (both values will be
  148. * `null`).
  149. *
  150. * @param mixed $entity Specifies the table name for which the schema should be returned, or
  151. * the class name of the model object requesting the schema, in which case the model
  152. * class will be queried for the correct table name.
  153. * @param array $fields Any schema data pre-defined by the model.
  154. * @param array $meta
  155. * @return array Returns an associative array describing the given table's schema, where the
  156. * array keys are the available fields, and the values are arrays describing each
  157. * field, containing the following keys:
  158. * - `'type'`: The field type name
  159. * @filter This method can be filtered.
  160. */
  161. public function describe($entity, $fields = array(), array $meta = array()) {
  162. $params = compact('entity', 'meta', 'fields');
  163. $regex = $this->_regex;
  164. return $this->_filter(__METHOD__, $params, function($self, $params) use ($regex) {
  165. extract($params);
  166. if ($fields) {
  167. return $self->invokeMethod('_instance', array('schema', compact('fields')));
  168. }
  169. $name = $self->invokeMethod('_entityName', array($entity, array('quoted' => true)));
  170. $columns = $self->read("PRAGMA table_info({$name})", array('return' => 'array'));
  171. $fields = array();
  172. foreach ($columns as $column) {
  173. preg_match("/{$regex['column']}/", $column['type'], $matches);
  174. $fields[$column['name']] = array(
  175. 'type' => isset($matches['type']) ? $matches['type'] : null,
  176. 'length' => isset($matches['length']) ? $matches['length'] : null,
  177. 'null' => $column['notnull'] == 1,
  178. 'default' => $column['dflt_value']
  179. );
  180. }
  181. return $self->invokeMethod('_instance', array('schema', compact('fields')));
  182. });
  183. }
  184. /**
  185. * Gets the last auto-generated ID from the query that inserted a new record.
  186. *
  187. * @param object $query The `Query` object associated with the query which generated
  188. * @return mixed Returns the last inserted ID key for an auto-increment column or a column
  189. * bound to a sequence.
  190. */
  191. protected function _insertId($query) {
  192. return $this->connection->lastInsertId();
  193. }
  194. /**
  195. * Gets or sets the encoding for the connection.
  196. *
  197. * @param string $encoding If setting the encoding, this is the name of the encoding to set,
  198. * i.e. `'utf8'` or `'UTF-8'` (both formats are valid).
  199. * @return mixed If setting the encoding; returns `true` on success, or `false` on
  200. * failure. When getting, returns the encoding as a string.
  201. */
  202. public function encoding($encoding = null) {
  203. $encodingMap = array('UTF-8' => 'utf8');
  204. if (!$encoding) {
  205. $query = $this->connection->query('PRAGMA encoding');
  206. $encoding = $query->fetchColumn();
  207. return ($key = array_search($encoding, $encodingMap)) ? $key : $encoding;
  208. }
  209. $encoding = isset($encodingMap[$encoding]) ? $encodingMap[$encoding] : $encoding;
  210. try {
  211. $this->connection->exec("PRAGMA encoding = \"{$encoding}\"");
  212. return true;
  213. } catch (PDOException $e) {
  214. return false;
  215. }
  216. }
  217. /**
  218. * Retrieves database error message and error code.
  219. *
  220. * @return array
  221. */
  222. public function error() {
  223. if ($error = $this->connection->errorInfo()) {
  224. return array($error[1], $error[2]);
  225. }
  226. }
  227. /**
  228. * Execute a given query.
  229. *
  230. * @see lithium\data\source\Database::renderCommand()
  231. * @param string $sql The sql string to execute
  232. * @param array $options No available options.
  233. * @return resource
  234. * @filter
  235. */
  236. protected function _execute($sql, array $options = array()) {
  237. $conn = $this->connection;
  238. $params = compact('sql', 'options');
  239. return $this->_filter(__METHOD__, $params, function($self, $params) use ($conn) {
  240. $sql = $params['sql'];
  241. $options = $params['options'];
  242. try {
  243. $resource = $conn->query($sql);
  244. } catch(PDOException $e) {
  245. $self->invokeMethod('_error', array($sql));
  246. };
  247. return $self->invokeMethod('_instance', array('result', compact('resource')));
  248. });
  249. }
  250. /**
  251. * Converts database-layer column types to basic types.
  252. *
  253. * @param string $real Real database-layer column type (i.e. "varchar(255)")
  254. * @return string Abstract column type (i.e. "string")
  255. */
  256. protected function _column($real) {
  257. if (is_array($real)) {
  258. return $real['type'] . (isset($real['length']) ? "({$real['length']})" : '');
  259. }
  260. if (!preg_match("/{$this->_regex['column']}/", $real, $column)) {
  261. return $real;
  262. }
  263. $column = array_intersect_key($column, array('type' => null, 'length' => null));
  264. if (isset($column['length']) && $column['length']) {
  265. $length = explode(',', $column['length']) + array(null, null);
  266. $column['length'] = $length[0] ? intval($length[0]) : null;
  267. $length[1] ? $column['precision'] = intval($length[1]) : null;
  268. }
  269. switch (true) {
  270. case in_array($column['type'], array('date', 'time', 'datetime', 'timestamp')):
  271. return $column;
  272. case ($column['type'] === 'tinyint' && $column['length'] == '1'):
  273. case ($column['type'] === 'boolean'):
  274. return array('type' => 'boolean');
  275. break;
  276. case (strpos($column['type'], 'int') !== false):
  277. $column['type'] = 'integer';
  278. break;
  279. case (strpos($column['type'], 'char') !== false || $column['type'] === 'tinytext'):
  280. $column['type'] = 'string';
  281. break;
  282. case (strpos($column['type'], 'text') !== false):
  283. $column['type'] = 'text';
  284. break;
  285. case (strpos($column['type'], 'blob') !== false || $column['type'] === 'binary'):
  286. $column['type'] = 'binary';
  287. break;
  288. case preg_match('/float|double|decimal/', $column['type']):
  289. $column['type'] = 'float';
  290. break;
  291. default:
  292. $column['type'] = 'text';
  293. break;
  294. }
  295. return $column;
  296. }
  297. }
  298. ?>