Sqlite.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Db
  17. * @subpackage Adapter
  18. * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. * @version $Id$
  21. */
  22. /**
  23. * @see Zend_Db_Adapter_Pdo_Abstract
  24. */
  25. require_once 'Zend/Db/Adapter/Pdo/Abstract.php';
  26. /**
  27. * Class for connecting to SQLite2 and SQLite3 databases and performing common operations.
  28. *
  29. * @category Zend
  30. * @package Zend_Db
  31. * @subpackage Adapter
  32. * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
  33. * @license http://framework.zend.com/license/new-bsd New BSD License
  34. */
  35. class Zend_Db_Adapter_Pdo_Sqlite extends Zend_Db_Adapter_Pdo_Abstract
  36. {
  37. /**
  38. * PDO type
  39. *
  40. * @var string
  41. */
  42. protected $_pdoType = 'sqlite';
  43. /**
  44. * Keys are UPPERCASE SQL datatypes or the constants
  45. * Zend_Db::INT_TYPE, Zend_Db::BIGINT_TYPE, or Zend_Db::FLOAT_TYPE.
  46. *
  47. * Values are:
  48. * 0 = 32-bit integer
  49. * 1 = 64-bit integer
  50. * 2 = float or decimal
  51. *
  52. * @var array Associative array of datatypes to values 0, 1, or 2.
  53. */
  54. protected $_numericDataTypes = array(
  55. Zend_Db::INT_TYPE => Zend_Db::INT_TYPE,
  56. Zend_Db::BIGINT_TYPE => Zend_Db::BIGINT_TYPE,
  57. Zend_Db::FLOAT_TYPE => Zend_Db::FLOAT_TYPE,
  58. 'INTEGER' => Zend_Db::BIGINT_TYPE,
  59. 'REAL' => Zend_Db::FLOAT_TYPE
  60. );
  61. /**
  62. * Constructor.
  63. *
  64. * $config is an array of key/value pairs containing configuration
  65. * options. Note that the SQLite options are different than most of
  66. * the other PDO adapters in that no username or password are needed.
  67. * Also, an extra config key "sqlite2" specifies compatibility mode.
  68. *
  69. * dbname => (string) The name of the database to user (required,
  70. * use :memory: for memory-based database)
  71. *
  72. * sqlite2 => (boolean) PDO_SQLITE defaults to SQLite 3. For compatibility
  73. * with an older SQLite 2 database, set this to TRUE.
  74. *
  75. * @param array $config An array of configuration keys.
  76. */
  77. public function __construct(array $config = array())
  78. {
  79. if (isset($config['sqlite2']) && $config['sqlite2']) {
  80. $this->_pdoType = 'sqlite2';
  81. }
  82. // SQLite uses no username/password. Stub to satisfy parent::_connect()
  83. $this->_config['username'] = null;
  84. $this->_config['password'] = null;
  85. return parent::__construct($config);
  86. }
  87. /**
  88. * Check for config options that are mandatory.
  89. * Throw exceptions if any are missing.
  90. *
  91. * @param array $config
  92. * @throws Zend_Db_Adapter_Exception
  93. */
  94. protected function _checkRequiredOptions(array $config)
  95. {
  96. // we need at least a dbname
  97. if (! array_key_exists('dbname', $config)) {
  98. /** @see Zend_Db_Adapter_Exception */
  99. require_once 'Zend/Db/Adapter/Exception.php';
  100. throw new Zend_Db_Adapter_Exception("Configuration array must have a key for 'dbname' that names the database instance");
  101. }
  102. }
  103. /**
  104. * DSN builder
  105. */
  106. protected function _dsn()
  107. {
  108. return $this->_pdoType .':'. $this->_config['dbname'];
  109. }
  110. /**
  111. * Special configuration for SQLite behavior: make sure that result sets
  112. * contain keys like 'column' instead of 'table.column'.
  113. *
  114. * @throws Zend_Db_Adapter_Exception
  115. */
  116. protected function _connect()
  117. {
  118. /**
  119. * if we already have a PDO object, no need to re-connect.
  120. */
  121. if ($this->_connection) {
  122. return;
  123. }
  124. parent::_connect();
  125. $retval = $this->_connection->exec('PRAGMA full_column_names=0');
  126. if ($retval === false) {
  127. $error = $this->_connection->errorInfo();
  128. /** @see Zend_Db_Adapter_Exception */
  129. require_once 'Zend/Db/Adapter/Exception.php';
  130. throw new Zend_Db_Adapter_Exception($error[2]);
  131. }
  132. $retval = $this->_connection->exec('PRAGMA short_column_names=1');
  133. if ($retval === false) {
  134. $error = $this->_connection->errorInfo();
  135. /** @see Zend_Db_Adapter_Exception */
  136. require_once 'Zend/Db/Adapter/Exception.php';
  137. throw new Zend_Db_Adapter_Exception($error[2]);
  138. }
  139. }
  140. /**
  141. * Returns a list of the tables in the database.
  142. *
  143. * @return array
  144. */
  145. public function listTables()
  146. {
  147. $sql = "SELECT name FROM sqlite_master WHERE type='table' "
  148. . "UNION ALL SELECT name FROM sqlite_temp_master "
  149. . "WHERE type='table' ORDER BY name";
  150. return $this->fetchCol($sql);
  151. }
  152. /**
  153. * Returns the column descriptions for a table.
  154. *
  155. * The return value is an associative array keyed by the column name,
  156. * as returned by the RDBMS.
  157. *
  158. * The value of each array element is an associative array
  159. * with the following keys:
  160. *
  161. * SCHEMA_NAME => string; name of database or schema
  162. * TABLE_NAME => string;
  163. * COLUMN_NAME => string; column name
  164. * COLUMN_POSITION => number; ordinal position of column in table
  165. * DATA_TYPE => string; SQL datatype name of column
  166. * DEFAULT => string; default expression of column, null if none
  167. * NULLABLE => boolean; true if column can have nulls
  168. * LENGTH => number; length of CHAR/VARCHAR
  169. * SCALE => number; scale of NUMERIC/DECIMAL
  170. * PRECISION => number; precision of NUMERIC/DECIMAL
  171. * UNSIGNED => boolean; unsigned property of an integer type
  172. * PRIMARY => boolean; true if column is part of the primary key
  173. * PRIMARY_POSITION => integer; position of column in primary key
  174. * IDENTITY => integer; true if column is auto-generated with unique values
  175. *
  176. * @param string $tableName
  177. * @param string $schemaName OPTIONAL
  178. * @return array
  179. */
  180. public function describeTable($tableName, $schemaName = null)
  181. {
  182. $sql = 'PRAGMA ';
  183. if ($schemaName) {
  184. $sql .= $this->quoteIdentifier($schemaName) . '.';
  185. }
  186. $sql .= 'table_info('.$this->quoteIdentifier($tableName).')';
  187. $stmt = $this->query($sql);
  188. /**
  189. * Use FETCH_NUM so we are not dependent on the CASE attribute of the PDO connection
  190. */
  191. $result = $stmt->fetchAll(Zend_Db::FETCH_NUM);
  192. $cid = 0;
  193. $name = 1;
  194. $type = 2;
  195. $notnull = 3;
  196. $dflt_value = 4;
  197. $pk = 5;
  198. $desc = array();
  199. $p = 1;
  200. foreach ($result as $key => $row) {
  201. list($length, $scale, $precision, $primary, $primaryPosition, $identity) =
  202. array(null, null, null, false, null, false);
  203. if (preg_match('/^((?:var)?char)\((\d+)\)/i', $row[$type], $matches)) {
  204. $row[$type] = $matches[1];
  205. $length = $matches[2];
  206. } else if (preg_match('/^decimal\((\d+),(\d+)\)/i', $row[$type], $matches)) {
  207. $row[$type] = 'DECIMAL';
  208. $precision = $matches[1];
  209. $scale = $matches[2];
  210. }
  211. if ((bool) $row[$pk]) {
  212. $primary = true;
  213. $primaryPosition = $p;
  214. /**
  215. * SQLite INTEGER primary key is always auto-increment.
  216. */
  217. $identity = (bool) ($row[$type] == 'INTEGER');
  218. ++$p;
  219. }
  220. $desc[$this->foldCase($row[$name])] = array(
  221. 'SCHEMA_NAME' => $this->foldCase($schemaName),
  222. 'TABLE_NAME' => $this->foldCase($tableName),
  223. 'COLUMN_NAME' => $this->foldCase($row[$name]),
  224. 'COLUMN_POSITION' => $row[$cid]+1,
  225. 'DATA_TYPE' => $row[$type],
  226. 'DEFAULT' => $row[$dflt_value],
  227. 'NULLABLE' => ! (bool) $row[$notnull],
  228. 'LENGTH' => $length,
  229. 'SCALE' => $scale,
  230. 'PRECISION' => $precision,
  231. 'UNSIGNED' => null, // Sqlite3 does not support unsigned data
  232. 'PRIMARY' => $primary,
  233. 'PRIMARY_POSITION' => $primaryPosition,
  234. 'IDENTITY' => $identity
  235. );
  236. }
  237. return $desc;
  238. }
  239. /**
  240. * Adds an adapter-specific LIMIT clause to the SELECT statement.
  241. *
  242. * @param string $sql
  243. * @param integer $count
  244. * @param integer $offset OPTIONAL
  245. * @return string
  246. */
  247. public function limit($sql, $count, $offset = 0)
  248. {
  249. $count = intval($count);
  250. if ($count <= 0) {
  251. /** @see Zend_Db_Adapter_Exception */
  252. require_once 'Zend/Db/Adapter/Exception.php';
  253. throw new Zend_Db_Adapter_Exception("LIMIT argument count=$count is not valid");
  254. }
  255. $offset = intval($offset);
  256. if ($offset < 0) {
  257. /** @see Zend_Db_Adapter_Exception */
  258. require_once 'Zend/Db/Adapter/Exception.php';
  259. throw new Zend_Db_Adapter_Exception("LIMIT argument offset=$offset is not valid");
  260. }
  261. $sql .= " LIMIT $count";
  262. if ($offset > 0) {
  263. $sql .= " OFFSET $offset";
  264. }
  265. return $sql;
  266. }
  267. /**
  268. * Quote a raw string.
  269. *
  270. * @param string $value Raw string
  271. * @return string Quoted string
  272. */
  273. protected function _quote($value)
  274. {
  275. if (!is_int($value) && !is_float($value)) {
  276. // Fix for null-byte injection
  277. $value = addcslashes($value, "\000\032");
  278. }
  279. return parent::_quote($value);
  280. }
  281. }