QueryBuilder.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\db\sqlite;
  8. use yii\base\InvalidArgumentException;
  9. use yii\base\NotSupportedException;
  10. use yii\db\Connection;
  11. use yii\db\Constraint;
  12. use yii\db\Expression;
  13. use yii\db\ExpressionInterface;
  14. use yii\db\Query;
  15. use yii\helpers\StringHelper;
  16. /**
  17. * QueryBuilder is the query builder for SQLite databases.
  18. *
  19. * @author Qiang Xue <qiang.xue@gmail.com>
  20. * @since 2.0
  21. */
  22. class QueryBuilder extends \yii\db\QueryBuilder
  23. {
  24. /**
  25. * @var array mapping from abstract column types (keys) to physical column types (values).
  26. */
  27. public $typeMap = [
  28. Schema::TYPE_PK => 'integer PRIMARY KEY AUTOINCREMENT NOT NULL',
  29. Schema::TYPE_UPK => 'integer UNSIGNED PRIMARY KEY AUTOINCREMENT NOT NULL',
  30. Schema::TYPE_BIGPK => 'integer PRIMARY KEY AUTOINCREMENT NOT NULL',
  31. Schema::TYPE_UBIGPK => 'integer UNSIGNED PRIMARY KEY AUTOINCREMENT NOT NULL',
  32. Schema::TYPE_CHAR => 'char(1)',
  33. Schema::TYPE_STRING => 'varchar(255)',
  34. Schema::TYPE_TEXT => 'text',
  35. Schema::TYPE_TINYINT => 'tinyint',
  36. Schema::TYPE_SMALLINT => 'smallint',
  37. Schema::TYPE_INTEGER => 'integer',
  38. Schema::TYPE_BIGINT => 'bigint',
  39. Schema::TYPE_FLOAT => 'float',
  40. Schema::TYPE_DOUBLE => 'double',
  41. Schema::TYPE_DECIMAL => 'decimal(10,0)',
  42. Schema::TYPE_DATETIME => 'datetime',
  43. Schema::TYPE_TIMESTAMP => 'timestamp',
  44. Schema::TYPE_TIME => 'time',
  45. Schema::TYPE_DATE => 'date',
  46. Schema::TYPE_BINARY => 'blob',
  47. Schema::TYPE_BOOLEAN => 'boolean',
  48. Schema::TYPE_MONEY => 'decimal(19,4)',
  49. ];
  50. /**
  51. * {@inheritdoc}
  52. */
  53. protected function defaultExpressionBuilders()
  54. {
  55. return array_merge(parent::defaultExpressionBuilders(), [
  56. 'yii\db\conditions\LikeCondition' => 'yii\db\sqlite\conditions\LikeConditionBuilder',
  57. 'yii\db\conditions\InCondition' => 'yii\db\sqlite\conditions\InConditionBuilder',
  58. ]);
  59. }
  60. /**
  61. * {@inheritdoc}
  62. * @see https://stackoverflow.com/questions/15277373/sqlite-upsert-update-or-insert/15277374#15277374
  63. */
  64. public function upsert($table, $insertColumns, $updateColumns, &$params)
  65. {
  66. /** @var Constraint[] $constraints */
  67. list($uniqueNames, $insertNames, $updateNames) = $this->prepareUpsertColumns($table, $insertColumns, $updateColumns, $constraints);
  68. if (empty($uniqueNames)) {
  69. return $this->insert($table, $insertColumns, $params);
  70. }
  71. list(, $placeholders, $values, $params) = $this->prepareInsertValues($table, $insertColumns, $params);
  72. $insertSql = 'INSERT OR IGNORE INTO ' . $this->db->quoteTableName($table)
  73. . (!empty($insertNames) ? ' (' . implode(', ', $insertNames) . ')' : '')
  74. . (!empty($placeholders) ? ' VALUES (' . implode(', ', $placeholders) . ')' : $values);
  75. if ($updateColumns === false) {
  76. return $insertSql;
  77. }
  78. $updateCondition = ['or'];
  79. $quotedTableName = $this->db->quoteTableName($table);
  80. foreach ($constraints as $constraint) {
  81. $constraintCondition = ['and'];
  82. foreach ($constraint->columnNames as $name) {
  83. $quotedName = $this->db->quoteColumnName($name);
  84. $constraintCondition[] = "$quotedTableName.$quotedName=(SELECT $quotedName FROM `EXCLUDED`)";
  85. }
  86. $updateCondition[] = $constraintCondition;
  87. }
  88. if ($updateColumns === true) {
  89. $updateColumns = [];
  90. foreach ($updateNames as $name) {
  91. $quotedName = $this->db->quoteColumnName($name);
  92. if (strrpos($quotedName, '.') === false) {
  93. $quotedName = "(SELECT $quotedName FROM `EXCLUDED`)";
  94. }
  95. $updateColumns[$name] = new Expression($quotedName);
  96. }
  97. }
  98. $updateSql = 'WITH "EXCLUDED" (' . implode(', ', $insertNames)
  99. . ') AS (' . (!empty($placeholders) ? 'VALUES (' . implode(', ', $placeholders) . ')' : ltrim($values, ' ')) . ') '
  100. . $this->update($table, $updateColumns, $updateCondition, $params);
  101. return "$updateSql; $insertSql;";
  102. }
  103. /**
  104. * Generates a batch INSERT SQL statement.
  105. *
  106. * For example,
  107. *
  108. * ```php
  109. * $connection->createCommand()->batchInsert('user', ['name', 'age'], [
  110. * ['Tom', 30],
  111. * ['Jane', 20],
  112. * ['Linda', 25],
  113. * ])->execute();
  114. * ```
  115. *
  116. * Note that the values in each row must match the corresponding column names.
  117. *
  118. * @param string $table the table that new rows will be inserted into.
  119. * @param array $columns the column names
  120. * @param array|\Generator $rows the rows to be batch inserted into the table
  121. * @return string the batch INSERT SQL statement
  122. */
  123. public function batchInsert($table, $columns, $rows, &$params = [])
  124. {
  125. if (empty($rows)) {
  126. return '';
  127. }
  128. // SQLite supports batch insert natively since 3.7.11
  129. // http://www.sqlite.org/releaselog/3_7_11.html
  130. $this->db->open(); // ensure pdo is not null
  131. if (version_compare($this->db->getServerVersion(), '3.7.11', '>=')) {
  132. return parent::batchInsert($table, $columns, $rows, $params);
  133. }
  134. $schema = $this->db->getSchema();
  135. if (($tableSchema = $schema->getTableSchema($table)) !== null) {
  136. $columnSchemas = $tableSchema->columns;
  137. } else {
  138. $columnSchemas = [];
  139. }
  140. $values = [];
  141. foreach ($rows as $row) {
  142. $vs = [];
  143. foreach ($row as $i => $value) {
  144. if (isset($columnSchemas[$columns[$i]])) {
  145. $value = $columnSchemas[$columns[$i]]->dbTypecast($value);
  146. }
  147. if (is_string($value)) {
  148. $value = $schema->quoteValue($value);
  149. } elseif (is_float($value)) {
  150. // ensure type cast always has . as decimal separator in all locales
  151. $value = StringHelper::floatToString($value);
  152. } elseif ($value === false) {
  153. $value = 0;
  154. } elseif ($value === null) {
  155. $value = 'NULL';
  156. } elseif ($value instanceof ExpressionInterface) {
  157. $value = $this->buildExpression($value, $params);
  158. }
  159. $vs[] = $value;
  160. }
  161. $values[] = implode(', ', $vs);
  162. }
  163. if (empty($values)) {
  164. return '';
  165. }
  166. foreach ($columns as $i => $name) {
  167. $columns[$i] = $schema->quoteColumnName($name);
  168. }
  169. return 'INSERT INTO ' . $schema->quoteTableName($table)
  170. . ' (' . implode(', ', $columns) . ') SELECT ' . implode(' UNION SELECT ', $values);
  171. }
  172. /**
  173. * Creates a SQL statement for resetting the sequence value of a table's primary key.
  174. * The sequence will be reset such that the primary key of the next new row inserted
  175. * will have the specified value or 1.
  176. * @param string $tableName the name of the table whose primary key sequence will be reset
  177. * @param mixed $value the value for the primary key of the next new row inserted. If this is not set,
  178. * the next new row's primary key will have a value 1.
  179. * @return string the SQL statement for resetting sequence
  180. * @throws InvalidArgumentException if the table does not exist or there is no sequence associated with the table.
  181. */
  182. public function resetSequence($tableName, $value = null)
  183. {
  184. $db = $this->db;
  185. $table = $db->getTableSchema($tableName);
  186. if ($table !== null && $table->sequenceName !== null) {
  187. $tableName = $db->quoteTableName($tableName);
  188. if ($value === null) {
  189. $key = $this->db->quoteColumnName(reset($table->primaryKey));
  190. $value = $this->db->useMaster(function (Connection $db) use ($key, $tableName) {
  191. return $db->createCommand("SELECT MAX($key) FROM $tableName")->queryScalar();
  192. });
  193. } else {
  194. $value = (int) $value - 1;
  195. }
  196. return "UPDATE sqlite_sequence SET seq='$value' WHERE name='{$table->name}'";
  197. } elseif ($table === null) {
  198. throw new InvalidArgumentException("Table not found: $tableName");
  199. }
  200. throw new InvalidArgumentException("There is not sequence associated with table '$tableName'.'");
  201. }
  202. /**
  203. * Enables or disables integrity check.
  204. * @param bool $check whether to turn on or off the integrity check.
  205. * @param string $schema the schema of the tables. Meaningless for SQLite.
  206. * @param string $table the table name. Meaningless for SQLite.
  207. * @return string the SQL statement for checking integrity
  208. * @throws NotSupportedException this is not supported by SQLite
  209. */
  210. public function checkIntegrity($check = true, $schema = '', $table = '')
  211. {
  212. return 'PRAGMA foreign_keys=' . (int) $check;
  213. }
  214. /**
  215. * Builds a SQL statement for truncating a DB table.
  216. * @param string $table the table to be truncated. The name will be properly quoted by the method.
  217. * @return string the SQL statement for truncating a DB table.
  218. */
  219. public function truncateTable($table)
  220. {
  221. return 'DELETE FROM ' . $this->db->quoteTableName($table);
  222. }
  223. /**
  224. * Builds a SQL statement for dropping an index.
  225. * @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
  226. * @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
  227. * @return string the SQL statement for dropping an index.
  228. */
  229. public function dropIndex($name, $table)
  230. {
  231. return 'DROP INDEX ' . $this->db->quoteTableName($name);
  232. }
  233. /**
  234. * Builds a SQL statement for dropping a DB column.
  235. * @param string $table the table whose column is to be dropped. The name will be properly quoted by the method.
  236. * @param string $column the name of the column to be dropped. The name will be properly quoted by the method.
  237. * @return string the SQL statement for dropping a DB column.
  238. * @throws NotSupportedException this is not supported by SQLite
  239. */
  240. public function dropColumn($table, $column)
  241. {
  242. throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
  243. }
  244. /**
  245. * Builds a SQL statement for renaming a column.
  246. * @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
  247. * @param string $oldName the old name of the column. The name will be properly quoted by the method.
  248. * @param string $newName the new name of the column. The name will be properly quoted by the method.
  249. * @return string the SQL statement for renaming a DB column.
  250. * @throws NotSupportedException this is not supported by SQLite
  251. */
  252. public function renameColumn($table, $oldName, $newName)
  253. {
  254. throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
  255. }
  256. /**
  257. * Builds a SQL statement for adding a foreign key constraint to an existing table.
  258. * The method will properly quote the table and column names.
  259. * @param string $name the name of the foreign key constraint.
  260. * @param string $table the table that the foreign key constraint will be added to.
  261. * @param string|array $columns the name of the column to that the constraint will be added on.
  262. * If there are multiple columns, separate them with commas or use an array to represent them.
  263. * @param string $refTable the table that the foreign key references to.
  264. * @param string|array $refColumns the name of the column that the foreign key references to.
  265. * If there are multiple columns, separate them with commas or use an array to represent them.
  266. * @param string $delete the ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
  267. * @param string $update the ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
  268. * @return string the SQL statement for adding a foreign key constraint to an existing table.
  269. * @throws NotSupportedException this is not supported by SQLite
  270. */
  271. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
  272. {
  273. throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
  274. }
  275. /**
  276. * Builds a SQL statement for dropping a foreign key constraint.
  277. * @param string $name the name of the foreign key constraint to be dropped. The name will be properly quoted by the method.
  278. * @param string $table the table whose foreign is to be dropped. The name will be properly quoted by the method.
  279. * @return string the SQL statement for dropping a foreign key constraint.
  280. * @throws NotSupportedException this is not supported by SQLite
  281. */
  282. public function dropForeignKey($name, $table)
  283. {
  284. throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
  285. }
  286. /**
  287. * Builds a SQL statement for renaming a DB table.
  288. *
  289. * @param string $table the table to be renamed. The name will be properly quoted by the method.
  290. * @param string $newName the new table name. The name will be properly quoted by the method.
  291. * @return string the SQL statement for renaming a DB table.
  292. */
  293. public function renameTable($table, $newName)
  294. {
  295. return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' RENAME TO ' . $this->db->quoteTableName($newName);
  296. }
  297. /**
  298. * Builds a SQL statement for changing the definition of a column.
  299. * @param string $table the table whose column is to be changed. The table name will be properly quoted by the method.
  300. * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
  301. * @param string $type the new column type. The [[getColumnType()]] method will be invoked to convert abstract
  302. * column type (if any) into the physical one. Anything that is not recognized as abstract type will be kept
  303. * in the generated SQL. For example, 'string' will be turned into 'varchar(255)', while 'string not null'
  304. * will become 'varchar(255) not null'.
  305. * @return string the SQL statement for changing the definition of a column.
  306. * @throws NotSupportedException this is not supported by SQLite
  307. */
  308. public function alterColumn($table, $column, $type)
  309. {
  310. throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
  311. }
  312. /**
  313. * Builds a SQL statement for adding a primary key constraint to an existing table.
  314. * @param string $name the name of the primary key constraint.
  315. * @param string $table the table that the primary key constraint will be added to.
  316. * @param string|array $columns comma separated string or array of columns that the primary key will consist of.
  317. * @return string the SQL statement for adding a primary key constraint to an existing table.
  318. * @throws NotSupportedException this is not supported by SQLite
  319. */
  320. public function addPrimaryKey($name, $table, $columns)
  321. {
  322. throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
  323. }
  324. /**
  325. * Builds a SQL statement for removing a primary key constraint to an existing table.
  326. * @param string $name the name of the primary key constraint to be removed.
  327. * @param string $table the table that the primary key constraint will be removed from.
  328. * @return string the SQL statement for removing a primary key constraint from an existing table.
  329. * @throws NotSupportedException this is not supported by SQLite
  330. */
  331. public function dropPrimaryKey($name, $table)
  332. {
  333. throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
  334. }
  335. /**
  336. * {@inheritdoc}
  337. * @throws NotSupportedException this is not supported by SQLite.
  338. */
  339. public function addUnique($name, $table, $columns)
  340. {
  341. throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
  342. }
  343. /**
  344. * {@inheritdoc}
  345. * @throws NotSupportedException this is not supported by SQLite.
  346. */
  347. public function dropUnique($name, $table)
  348. {
  349. throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
  350. }
  351. /**
  352. * {@inheritdoc}
  353. * @throws NotSupportedException this is not supported by SQLite.
  354. */
  355. public function addCheck($name, $table, $expression)
  356. {
  357. throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
  358. }
  359. /**
  360. * {@inheritdoc}
  361. * @throws NotSupportedException this is not supported by SQLite.
  362. */
  363. public function dropCheck($name, $table)
  364. {
  365. throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
  366. }
  367. /**
  368. * {@inheritdoc}
  369. * @throws NotSupportedException this is not supported by SQLite.
  370. */
  371. public function addDefaultValue($name, $table, $column, $value)
  372. {
  373. throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
  374. }
  375. /**
  376. * {@inheritdoc}
  377. * @throws NotSupportedException this is not supported by SQLite.
  378. */
  379. public function dropDefaultValue($name, $table)
  380. {
  381. throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
  382. }
  383. /**
  384. * {@inheritdoc}
  385. * @throws NotSupportedException
  386. * @since 2.0.8
  387. */
  388. public function addCommentOnColumn($table, $column, $comment)
  389. {
  390. throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
  391. }
  392. /**
  393. * {@inheritdoc}
  394. * @throws NotSupportedException
  395. * @since 2.0.8
  396. */
  397. public function addCommentOnTable($table, $comment)
  398. {
  399. throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
  400. }
  401. /**
  402. * {@inheritdoc}
  403. * @throws NotSupportedException
  404. * @since 2.0.8
  405. */
  406. public function dropCommentFromColumn($table, $column)
  407. {
  408. throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
  409. }
  410. /**
  411. * {@inheritdoc}
  412. * @throws NotSupportedException
  413. * @since 2.0.8
  414. */
  415. public function dropCommentFromTable($table)
  416. {
  417. throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
  418. }
  419. /**
  420. * {@inheritdoc}
  421. */
  422. public function buildLimit($limit, $offset)
  423. {
  424. $sql = '';
  425. if ($this->hasLimit($limit)) {
  426. $sql = 'LIMIT ' . $limit;
  427. if ($this->hasOffset($offset)) {
  428. $sql .= ' OFFSET ' . $offset;
  429. }
  430. } elseif ($this->hasOffset($offset)) {
  431. // limit is not optional in SQLite
  432. // http://www.sqlite.org/syntaxdiagrams.html#select-stmt
  433. $sql = "LIMIT 9223372036854775807 OFFSET $offset"; // 2^63-1
  434. }
  435. return $sql;
  436. }
  437. /**
  438. * {@inheritdoc}
  439. */
  440. public function build($query, $params = [])
  441. {
  442. $query = $query->prepare($this);
  443. $params = empty($params) ? $query->params : array_merge($params, $query->params);
  444. $clauses = [
  445. $this->buildSelect($query->select, $params, $query->distinct, $query->selectOption),
  446. $this->buildFrom($query->from, $params),
  447. $this->buildJoin($query->join, $params),
  448. $this->buildWhere($query->where, $params),
  449. $this->buildGroupBy($query->groupBy),
  450. $this->buildHaving($query->having, $params),
  451. ];
  452. $sql = implode($this->separator, array_filter($clauses));
  453. $sql = $this->buildOrderByAndLimit($sql, $query->orderBy, $query->limit, $query->offset);
  454. if (!empty($query->orderBy)) {
  455. foreach ($query->orderBy as $expression) {
  456. if ($expression instanceof ExpressionInterface) {
  457. $this->buildExpression($expression, $params);
  458. }
  459. }
  460. }
  461. if (!empty($query->groupBy)) {
  462. foreach ($query->groupBy as $expression) {
  463. if ($expression instanceof ExpressionInterface) {
  464. $this->buildExpression($expression, $params);
  465. }
  466. }
  467. }
  468. $union = $this->buildUnion($query->union, $params);
  469. if ($union !== '') {
  470. $sql = "$sql{$this->separator}$union";
  471. }
  472. return [$sql, $params];
  473. }
  474. /**
  475. * {@inheritdoc}
  476. */
  477. public function buildUnion($unions, &$params)
  478. {
  479. if (empty($unions)) {
  480. return '';
  481. }
  482. $result = '';
  483. foreach ($unions as $i => $union) {
  484. $query = $union['query'];
  485. if ($query instanceof Query) {
  486. list($unions[$i]['query'], $params) = $this->build($query, $params);
  487. }
  488. $result .= ' UNION ' . ($union['all'] ? 'ALL ' : '') . ' ' . $unions[$i]['query'];
  489. }
  490. return trim($result);
  491. }
  492. }