QueryBuilder.php 18 KB

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