SqlitePlatform.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. <?php
  2. /*
  3. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  4. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  5. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  11. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  12. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  13. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  14. *
  15. * This software consists of voluntary contributions made by many individuals
  16. * and is licensed under the LGPL. For more information, see
  17. * <http://www.doctrine-project.org>.
  18. */
  19. namespace Doctrine\DBAL\Platforms;
  20. use Doctrine\DBAL\DBALException;
  21. /**
  22. * The SqlitePlatform class describes the specifics and dialects of the SQLite
  23. * database platform.
  24. *
  25. * @since 2.0
  26. * @author Roman Borschel <roman@code-factory.org>
  27. * @author Benjamin Eberlei <kontakt@beberlei.de>
  28. * @todo Rename: SQLitePlatform
  29. */
  30. class SqlitePlatform extends AbstractPlatform
  31. {
  32. /**
  33. * returns the regular expression operator
  34. *
  35. * @return string
  36. * @override
  37. */
  38. public function getRegexpExpression()
  39. {
  40. return 'RLIKE';
  41. }
  42. /**
  43. * Return string to call a variable with the current timestamp inside an SQL statement
  44. * There are three special variables for current date and time.
  45. *
  46. * @return string sqlite function as string
  47. * @override
  48. */
  49. public function getNowExpression($type = 'timestamp')
  50. {
  51. switch ($type) {
  52. case 'time':
  53. return 'time(\'now\')';
  54. case 'date':
  55. return 'date(\'now\')';
  56. case 'timestamp':
  57. default:
  58. return 'datetime(\'now\')';
  59. }
  60. }
  61. /**
  62. * Trim a string, leading/trailing/both and with a given char which defaults to space.
  63. *
  64. * @param string $str
  65. * @param int $pos
  66. * @param string $char
  67. * @return string
  68. */
  69. public function getTrimExpression($str, $pos = self::TRIM_UNSPECIFIED, $char = false)
  70. {
  71. $trimFn = '';
  72. $trimChar = ($char != false) ? (', ' . $char) : '';
  73. if ($pos == self::TRIM_LEADING) {
  74. $trimFn = 'LTRIM';
  75. } else if($pos == self::TRIM_TRAILING) {
  76. $trimFn = 'RTRIM';
  77. } else {
  78. $trimFn = 'TRIM';
  79. }
  80. return $trimFn . '(' . $str . $trimChar . ')';
  81. }
  82. /**
  83. * return string to call a function to get a substring inside an SQL statement
  84. *
  85. * Note: Not SQL92, but common functionality.
  86. *
  87. * SQLite only supports the 2 parameter variant of this function
  88. *
  89. * @param string $value an sql string literal or column name/alias
  90. * @param integer $position where to start the substring portion
  91. * @param integer $length the substring portion length
  92. * @return string SQL substring function with given parameters
  93. * @override
  94. */
  95. public function getSubstringExpression($value, $position, $length = null)
  96. {
  97. if ($length !== null) {
  98. return 'SUBSTR(' . $value . ', ' . $position . ', ' . $length . ')';
  99. }
  100. return 'SUBSTR(' . $value . ', ' . $position . ', LENGTH(' . $value . '))';
  101. }
  102. /**
  103. * returns the position of the first occurrence of substring $substr in string $str
  104. *
  105. * @param string $substr literal string to find
  106. * @param string $str literal string
  107. * @param int $pos position to start at, beginning of string by default
  108. * @return integer
  109. */
  110. public function getLocateExpression($str, $substr, $startPos = false)
  111. {
  112. if ($startPos == false) {
  113. return 'LOCATE('.$str.', '.$substr.')';
  114. } else {
  115. return 'LOCATE('.$str.', '.$substr.', '.$startPos.')';
  116. }
  117. }
  118. public function getDateDiffExpression($date1, $date2)
  119. {
  120. return 'ROUND(JULIANDAY('.$date1 . ')-JULIANDAY('.$date2.'))';
  121. }
  122. public function getDateAddDaysExpression($date, $days)
  123. {
  124. return "DATE(" . $date . ",'+". $days . " day')";
  125. }
  126. public function getDateSubDaysExpression($date, $days)
  127. {
  128. return "DATE(" . $date . ",'-". $days . " day')";
  129. }
  130. public function getDateAddMonthExpression($date, $months)
  131. {
  132. return "DATE(" . $date . ",'+". $months . " month')";
  133. }
  134. public function getDateSubMonthExpression($date, $months)
  135. {
  136. return "DATE(" . $date . ",'-". $months . " month')";
  137. }
  138. protected function _getTransactionIsolationLevelSQL($level)
  139. {
  140. switch ($level) {
  141. case \Doctrine\DBAL\Connection::TRANSACTION_READ_UNCOMMITTED:
  142. return 0;
  143. case \Doctrine\DBAL\Connection::TRANSACTION_READ_COMMITTED:
  144. case \Doctrine\DBAL\Connection::TRANSACTION_REPEATABLE_READ:
  145. case \Doctrine\DBAL\Connection::TRANSACTION_SERIALIZABLE:
  146. return 1;
  147. default:
  148. return parent::_getTransactionIsolationLevelSQL($level);
  149. }
  150. }
  151. public function getSetTransactionIsolationSQL($level)
  152. {
  153. return 'PRAGMA read_uncommitted = ' . $this->_getTransactionIsolationLevelSQL($level);
  154. }
  155. /**
  156. * @override
  157. */
  158. public function prefersIdentityColumns()
  159. {
  160. return true;
  161. }
  162. /**
  163. * @override
  164. */
  165. public function getBooleanTypeDeclarationSQL(array $field)
  166. {
  167. return 'BOOLEAN';
  168. }
  169. /**
  170. * @override
  171. */
  172. public function getIntegerTypeDeclarationSQL(array $field)
  173. {
  174. return $this->_getCommonIntegerTypeDeclarationSQL($field);
  175. }
  176. /**
  177. * @override
  178. */
  179. public function getBigIntTypeDeclarationSQL(array $field)
  180. {
  181. return $this->_getCommonIntegerTypeDeclarationSQL($field);
  182. }
  183. /**
  184. * @override
  185. */
  186. public function getTinyIntTypeDeclarationSql(array $field)
  187. {
  188. return $this->_getCommonIntegerTypeDeclarationSQL($field);
  189. }
  190. /**
  191. * @override
  192. */
  193. public function getSmallIntTypeDeclarationSQL(array $field)
  194. {
  195. return $this->_getCommonIntegerTypeDeclarationSQL($field);
  196. }
  197. /**
  198. * @override
  199. */
  200. public function getMediumIntTypeDeclarationSql(array $field)
  201. {
  202. return $this->_getCommonIntegerTypeDeclarationSQL($field);
  203. }
  204. /**
  205. * @override
  206. */
  207. public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration)
  208. {
  209. return 'DATETIME';
  210. }
  211. /**
  212. * @override
  213. */
  214. public function getDateTypeDeclarationSQL(array $fieldDeclaration)
  215. {
  216. return 'DATE';
  217. }
  218. /**
  219. * @override
  220. */
  221. public function getTimeTypeDeclarationSQL(array $fieldDeclaration)
  222. {
  223. return 'TIME';
  224. }
  225. /**
  226. * @override
  227. */
  228. protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef)
  229. {
  230. return 'INTEGER';
  231. }
  232. /**
  233. * create a new table
  234. *
  235. * @param string $name Name of the database that should be created
  236. * @param array $fields Associative array that contains the definition of each field of the new table
  237. * The indexes of the array entries are the names of the fields of the table an
  238. * the array entry values are associative arrays like those that are meant to be
  239. * passed with the field definitions to get[Type]Declaration() functions.
  240. * array(
  241. * 'id' => array(
  242. * 'type' => 'integer',
  243. * 'unsigned' => 1
  244. * 'notnull' => 1
  245. * 'default' => 0
  246. * ),
  247. * 'name' => array(
  248. * 'type' => 'text',
  249. * 'length' => 12
  250. * ),
  251. * 'password' => array(
  252. * 'type' => 'text',
  253. * 'length' => 12
  254. * )
  255. * );
  256. * @param array $options An associative array of table options:
  257. *
  258. * @return void
  259. * @override
  260. */
  261. protected function _getCreateTableSQL($name, array $columns, array $options = array())
  262. {
  263. $name = str_replace(".", "__", $name);
  264. $queryFields = $this->getColumnDeclarationListSQL($columns);
  265. if (isset($options['primary']) && ! empty($options['primary'])) {
  266. $keyColumns = array_unique(array_values($options['primary']));
  267. $keyColumns = array_map(array($this, 'quoteIdentifier'), $keyColumns);
  268. $queryFields.= ', PRIMARY KEY('.implode(', ', $keyColumns).')';
  269. }
  270. $query[] = 'CREATE TABLE ' . $name . ' (' . $queryFields . ')';
  271. if (isset($options['indexes']) && ! empty($options['indexes'])) {
  272. foreach ($options['indexes'] as $index => $indexDef) {
  273. $query[] = $this->getCreateIndexSQL($indexDef, $name);
  274. }
  275. }
  276. if (isset($options['unique']) && ! empty($options['unique'])) {
  277. foreach ($options['unique'] as $index => $indexDef) {
  278. $query[] = $this->getCreateIndexSQL($indexDef, $name);
  279. }
  280. }
  281. return $query;
  282. }
  283. /**
  284. * {@inheritdoc}
  285. */
  286. protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed)
  287. {
  288. return $fixed ? ($length ? 'CHAR(' . $length . ')' : 'CHAR(255)')
  289. : ($length ? 'VARCHAR(' . $length . ')' : 'TEXT');
  290. }
  291. public function getClobTypeDeclarationSQL(array $field)
  292. {
  293. return 'CLOB';
  294. }
  295. public function getListTableConstraintsSQL($table)
  296. {
  297. $table = str_replace(".", "__", $table);
  298. return "SELECT sql FROM sqlite_master WHERE type='index' AND tbl_name = '$table' AND sql NOT NULL ORDER BY name";
  299. }
  300. public function getListTableColumnsSQL($table, $currentDatabase = null)
  301. {
  302. $table = str_replace(".", "__", $table);
  303. return "PRAGMA table_info($table)";
  304. }
  305. public function getListTableIndexesSQL($table, $currentDatabase = null)
  306. {
  307. $table = str_replace(".", "__", $table);
  308. return "PRAGMA index_list($table)";
  309. }
  310. public function getListTablesSQL()
  311. {
  312. return "SELECT name FROM sqlite_master WHERE type = 'table' AND name != 'sqlite_sequence' AND name != 'geometry_columns' AND name != 'spatial_ref_sys' "
  313. . "UNION ALL SELECT name FROM sqlite_temp_master "
  314. . "WHERE type = 'table' ORDER BY name";
  315. }
  316. public function getListViewsSQL($database)
  317. {
  318. return "SELECT name, sql FROM sqlite_master WHERE type='view' AND sql NOT NULL";
  319. }
  320. public function getCreateViewSQL($name, $sql)
  321. {
  322. return 'CREATE VIEW ' . $name . ' AS ' . $sql;
  323. }
  324. public function getDropViewSQL($name)
  325. {
  326. return 'DROP VIEW '. $name;
  327. }
  328. /**
  329. * SQLite does support foreign key constraints, but only in CREATE TABLE statements...
  330. * This really limits their usefulness and requires SQLite specific handling, so
  331. * we simply say that SQLite does NOT support foreign keys for now...
  332. *
  333. * @return boolean FALSE
  334. * @override
  335. */
  336. public function supportsForeignKeyConstraints()
  337. {
  338. return false;
  339. }
  340. public function supportsAlterTable()
  341. {
  342. return false;
  343. }
  344. public function supportsIdentityColumns()
  345. {
  346. return true;
  347. }
  348. /**
  349. * Get the platform name for this instance
  350. *
  351. * @return string
  352. */
  353. public function getName()
  354. {
  355. return 'sqlite';
  356. }
  357. /**
  358. * @inheritdoc
  359. */
  360. public function getTruncateTableSQL($tableName, $cascade = false)
  361. {
  362. $tableName = str_replace(".", "__", $tableName);
  363. return 'DELETE FROM '.$tableName;
  364. }
  365. /**
  366. * User-defined function for Sqlite that is used with PDO::sqliteCreateFunction()
  367. *
  368. * @param int|float $value
  369. * @return float
  370. */
  371. static public function udfSqrt($value)
  372. {
  373. return sqrt($value);
  374. }
  375. /**
  376. * User-defined function for Sqlite that implements MOD(a, b)
  377. */
  378. static public function udfMod($a, $b)
  379. {
  380. return ($a % $b);
  381. }
  382. /**
  383. * @param string $str
  384. * @param string $substr
  385. * @param int $offset
  386. */
  387. static public function udfLocate($str, $substr, $offset = 0)
  388. {
  389. $pos = strpos($str, $substr, $offset);
  390. if ($pos !== false) {
  391. return $pos+1;
  392. }
  393. return 0;
  394. }
  395. public function getForUpdateSql()
  396. {
  397. return '';
  398. }
  399. protected function initializeDoctrineTypeMappings()
  400. {
  401. $this->doctrineTypeMapping = array(
  402. 'boolean' => 'boolean',
  403. 'tinyint' => 'boolean',
  404. 'smallint' => 'smallint',
  405. 'mediumint' => 'integer',
  406. 'int' => 'integer',
  407. 'integer' => 'integer',
  408. 'serial' => 'integer',
  409. 'bigint' => 'bigint',
  410. 'bigserial' => 'bigint',
  411. 'clob' => 'text',
  412. 'tinytext' => 'text',
  413. 'mediumtext' => 'text',
  414. 'longtext' => 'text',
  415. 'text' => 'text',
  416. 'varchar' => 'string',
  417. 'longvarchar' => 'string',
  418. 'varchar2' => 'string',
  419. 'nvarchar' => 'string',
  420. 'image' => 'string',
  421. 'ntext' => 'string',
  422. 'char' => 'string',
  423. 'date' => 'date',
  424. 'datetime' => 'datetime',
  425. 'timestamp' => 'datetime',
  426. 'time' => 'time',
  427. 'float' => 'float',
  428. 'double' => 'float',
  429. 'double precision' => 'float',
  430. 'real' => 'float',
  431. 'decimal' => 'decimal',
  432. 'numeric' => 'decimal',
  433. 'blob' => 'blob',
  434. );
  435. }
  436. protected function getReservedKeywordsClass()
  437. {
  438. return 'Doctrine\DBAL\Platforms\Keywords\SQLiteKeywords';
  439. }
  440. /**
  441. * Gets the SQL Snippet used to declare a BLOB column type.
  442. */
  443. public function getBlobTypeDeclarationSQL(array $field)
  444. {
  445. return 'BLOB';
  446. }
  447. public function getTemporaryTableName($tableName)
  448. {
  449. $tableName = str_replace(".", "__", $tableName);
  450. return $tableName;
  451. }
  452. /**
  453. * Sqlite Platform emulates schema by underscoring each dot and generating tables
  454. * into the default database.
  455. *
  456. * This hack is implemented to be able to use SQLite as testdriver when
  457. * using schema supporting databases.
  458. *
  459. * @return bool
  460. */
  461. public function canEmulateSchemas()
  462. {
  463. return true;
  464. }
  465. }