QueryBuilder.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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\Exception;
  9. use yii\base\InvalidParamException;
  10. use yii\base\NotSupportedException;
  11. /**
  12. * QueryBuilder is the query builder for SQLite databases.
  13. *
  14. * @author Qiang Xue <[email protected]>
  15. * @since 2.0
  16. */
  17. class QueryBuilder extends \yii\db\QueryBuilder
  18. {
  19. /**
  20. * @var array mapping from abstract column types (keys) to physical column types (values).
  21. */
  22. public $typeMap = [
  23. Schema::TYPE_PK => 'integer PRIMARY KEY AUTOINCREMENT NOT NULL',
  24. Schema::TYPE_BIGPK => 'integer PRIMARY KEY AUTOINCREMENT NOT NULL',
  25. Schema::TYPE_STRING => 'varchar(255)',
  26. Schema::TYPE_TEXT => 'text',
  27. Schema::TYPE_SMALLINT => 'smallint',
  28. Schema::TYPE_INTEGER => 'integer',
  29. Schema::TYPE_BIGINT => 'bigint',
  30. Schema::TYPE_FLOAT => 'float',
  31. Schema::TYPE_DECIMAL => 'decimal(10,0)',
  32. Schema::TYPE_DATETIME => 'datetime',
  33. Schema::TYPE_TIMESTAMP => 'timestamp',
  34. Schema::TYPE_TIME => 'time',
  35. Schema::TYPE_DATE => 'date',
  36. Schema::TYPE_BINARY => 'blob',
  37. Schema::TYPE_BOOLEAN => 'boolean',
  38. Schema::TYPE_MONEY => 'decimal(19,4)',
  39. ];
  40. /**
  41. * Generates a batch INSERT SQL statement.
  42. * For example,
  43. *
  44. * ~~~
  45. * $connection->createCommand()->batchInsert('tbl_user', ['name', 'age'], [
  46. * ['Tom', 30],
  47. * ['Jane', 20],
  48. * ['Linda', 25],
  49. * ])->execute();
  50. * ~~~
  51. *
  52. * Note that the values in each row must match the corresponding column names.
  53. *
  54. * @param string $table the table that new rows will be inserted into.
  55. * @param array $columns the column names
  56. * @param array $rows the rows to be batch inserted into the table
  57. * @return string the batch INSERT SQL statement
  58. */
  59. public function batchInsert($table, $columns, $rows)
  60. {
  61. if (($tableSchema = $this->db->getTableSchema($table)) !== null) {
  62. $columnSchemas = $tableSchema->columns;
  63. } else {
  64. $columnSchemas = [];
  65. }
  66. foreach ($columns as $i => $name) {
  67. $columns[$i] = $this->db->quoteColumnName($name);
  68. }
  69. $values = [];
  70. foreach ($rows as $row) {
  71. $vs = [];
  72. foreach ($row as $i => $value) {
  73. if (!is_array($value) && isset($columnSchemas[$columns[$i]])) {
  74. $value = $columnSchemas[$columns[$i]]->typecast($value);
  75. }
  76. $vs[] = is_string($value) ? $this->db->quoteValue($value) : $value;
  77. }
  78. $values[] = implode(', ', $vs);
  79. }
  80. return 'INSERT INTO ' . $this->db->quoteTableName($table)
  81. . ' (' . implode(', ', $columns) . ') SELECT ' . implode(' UNION ALL ', $values);
  82. }
  83. /**
  84. * Creates a SQL statement for resetting the sequence value of a table's primary key.
  85. * The sequence will be reset such that the primary key of the next new row inserted
  86. * will have the specified value or 1.
  87. * @param string $tableName the name of the table whose primary key sequence will be reset
  88. * @param mixed $value the value for the primary key of the next new row inserted. If this is not set,
  89. * the next new row's primary key will have a value 1.
  90. * @return string the SQL statement for resetting sequence
  91. * @throws InvalidParamException if the table does not exist or there is no sequence associated with the table.
  92. */
  93. public function resetSequence($tableName, $value = null)
  94. {
  95. $db = $this->db;
  96. $table = $db->getTableSchema($tableName);
  97. if ($table !== null && $table->sequenceName !== null) {
  98. if ($value === null) {
  99. $key = reset($table->primaryKey);
  100. $tableName = $db->quoteTableName($tableName);
  101. $value = $db->createCommand("SELECT MAX('$key') FROM $tableName")->queryScalar();
  102. } else {
  103. $value = (int)$value - 1;
  104. }
  105. try {
  106. // it's possible sqlite_sequence does not exist
  107. $db->createCommand("UPDATE sqlite_sequence SET seq='$value' WHERE name='{$table->name}'")->execute();
  108. } catch (Exception $e) {
  109. }
  110. } elseif ($table === null) {
  111. throw new InvalidParamException("Table not found: $tableName");
  112. } else {
  113. throw new InvalidParamException("There is not sequence associated with table '$tableName'.'");
  114. }
  115. }
  116. /**
  117. * Enables or disables integrity check.
  118. * @param boolean $check whether to turn on or off the integrity check.
  119. * @param string $schema the schema of the tables. Meaningless for SQLite.
  120. * @param string $table the table name. Meaningless for SQLite.
  121. * @return string the SQL statement for checking integrity
  122. * @throws NotSupportedException this is not supported by SQLite
  123. */
  124. public function checkIntegrity($check = true, $schema = '', $table = '')
  125. {
  126. throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
  127. }
  128. /**
  129. * Builds a SQL statement for truncating a DB table.
  130. * @param string $table the table to be truncated. The name will be properly quoted by the method.
  131. * @return string the SQL statement for truncating a DB table.
  132. */
  133. public function truncateTable($table)
  134. {
  135. return "DELETE FROM " . $this->db->quoteTableName($table);
  136. }
  137. /**
  138. * Builds a SQL statement for dropping an index.
  139. * @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
  140. * @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
  141. * @return string the SQL statement for dropping an index.
  142. */
  143. public function dropIndex($name, $table)
  144. {
  145. return 'DROP INDEX ' . $this->db->quoteTableName($name);
  146. }
  147. /**
  148. * Builds a SQL statement for dropping a DB column.
  149. * @param string $table the table whose column is to be dropped. The name will be properly quoted by the method.
  150. * @param string $column the name of the column to be dropped. The name will be properly quoted by the method.
  151. * @return string the SQL statement for dropping a DB column.
  152. * @throws NotSupportedException this is not supported by SQLite
  153. */
  154. public function dropColumn($table, $column)
  155. {
  156. throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
  157. }
  158. /**
  159. * Builds a SQL statement for renaming a column.
  160. * @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
  161. * @param string $oldName the old name of the column. The name will be properly quoted by the method.
  162. * @param string $newName the new name of the column. The name will be properly quoted by the method.
  163. * @return string the SQL statement for renaming a DB column.
  164. * @throws NotSupportedException this is not supported by SQLite
  165. */
  166. public function renameColumn($table, $oldName, $newName)
  167. {
  168. throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
  169. }
  170. /**
  171. * Builds a SQL statement for adding a foreign key constraint to an existing table.
  172. * The method will properly quote the table and column names.
  173. * @param string $name the name of the foreign key constraint.
  174. * @param string $table the table that the foreign key constraint will be added to.
  175. * @param string|array $columns the name of the column to that the constraint will be added on.
  176. * If there are multiple columns, separate them with commas or use an array to represent them.
  177. * @param string $refTable the table that the foreign key references to.
  178. * @param string|array $refColumns the name of the column that the foreign key references to.
  179. * If there are multiple columns, separate them with commas or use an array to represent them.
  180. * @param string $delete the ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
  181. * @param string $update the ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
  182. * @return string the SQL statement for adding a foreign key constraint to an existing table.
  183. * @throws NotSupportedException this is not supported by SQLite
  184. */
  185. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
  186. {
  187. throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
  188. }
  189. /**
  190. * Builds a SQL statement for dropping a foreign key constraint.
  191. * @param string $name the name of the foreign key constraint to be dropped. The name will be properly quoted by the method.
  192. * @param string $table the table whose foreign is to be dropped. The name will be properly quoted by the method.
  193. * @return string the SQL statement for dropping a foreign key constraint.
  194. * @throws NotSupportedException this is not supported by SQLite
  195. */
  196. public function dropForeignKey($name, $table)
  197. {
  198. throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
  199. }
  200. /**
  201. * Builds a SQL statement for changing the definition of a column.
  202. * @param string $table the table whose column is to be changed. The table name will be properly quoted by the method.
  203. * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
  204. * @param string $type the new column type. The [[getColumnType()]] method will be invoked to convert abstract
  205. * column type (if any) into the physical one. Anything that is not recognized as abstract type will be kept
  206. * in the generated SQL. For example, 'string' will be turned into 'varchar(255)', while 'string not null'
  207. * will become 'varchar(255) not null'.
  208. * @return string the SQL statement for changing the definition of a column.
  209. * @throws NotSupportedException this is not supported by SQLite
  210. */
  211. public function alterColumn($table, $column, $type)
  212. {
  213. throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
  214. }
  215. /**
  216. * Builds a SQL statement for adding a primary key constraint to an existing table.
  217. * @param string $name the name of the primary key constraint.
  218. * @param string $table the table that the primary key constraint will be added to.
  219. * @param string|array $columns comma separated string or array of columns that the primary key will consist of.
  220. * @return string the SQL statement for adding a primary key constraint to an existing table.
  221. * @throws NotSupportedException this is not supported by SQLite
  222. */
  223. public function addPrimaryKey($name, $table, $columns)
  224. {
  225. throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
  226. }
  227. /**
  228. * Builds a SQL statement for removing a primary key constraint to an existing table.
  229. * @param string $name the name of the primary key constraint to be removed.
  230. * @param string $table the table that the primary key constraint will be removed from.
  231. * @return string the SQL statement for removing a primary key constraint from an existing table.
  232. * @throws NotSupportedException this is not supported by SQLite *
  233. */
  234. public function dropPrimaryKey($name, $table)
  235. {
  236. throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
  237. }
  238. /**
  239. * @inheritdoc
  240. */
  241. public function buildLimit($limit, $offset)
  242. {
  243. $sql = '';
  244. // limit is not optional in SQLite
  245. // http://www.sqlite.org/syntaxdiagrams.html#select-stmt
  246. if ($limit !== null && $limit >= 0) {
  247. $sql = 'LIMIT ' . (int)$limit;
  248. if ($offset > 0) {
  249. $sql .= ' OFFSET ' . (int)$offset;
  250. }
  251. } elseif ($offset > 0) {
  252. $sql = 'LIMIT 9223372036854775807 OFFSET ' . (int)$offset; // 2^63-1
  253. }
  254. return $sql;
  255. }
  256. }