QueryBuilder.php 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491
  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;
  8. use yii\base\InvalidParamException;
  9. use yii\base\NotSupportedException;
  10. use yii\helpers\ArrayHelper;
  11. /**
  12. * QueryBuilder builds a SELECT SQL statement based on the specification given as a [[Query]] object.
  13. *
  14. * SQL statements are created from [[Query]] objects using the [[build()]]-method.
  15. *
  16. * QueryBuilder is also used by [[Command]] to build SQL statements such as INSERT, UPDATE, DELETE, CREATE TABLE.
  17. *
  18. * For more details and usage information on QueryBuilder, see the [guide article on query builders](guide:db-query-builder).
  19. *
  20. * @author Qiang Xue <qiang.xue@gmail.com>
  21. * @since 2.0
  22. */
  23. class QueryBuilder extends \yii\base\Object
  24. {
  25. /**
  26. * The prefix for automatically generated query binding parameters.
  27. */
  28. const PARAM_PREFIX = ':qp';
  29. /**
  30. * @var Connection the database connection.
  31. */
  32. public $db;
  33. /**
  34. * @var string the separator between different fragments of a SQL statement.
  35. * Defaults to an empty space. This is mainly used by [[build()]] when generating a SQL statement.
  36. */
  37. public $separator = ' ';
  38. /**
  39. * @var array the abstract column types mapped to physical column types.
  40. * This is mainly used to support creating/modifying tables using DB-independent data type specifications.
  41. * Child classes should override this property to declare supported type mappings.
  42. */
  43. public $typeMap = [];
  44. /**
  45. * @var array map of query condition to builder methods.
  46. * These methods are used by [[buildCondition]] to build SQL conditions from array syntax.
  47. */
  48. protected $conditionBuilders = [
  49. 'NOT' => 'buildNotCondition',
  50. 'AND' => 'buildAndCondition',
  51. 'OR' => 'buildAndCondition',
  52. 'BETWEEN' => 'buildBetweenCondition',
  53. 'NOT BETWEEN' => 'buildBetweenCondition',
  54. 'IN' => 'buildInCondition',
  55. 'NOT IN' => 'buildInCondition',
  56. 'LIKE' => 'buildLikeCondition',
  57. 'NOT LIKE' => 'buildLikeCondition',
  58. 'OR LIKE' => 'buildLikeCondition',
  59. 'OR NOT LIKE' => 'buildLikeCondition',
  60. 'EXISTS' => 'buildExistsCondition',
  61. 'NOT EXISTS' => 'buildExistsCondition',
  62. ];
  63. /**
  64. * @var array map of chars to their replacements in LIKE conditions.
  65. * By default it's configured to escape `%`, `_` and `\` with `\`.
  66. * @since 2.0.12.
  67. */
  68. protected $likeEscapingReplacements = [
  69. '%' => '\%',
  70. '_' => '\_',
  71. '\\' => '\\\\',
  72. ];
  73. /**
  74. * @var string|null character used to escape special characters in LIKE conditions.
  75. * By default it's assumed to be `\`.
  76. * @since 2.0.12
  77. */
  78. protected $likeEscapeCharacter;
  79. /**
  80. * Constructor.
  81. * @param Connection $connection the database connection.
  82. * @param array $config name-value pairs that will be used to initialize the object properties
  83. */
  84. public function __construct($connection, $config = [])
  85. {
  86. $this->db = $connection;
  87. parent::__construct($config);
  88. }
  89. /**
  90. * Generates a SELECT SQL statement from a [[Query]] object.
  91. * @param Query $query the [[Query]] object from which the SQL statement will be generated.
  92. * @param array $params the parameters to be bound to the generated SQL statement. These parameters will
  93. * be included in the result with the additional parameters generated during the query building process.
  94. * @return array the generated SQL statement (the first array element) and the corresponding
  95. * parameters to be bound to the SQL statement (the second array element). The parameters returned
  96. * include those provided in `$params`.
  97. */
  98. public function build($query, $params = [])
  99. {
  100. $query = $query->prepare($this);
  101. $params = empty($params) ? $query->params : array_merge($params, $query->params);
  102. $clauses = [
  103. $this->buildSelect($query->select, $params, $query->distinct, $query->selectOption),
  104. $this->buildFrom($query->from, $params),
  105. $this->buildJoin($query->join, $params),
  106. $this->buildWhere($query->where, $params),
  107. $this->buildGroupBy($query->groupBy),
  108. $this->buildHaving($query->having, $params),
  109. ];
  110. $sql = implode($this->separator, array_filter($clauses));
  111. $sql = $this->buildOrderByAndLimit($sql, $query->orderBy, $query->limit, $query->offset);
  112. if (!empty($query->orderBy)) {
  113. foreach ($query->orderBy as $expression) {
  114. if ($expression instanceof Expression) {
  115. $params = array_merge($params, $expression->params);
  116. }
  117. }
  118. }
  119. if (!empty($query->groupBy)) {
  120. foreach ($query->groupBy as $expression) {
  121. if ($expression instanceof Expression) {
  122. $params = array_merge($params, $expression->params);
  123. }
  124. }
  125. }
  126. $union = $this->buildUnion($query->union, $params);
  127. if ($union !== '') {
  128. $sql = "($sql){$this->separator}$union";
  129. }
  130. return [$sql, $params];
  131. }
  132. /**
  133. * Creates an INSERT SQL statement.
  134. * For example,
  135. *
  136. * ```php
  137. * $sql = $queryBuilder->insert('user', [
  138. * 'name' => 'Sam',
  139. * 'age' => 30,
  140. * ], $params);
  141. * ```
  142. *
  143. * The method will properly escape the table and column names.
  144. *
  145. * @param string $table the table that new rows will be inserted into.
  146. * @param array|\yii\db\Query $columns the column data (name => value) to be inserted into the table or instance
  147. * of [[yii\db\Query|Query]] to perform INSERT INTO ... SELECT SQL statement.
  148. * Passing of [[yii\db\Query|Query]] is available since version 2.0.11.
  149. * @param array $params the binding parameters that will be generated by this method.
  150. * They should be bound to the DB command later.
  151. * @return string the INSERT SQL
  152. */
  153. public function insert($table, $columns, &$params)
  154. {
  155. $schema = $this->db->getSchema();
  156. if (($tableSchema = $schema->getTableSchema($table)) !== null) {
  157. $columnSchemas = $tableSchema->columns;
  158. } else {
  159. $columnSchemas = [];
  160. }
  161. $names = [];
  162. $placeholders = [];
  163. $values = ' DEFAULT VALUES';
  164. if ($columns instanceof \yii\db\Query) {
  165. list($names, $values, $params) = $this->prepareInsertSelectSubQuery($columns, $schema);
  166. } else {
  167. foreach ($columns as $name => $value) {
  168. $names[] = $schema->quoteColumnName($name);
  169. if ($value instanceof Expression) {
  170. $placeholders[] = $value->expression;
  171. foreach ($value->params as $n => $v) {
  172. $params[$n] = $v;
  173. }
  174. } elseif ($value instanceof \yii\db\Query) {
  175. list($sql, $params) = $this->build($value, $params);
  176. $placeholders[] = "($sql)";
  177. } else {
  178. $phName = self::PARAM_PREFIX . count($params);
  179. $placeholders[] = $phName;
  180. $params[$phName] = !is_array($value) && isset($columnSchemas[$name]) ? $columnSchemas[$name]->dbTypecast($value) : $value;
  181. }
  182. }
  183. }
  184. return 'INSERT INTO ' . $schema->quoteTableName($table)
  185. . (!empty($names) ? ' (' . implode(', ', $names) . ')' : '')
  186. . (!empty($placeholders) ? ' VALUES (' . implode(', ', $placeholders) . ')' : $values);
  187. }
  188. /**
  189. * Prepare select-subquery and field names for INSERT INTO ... SELECT SQL statement.
  190. *
  191. * @param \yii\db\Query $columns Object, which represents select query.
  192. * @param \yii\db\Schema $schema Schema object to quote column name.
  193. * @param array $params the parameters to be bound to the generated SQL statement. These parameters will
  194. * be included in the result with the additional parameters generated during the query building process.
  195. * @return array
  196. * @throws InvalidParamException if query's select does not contain named parameters only.
  197. * @since 2.0.11
  198. */
  199. protected function prepareInsertSelectSubQuery($columns, $schema, $params = [])
  200. {
  201. if (!is_array($columns->select) || empty($columns->select) || in_array('*', $columns->select)) {
  202. throw new InvalidParamException('Expected select query object with enumerated (named) parameters');
  203. }
  204. list($values, $params) = $this->build($columns, $params);
  205. $names = [];
  206. $values = ' ' . $values;
  207. foreach ($columns->select as $title => $field) {
  208. if (is_string($title)) {
  209. $names[] = $schema->quoteColumnName($title);
  210. } else if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_\.]+)$/', $field, $matches)) {
  211. $names[] = $schema->quoteColumnName($matches[2]);
  212. } else {
  213. $names[] = $schema->quoteColumnName($field);
  214. }
  215. }
  216. return [$names, $values, $params];
  217. }
  218. /**
  219. * Generates a batch INSERT SQL statement.
  220. * For example,
  221. *
  222. * ```php
  223. * $sql = $queryBuilder->batchInsert('user', ['name', 'age'], [
  224. * ['Tom', 30],
  225. * ['Jane', 20],
  226. * ['Linda', 25],
  227. * ]);
  228. * ```
  229. *
  230. * Note that the values in each row must match the corresponding column names.
  231. *
  232. * The method will properly escape the column names, and quote the values to be inserted.
  233. *
  234. * @param string $table the table that new rows will be inserted into.
  235. * @param array $columns the column names
  236. * @param array $rows the rows to be batch inserted into the table
  237. * @return string the batch INSERT SQL statement
  238. */
  239. public function batchInsert($table, $columns, $rows)
  240. {
  241. if (empty($rows)) {
  242. return '';
  243. }
  244. $schema = $this->db->getSchema();
  245. if (($tableSchema = $schema->getTableSchema($table)) !== null) {
  246. $columnSchemas = $tableSchema->columns;
  247. } else {
  248. $columnSchemas = [];
  249. }
  250. $values = [];
  251. foreach ($rows as $row) {
  252. $vs = [];
  253. foreach ($row as $i => $value) {
  254. if (isset($columns[$i], $columnSchemas[$columns[$i]]) && !is_array($value)) {
  255. $value = $columnSchemas[$columns[$i]]->dbTypecast($value);
  256. }
  257. if (is_string($value)) {
  258. $value = $schema->quoteValue($value);
  259. } elseif ($value === false) {
  260. $value = 0;
  261. } elseif ($value === null) {
  262. $value = 'NULL';
  263. }
  264. $vs[] = $value;
  265. }
  266. $values[] = '(' . implode(', ', $vs) . ')';
  267. }
  268. if (empty($values)) {
  269. return '';
  270. }
  271. foreach ($columns as $i => $name) {
  272. $columns[$i] = $schema->quoteColumnName($name);
  273. }
  274. return 'INSERT INTO ' . $schema->quoteTableName($table)
  275. . ' (' . implode(', ', $columns) . ') VALUES ' . implode(', ', $values);
  276. }
  277. /**
  278. * Creates an UPDATE SQL statement.
  279. * For example,
  280. *
  281. * ```php
  282. * $params = [];
  283. * $sql = $queryBuilder->update('user', ['status' => 1], 'age > 30', $params);
  284. * ```
  285. *
  286. * The method will properly escape the table and column names.
  287. *
  288. * @param string $table the table to be updated.
  289. * @param array $columns the column data (name => value) to be updated.
  290. * @param array|string $condition the condition that will be put in the WHERE part. Please
  291. * refer to [[Query::where()]] on how to specify condition.
  292. * @param array $params the binding parameters that will be modified by this method
  293. * so that they can be bound to the DB command later.
  294. * @return string the UPDATE SQL
  295. */
  296. public function update($table, $columns, $condition, &$params)
  297. {
  298. if (($tableSchema = $this->db->getTableSchema($table)) !== null) {
  299. $columnSchemas = $tableSchema->columns;
  300. } else {
  301. $columnSchemas = [];
  302. }
  303. $lines = [];
  304. foreach ($columns as $name => $value) {
  305. if ($value instanceof Expression) {
  306. $lines[] = $this->db->quoteColumnName($name) . '=' . $value->expression;
  307. foreach ($value->params as $n => $v) {
  308. $params[$n] = $v;
  309. }
  310. } else {
  311. $phName = self::PARAM_PREFIX . count($params);
  312. $lines[] = $this->db->quoteColumnName($name) . '=' . $phName;
  313. $params[$phName] = !is_array($value) && isset($columnSchemas[$name]) ? $columnSchemas[$name]->dbTypecast($value) : $value;
  314. }
  315. }
  316. $sql = 'UPDATE ' . $this->db->quoteTableName($table) . ' SET ' . implode(', ', $lines);
  317. $where = $this->buildWhere($condition, $params);
  318. return $where === '' ? $sql : $sql . ' ' . $where;
  319. }
  320. /**
  321. * Creates a DELETE SQL statement.
  322. * For example,
  323. *
  324. * ```php
  325. * $sql = $queryBuilder->delete('user', 'status = 0');
  326. * ```
  327. *
  328. * The method will properly escape the table and column names.
  329. *
  330. * @param string $table the table where the data will be deleted from.
  331. * @param array|string $condition the condition that will be put in the WHERE part. Please
  332. * refer to [[Query::where()]] on how to specify condition.
  333. * @param array $params the binding parameters that will be modified by this method
  334. * so that they can be bound to the DB command later.
  335. * @return string the DELETE SQL
  336. */
  337. public function delete($table, $condition, &$params)
  338. {
  339. $sql = 'DELETE FROM ' . $this->db->quoteTableName($table);
  340. $where = $this->buildWhere($condition, $params);
  341. return $where === '' ? $sql : $sql . ' ' . $where;
  342. }
  343. /**
  344. * Builds a SQL statement for creating a new DB table.
  345. *
  346. * The columns in the new table should be specified as name-definition pairs (e.g. 'name' => 'string'),
  347. * where name stands for a column name which will be properly quoted by the method, and definition
  348. * stands for the column type which can contain an abstract DB type.
  349. * The [[getColumnType()]] method will be invoked to convert any abstract type into a physical one.
  350. *
  351. * If a column is specified with definition only (e.g. 'PRIMARY KEY (name, type)'), it will be directly
  352. * inserted into the generated SQL.
  353. *
  354. * For example,
  355. *
  356. * ```php
  357. * $sql = $queryBuilder->createTable('user', [
  358. * 'id' => 'pk',
  359. * 'name' => 'string',
  360. * 'age' => 'integer',
  361. * ]);
  362. * ```
  363. *
  364. * @param string $table the name of the table to be created. The name will be properly quoted by the method.
  365. * @param array $columns the columns (name => definition) in the new table.
  366. * @param string $options additional SQL fragment that will be appended to the generated SQL.
  367. * @return string the SQL statement for creating a new DB table.
  368. */
  369. public function createTable($table, $columns, $options = null)
  370. {
  371. $cols = [];
  372. foreach ($columns as $name => $type) {
  373. if (is_string($name)) {
  374. $cols[] = "\t" . $this->db->quoteColumnName($name) . ' ' . $this->getColumnType($type);
  375. } else {
  376. $cols[] = "\t" . $type;
  377. }
  378. }
  379. $sql = 'CREATE TABLE ' . $this->db->quoteTableName($table) . " (\n" . implode(",\n", $cols) . "\n)";
  380. return $options === null ? $sql : $sql . ' ' . $options;
  381. }
  382. /**
  383. * Builds a SQL statement for renaming a DB table.
  384. * @param string $oldName the table to be renamed. The name will be properly quoted by the method.
  385. * @param string $newName the new table name. The name will be properly quoted by the method.
  386. * @return string the SQL statement for renaming a DB table.
  387. */
  388. public function renameTable($oldName, $newName)
  389. {
  390. return 'RENAME TABLE ' . $this->db->quoteTableName($oldName) . ' TO ' . $this->db->quoteTableName($newName);
  391. }
  392. /**
  393. * Builds a SQL statement for dropping a DB table.
  394. * @param string $table the table to be dropped. The name will be properly quoted by the method.
  395. * @return string the SQL statement for dropping a DB table.
  396. */
  397. public function dropTable($table)
  398. {
  399. return 'DROP TABLE ' . $this->db->quoteTableName($table);
  400. }
  401. /**
  402. * Builds a SQL statement for adding a primary key constraint to an existing table.
  403. * @param string $name the name of the primary key constraint.
  404. * @param string $table the table that the primary key constraint will be added to.
  405. * @param string|array $columns comma separated string or array of columns that the primary key will consist of.
  406. * @return string the SQL statement for adding a primary key constraint to an existing table.
  407. */
  408. public function addPrimaryKey($name, $table, $columns)
  409. {
  410. if (is_string($columns)) {
  411. $columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
  412. }
  413. foreach ($columns as $i => $col) {
  414. $columns[$i] = $this->db->quoteColumnName($col);
  415. }
  416. return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT '
  417. . $this->db->quoteColumnName($name) . ' PRIMARY KEY ('
  418. . implode(', ', $columns). ' )';
  419. }
  420. /**
  421. * Builds a SQL statement for removing a primary key constraint to an existing table.
  422. * @param string $name the name of the primary key constraint to be removed.
  423. * @param string $table the table that the primary key constraint will be removed from.
  424. * @return string the SQL statement for removing a primary key constraint from an existing table.
  425. */
  426. public function dropPrimaryKey($name, $table)
  427. {
  428. return 'ALTER TABLE ' . $this->db->quoteTableName($table)
  429. . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
  430. }
  431. /**
  432. * Builds a SQL statement for truncating a DB table.
  433. * @param string $table the table to be truncated. The name will be properly quoted by the method.
  434. * @return string the SQL statement for truncating a DB table.
  435. */
  436. public function truncateTable($table)
  437. {
  438. return 'TRUNCATE TABLE ' . $this->db->quoteTableName($table);
  439. }
  440. /**
  441. * Builds a SQL statement for adding a new DB column.
  442. * @param string $table the table that the new column will be added to. The table name will be properly quoted by the method.
  443. * @param string $column the name of the new column. The name will be properly quoted by the method.
  444. * @param string $type the column type. The [[getColumnType()]] method will be invoked to convert abstract column type (if any)
  445. * into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL.
  446. * For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'.
  447. * @return string the SQL statement for adding a new column.
  448. */
  449. public function addColumn($table, $column, $type)
  450. {
  451. return 'ALTER TABLE ' . $this->db->quoteTableName($table)
  452. . ' ADD ' . $this->db->quoteColumnName($column) . ' '
  453. . $this->getColumnType($type);
  454. }
  455. /**
  456. * Builds a SQL statement for dropping a DB column.
  457. * @param string $table the table whose column is to be dropped. The name will be properly quoted by the method.
  458. * @param string $column the name of the column to be dropped. The name will be properly quoted by the method.
  459. * @return string the SQL statement for dropping a DB column.
  460. */
  461. public function dropColumn($table, $column)
  462. {
  463. return 'ALTER TABLE ' . $this->db->quoteTableName($table)
  464. . ' DROP COLUMN ' . $this->db->quoteColumnName($column);
  465. }
  466. /**
  467. * Builds a SQL statement for renaming a column.
  468. * @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
  469. * @param string $oldName the old name of the column. The name will be properly quoted by the method.
  470. * @param string $newName the new name of the column. The name will be properly quoted by the method.
  471. * @return string the SQL statement for renaming a DB column.
  472. */
  473. public function renameColumn($table, $oldName, $newName)
  474. {
  475. return 'ALTER TABLE ' . $this->db->quoteTableName($table)
  476. . ' RENAME COLUMN ' . $this->db->quoteColumnName($oldName)
  477. . ' TO ' . $this->db->quoteColumnName($newName);
  478. }
  479. /**
  480. * Builds a SQL statement for changing the definition of a column.
  481. * @param string $table the table whose column is to be changed. The table name will be properly quoted by the method.
  482. * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
  483. * @param string $type the new column type. The [[getColumnType()]] method will be invoked to convert abstract
  484. * column type (if any) into the physical one. Anything that is not recognized as abstract type will be kept
  485. * in the generated SQL. For example, 'string' will be turned into 'varchar(255)', while 'string not null'
  486. * will become 'varchar(255) not null'.
  487. * @return string the SQL statement for changing the definition of a column.
  488. */
  489. public function alterColumn($table, $column, $type)
  490. {
  491. return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' CHANGE '
  492. . $this->db->quoteColumnName($column) . ' '
  493. . $this->db->quoteColumnName($column) . ' '
  494. . $this->getColumnType($type);
  495. }
  496. /**
  497. * Builds a SQL statement for adding a foreign key constraint to an existing table.
  498. * The method will properly quote the table and column names.
  499. * @param string $name the name of the foreign key constraint.
  500. * @param string $table the table that the foreign key constraint will be added to.
  501. * @param string|array $columns the name of the column to that the constraint will be added on.
  502. * If there are multiple columns, separate them with commas or use an array to represent them.
  503. * @param string $refTable the table that the foreign key references to.
  504. * @param string|array $refColumns the name of the column that the foreign key references to.
  505. * If there are multiple columns, separate them with commas or use an array to represent them.
  506. * @param string $delete the ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
  507. * @param string $update the ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
  508. * @return string the SQL statement for adding a foreign key constraint to an existing table.
  509. */
  510. public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
  511. {
  512. $sql = 'ALTER TABLE ' . $this->db->quoteTableName($table)
  513. . ' ADD CONSTRAINT ' . $this->db->quoteColumnName($name)
  514. . ' FOREIGN KEY (' . $this->buildColumns($columns) . ')'
  515. . ' REFERENCES ' . $this->db->quoteTableName($refTable)
  516. . ' (' . $this->buildColumns($refColumns) . ')';
  517. if ($delete !== null) {
  518. $sql .= ' ON DELETE ' . $delete;
  519. }
  520. if ($update !== null) {
  521. $sql .= ' ON UPDATE ' . $update;
  522. }
  523. return $sql;
  524. }
  525. /**
  526. * Builds a SQL statement for dropping a foreign key constraint.
  527. * @param string $name the name of the foreign key constraint to be dropped. The name will be properly quoted by the method.
  528. * @param string $table the table whose foreign is to be dropped. The name will be properly quoted by the method.
  529. * @return string the SQL statement for dropping a foreign key constraint.
  530. */
  531. public function dropForeignKey($name, $table)
  532. {
  533. return 'ALTER TABLE ' . $this->db->quoteTableName($table)
  534. . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
  535. }
  536. /**
  537. * Builds a SQL statement for creating a new index.
  538. * @param string $name the name of the index. The name will be properly quoted by the method.
  539. * @param string $table the table that the new index will be created for. The table name will be properly quoted by the method.
  540. * @param string|array $columns the column(s) that should be included in the index. If there are multiple columns,
  541. * separate them with commas or use an array to represent them. Each column name will be properly quoted
  542. * by the method, unless a parenthesis is found in the name.
  543. * @param bool $unique whether to add UNIQUE constraint on the created index.
  544. * @return string the SQL statement for creating a new index.
  545. */
  546. public function createIndex($name, $table, $columns, $unique = false)
  547. {
  548. return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ')
  549. . $this->db->quoteTableName($name) . ' ON '
  550. . $this->db->quoteTableName($table)
  551. . ' (' . $this->buildColumns($columns) . ')';
  552. }
  553. /**
  554. * Builds a SQL statement for dropping an index.
  555. * @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
  556. * @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
  557. * @return string the SQL statement for dropping an index.
  558. */
  559. public function dropIndex($name, $table)
  560. {
  561. return 'DROP INDEX ' . $this->db->quoteTableName($name) . ' ON ' . $this->db->quoteTableName($table);
  562. }
  563. /**
  564. * Creates a SQL statement for resetting the sequence value of a table's primary key.
  565. * The sequence will be reset such that the primary key of the next new row inserted
  566. * will have the specified value or 1.
  567. * @param string $table the name of the table whose primary key sequence will be reset
  568. * @param array|string $value the value for the primary key of the next new row inserted. If this is not set,
  569. * the next new row's primary key will have a value 1.
  570. * @return string the SQL statement for resetting sequence
  571. * @throws NotSupportedException if this is not supported by the underlying DBMS
  572. */
  573. public function resetSequence($table, $value = null)
  574. {
  575. throw new NotSupportedException($this->db->getDriverName() . ' does not support resetting sequence.');
  576. }
  577. /**
  578. * Builds a SQL statement for enabling or disabling integrity check.
  579. * @param bool $check whether to turn on or off the integrity check.
  580. * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
  581. * @param string $table the table name. Defaults to empty string, meaning that no table will be changed.
  582. * @return string the SQL statement for checking integrity
  583. * @throws NotSupportedException if this is not supported by the underlying DBMS
  584. */
  585. public function checkIntegrity($check = true, $schema = '', $table = '')
  586. {
  587. throw new NotSupportedException($this->db->getDriverName() . ' does not support enabling/disabling integrity check.');
  588. }
  589. /**
  590. * Builds a SQL command for adding comment to column
  591. *
  592. * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
  593. * @param string $column the name of the column to be commented. The column name will be properly quoted by the method.
  594. * @param string $comment the text of the comment to be added. The comment will be properly quoted by the method.
  595. * @return string the SQL statement for adding comment on column
  596. * @since 2.0.8
  597. */
  598. public function addCommentOnColumn($table, $column, $comment)
  599. {
  600. return 'COMMENT ON COLUMN ' . $this->db->quoteTableName($table) . '.' . $this->db->quoteColumnName($column) . ' IS ' . $this->db->quoteValue($comment);
  601. }
  602. /**
  603. * Builds a SQL command for adding comment to table
  604. *
  605. * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
  606. * @param string $comment the text of the comment to be added. The comment will be properly quoted by the method.
  607. * @return string the SQL statement for adding comment on table
  608. * @since 2.0.8
  609. */
  610. public function addCommentOnTable($table, $comment)
  611. {
  612. return 'COMMENT ON TABLE ' . $this->db->quoteTableName($table) . ' IS ' . $this->db->quoteValue($comment);
  613. }
  614. /**
  615. * Builds a SQL command for adding comment to column
  616. *
  617. * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
  618. * @param string $column the name of the column to be commented. The column name will be properly quoted by the method.
  619. * @return string the SQL statement for adding comment on column
  620. * @since 2.0.8
  621. */
  622. public function dropCommentFromColumn($table, $column)
  623. {
  624. return 'COMMENT ON COLUMN ' . $this->db->quoteTableName($table) . '.' . $this->db->quoteColumnName($column) . ' IS NULL';
  625. }
  626. /**
  627. * Builds a SQL command for adding comment to table
  628. *
  629. * @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
  630. * @return string the SQL statement for adding comment on column
  631. * @since 2.0.8
  632. */
  633. public function dropCommentFromTable($table)
  634. {
  635. return 'COMMENT ON TABLE ' . $this->db->quoteTableName($table) . ' IS NULL';
  636. }
  637. /**
  638. * Converts an abstract column type into a physical column type.
  639. * The conversion is done using the type map specified in [[typeMap]].
  640. * The following abstract column types are supported (using MySQL as an example to explain the corresponding
  641. * physical types):
  642. *
  643. * - `pk`: an auto-incremental primary key type, will be converted into "int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY"
  644. * - `bigpk`: an auto-incremental primary key type, will be converted into "bigint(20) NOT NULL AUTO_INCREMENT PRIMARY KEY"
  645. * - `unsignedpk`: an unsigned auto-incremental primary key type, will be converted into "int(11) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY"
  646. * - `char`: char type, will be converted into "char(1)"
  647. * - `string`: string type, will be converted into "varchar(255)"
  648. * - `text`: a long string type, will be converted into "text"
  649. * - `smallint`: a small integer type, will be converted into "smallint(6)"
  650. * - `integer`: integer type, will be converted into "int(11)"
  651. * - `bigint`: a big integer type, will be converted into "bigint(20)"
  652. * - `boolean`: boolean type, will be converted into "tinyint(1)"
  653. * - `float``: float number type, will be converted into "float"
  654. * - `decimal`: decimal number type, will be converted into "decimal"
  655. * - `datetime`: datetime type, will be converted into "datetime"
  656. * - `timestamp`: timestamp type, will be converted into "timestamp"
  657. * - `time`: time type, will be converted into "time"
  658. * - `date`: date type, will be converted into "date"
  659. * - `money`: money type, will be converted into "decimal(19,4)"
  660. * - `binary`: binary data type, will be converted into "blob"
  661. *
  662. * If the abstract type contains two or more parts separated by spaces (e.g. "string NOT NULL"), then only
  663. * the first part will be converted, and the rest of the parts will be appended to the converted result.
  664. * For example, 'string NOT NULL' is converted to 'varchar(255) NOT NULL'.
  665. *
  666. * For some of the abstract types you can also specify a length or precision constraint
  667. * by appending it in round brackets directly to the type.
  668. * For example `string(32)` will be converted into "varchar(32)" on a MySQL database.
  669. * If the underlying DBMS does not support these kind of constraints for a type it will
  670. * be ignored.
  671. *
  672. * If a type cannot be found in [[typeMap]], it will be returned without any change.
  673. * @param string|ColumnSchemaBuilder $type abstract column type
  674. * @return string physical column type.
  675. */
  676. public function getColumnType($type)
  677. {
  678. if ($type instanceof ColumnSchemaBuilder) {
  679. $type = $type->__toString();
  680. }
  681. if (isset($this->typeMap[$type])) {
  682. return $this->typeMap[$type];
  683. } elseif (preg_match('/^(\w+)\((.+?)\)(.*)$/', $type, $matches)) {
  684. if (isset($this->typeMap[$matches[1]])) {
  685. return preg_replace('/\(.+\)/', '(' . $matches[2] . ')', $this->typeMap[$matches[1]]) . $matches[3];
  686. }
  687. } elseif (preg_match('/^(\w+)\s+/', $type, $matches)) {
  688. if (isset($this->typeMap[$matches[1]])) {
  689. return preg_replace('/^\w+/', $this->typeMap[$matches[1]], $type);
  690. }
  691. }
  692. return $type;
  693. }
  694. /**
  695. * @param array $columns
  696. * @param array $params the binding parameters to be populated
  697. * @param bool $distinct
  698. * @param string $selectOption
  699. * @return string the SELECT clause built from [[Query::$select]].
  700. */
  701. public function buildSelect($columns, &$params, $distinct = false, $selectOption = null)
  702. {
  703. $select = $distinct ? 'SELECT DISTINCT' : 'SELECT';
  704. if ($selectOption !== null) {
  705. $select .= ' ' . $selectOption;
  706. }
  707. if (empty($columns)) {
  708. return $select . ' *';
  709. }
  710. foreach ($columns as $i => $column) {
  711. if ($column instanceof Expression) {
  712. if (is_int($i)) {
  713. $columns[$i] = $column->expression;
  714. } else {
  715. $columns[$i] = $column->expression . ' AS ' . $this->db->quoteColumnName($i);
  716. }
  717. $params = array_merge($params, $column->params);
  718. } elseif ($column instanceof Query) {
  719. list($sql, $params) = $this->build($column, $params);
  720. $columns[$i] = "($sql) AS " . $this->db->quoteColumnName($i);
  721. } elseif (is_string($i)) {
  722. if (strpos($column, '(') === false) {
  723. $column = $this->db->quoteColumnName($column);
  724. }
  725. $columns[$i] = "$column AS " . $this->db->quoteColumnName($i);
  726. } elseif (strpos($column, '(') === false) {
  727. if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_\.]+)$/', $column, $matches)) {
  728. $columns[$i] = $this->db->quoteColumnName($matches[1]) . ' AS ' . $this->db->quoteColumnName($matches[2]);
  729. } else {
  730. $columns[$i] = $this->db->quoteColumnName($column);
  731. }
  732. }
  733. }
  734. return $select . ' ' . implode(', ', $columns);
  735. }
  736. /**
  737. * @param array $tables
  738. * @param array $params the binding parameters to be populated
  739. * @return string the FROM clause built from [[Query::$from]].
  740. */
  741. public function buildFrom($tables, &$params)
  742. {
  743. if (empty($tables)) {
  744. return '';
  745. }
  746. $tables = $this->quoteTableNames($tables, $params);
  747. return 'FROM ' . implode(', ', $tables);
  748. }
  749. /**
  750. * @param array $joins
  751. * @param array $params the binding parameters to be populated
  752. * @return string the JOIN clause built from [[Query::$join]].
  753. * @throws Exception if the $joins parameter is not in proper format
  754. */
  755. public function buildJoin($joins, &$params)
  756. {
  757. if (empty($joins)) {
  758. return '';
  759. }
  760. foreach ($joins as $i => $join) {
  761. if (!is_array($join) || !isset($join[0], $join[1])) {
  762. throw new Exception('A join clause must be specified as an array of join type, join table, and optionally join condition.');
  763. }
  764. // 0:join type, 1:join table, 2:on-condition (optional)
  765. list ($joinType, $table) = $join;
  766. $tables = $this->quoteTableNames((array) $table, $params);
  767. $table = reset($tables);
  768. $joins[$i] = "$joinType $table";
  769. if (isset($join[2])) {
  770. $condition = $this->buildCondition($join[2], $params);
  771. if ($condition !== '') {
  772. $joins[$i] .= ' ON ' . $condition;
  773. }
  774. }
  775. }
  776. return implode($this->separator, $joins);
  777. }
  778. /**
  779. * Quotes table names passed
  780. *
  781. * @param array $tables
  782. * @param array $params
  783. * @return array
  784. */
  785. private function quoteTableNames($tables, &$params)
  786. {
  787. foreach ($tables as $i => $table) {
  788. if ($table instanceof Query) {
  789. list($sql, $params) = $this->build($table, $params);
  790. $tables[$i] = "($sql) " . $this->db->quoteTableName($i);
  791. } elseif (is_string($i)) {
  792. if (strpos($table, '(') === false) {
  793. $table = $this->db->quoteTableName($table);
  794. }
  795. $tables[$i] = "$table " . $this->db->quoteTableName($i);
  796. } elseif (strpos($table, '(') === false) {
  797. if (preg_match('/^(.*?)(?i:\s+as|)\s+([^ ]+)$/', $table, $matches)) { // with alias
  798. $tables[$i] = $this->db->quoteTableName($matches[1]) . ' ' . $this->db->quoteTableName($matches[2]);
  799. } else {
  800. $tables[$i] = $this->db->quoteTableName($table);
  801. }
  802. }
  803. }
  804. return $tables;
  805. }
  806. /**
  807. * @param string|array $condition
  808. * @param array $params the binding parameters to be populated
  809. * @return string the WHERE clause built from [[Query::$where]].
  810. */
  811. public function buildWhere($condition, &$params)
  812. {
  813. $where = $this->buildCondition($condition, $params);
  814. return $where === '' ? '' : 'WHERE ' . $where;
  815. }
  816. /**
  817. * @param array $columns
  818. * @return string the GROUP BY clause
  819. */
  820. public function buildGroupBy($columns)
  821. {
  822. if (empty($columns)) {
  823. return '';
  824. }
  825. foreach ($columns as $i => $column) {
  826. if ($column instanceof Expression) {
  827. $columns[$i] = $column->expression;
  828. } elseif (strpos($column, '(') === false) {
  829. $columns[$i] = $this->db->quoteColumnName($column);
  830. }
  831. }
  832. return 'GROUP BY ' . implode(', ', $columns);
  833. }
  834. /**
  835. * @param string|array $condition
  836. * @param array $params the binding parameters to be populated
  837. * @return string the HAVING clause built from [[Query::$having]].
  838. */
  839. public function buildHaving($condition, &$params)
  840. {
  841. $having = $this->buildCondition($condition, $params);
  842. return $having === '' ? '' : 'HAVING ' . $having;
  843. }
  844. /**
  845. * Builds the ORDER BY and LIMIT/OFFSET clauses and appends them to the given SQL.
  846. * @param string $sql the existing SQL (without ORDER BY/LIMIT/OFFSET)
  847. * @param array $orderBy the order by columns. See [[Query::orderBy]] for more details on how to specify this parameter.
  848. * @param int $limit the limit number. See [[Query::limit]] for more details.
  849. * @param int $offset the offset number. See [[Query::offset]] for more details.
  850. * @return string the SQL completed with ORDER BY/LIMIT/OFFSET (if any)
  851. */
  852. public function buildOrderByAndLimit($sql, $orderBy, $limit, $offset)
  853. {
  854. $orderBy = $this->buildOrderBy($orderBy);
  855. if ($orderBy !== '') {
  856. $sql .= $this->separator . $orderBy;
  857. }
  858. $limit = $this->buildLimit($limit, $offset);
  859. if ($limit !== '') {
  860. $sql .= $this->separator . $limit;
  861. }
  862. return $sql;
  863. }
  864. /**
  865. * @param array $columns
  866. * @return string the ORDER BY clause built from [[Query::$orderBy]].
  867. */
  868. public function buildOrderBy($columns)
  869. {
  870. if (empty($columns)) {
  871. return '';
  872. }
  873. $orders = [];
  874. foreach ($columns as $name => $direction) {
  875. if ($direction instanceof Expression) {
  876. $orders[] = $direction->expression;
  877. } else {
  878. $orders[] = $this->db->quoteColumnName($name) . ($direction === SORT_DESC ? ' DESC' : '');
  879. }
  880. }
  881. return 'ORDER BY ' . implode(', ', $orders);
  882. }
  883. /**
  884. * @param int $limit
  885. * @param int $offset
  886. * @return string the LIMIT and OFFSET clauses
  887. */
  888. public function buildLimit($limit, $offset)
  889. {
  890. $sql = '';
  891. if ($this->hasLimit($limit)) {
  892. $sql = 'LIMIT ' . $limit;
  893. }
  894. if ($this->hasOffset($offset)) {
  895. $sql .= ' OFFSET ' . $offset;
  896. }
  897. return ltrim($sql);
  898. }
  899. /**
  900. * Checks to see if the given limit is effective.
  901. * @param mixed $limit the given limit
  902. * @return bool whether the limit is effective
  903. */
  904. protected function hasLimit($limit)
  905. {
  906. return ($limit instanceof Expression) || ctype_digit((string) $limit);
  907. }
  908. /**
  909. * Checks to see if the given offset is effective.
  910. * @param mixed $offset the given offset
  911. * @return bool whether the offset is effective
  912. */
  913. protected function hasOffset($offset)
  914. {
  915. return ($offset instanceof Expression) || ctype_digit((string) $offset) && (string) $offset !== '0';
  916. }
  917. /**
  918. * @param array $unions
  919. * @param array $params the binding parameters to be populated
  920. * @return string the UNION clause built from [[Query::$union]].
  921. */
  922. public function buildUnion($unions, &$params)
  923. {
  924. if (empty($unions)) {
  925. return '';
  926. }
  927. $result = '';
  928. foreach ($unions as $i => $union) {
  929. $query = $union['query'];
  930. if ($query instanceof Query) {
  931. list($unions[$i]['query'], $params) = $this->build($query, $params);
  932. }
  933. $result .= 'UNION ' . ($union['all'] ? 'ALL ' : '') . '( ' . $unions[$i]['query'] . ' ) ';
  934. }
  935. return trim($result);
  936. }
  937. /**
  938. * Processes columns and properly quotes them if necessary.
  939. * It will join all columns into a string with comma as separators.
  940. * @param string|array $columns the columns to be processed
  941. * @return string the processing result
  942. */
  943. public function buildColumns($columns)
  944. {
  945. if (!is_array($columns)) {
  946. if (strpos($columns, '(') !== false) {
  947. return $columns;
  948. } else {
  949. $columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
  950. }
  951. }
  952. foreach ($columns as $i => $column) {
  953. if ($column instanceof Expression) {
  954. $columns[$i] = $column->expression;
  955. } elseif (strpos($column, '(') === false) {
  956. $columns[$i] = $this->db->quoteColumnName($column);
  957. }
  958. }
  959. return is_array($columns) ? implode(', ', $columns) : $columns;
  960. }
  961. /**
  962. * Parses the condition specification and generates the corresponding SQL expression.
  963. * @param string|array|Expression $condition the condition specification. Please refer to [[Query::where()]]
  964. * on how to specify a condition.
  965. * @param array $params the binding parameters to be populated
  966. * @return string the generated SQL expression
  967. */
  968. public function buildCondition($condition, &$params)
  969. {
  970. if ($condition instanceof Expression) {
  971. foreach ($condition->params as $n => $v) {
  972. $params[$n] = $v;
  973. }
  974. return $condition->expression;
  975. } elseif (!is_array($condition)) {
  976. return (string) $condition;
  977. } elseif (empty($condition)) {
  978. return '';
  979. }
  980. if (isset($condition[0])) { // operator format: operator, operand 1, operand 2, ...
  981. $operator = strtoupper($condition[0]);
  982. if (isset($this->conditionBuilders[$operator])) {
  983. $method = $this->conditionBuilders[$operator];
  984. } else {
  985. $method = 'buildSimpleCondition';
  986. }
  987. array_shift($condition);
  988. return $this->$method($operator, $condition, $params);
  989. } else { // hash format: 'column1' => 'value1', 'column2' => 'value2', ...
  990. return $this->buildHashCondition($condition, $params);
  991. }
  992. }
  993. /**
  994. * Creates a condition based on column-value pairs.
  995. * @param array $condition the condition specification.
  996. * @param array $params the binding parameters to be populated
  997. * @return string the generated SQL expression
  998. */
  999. public function buildHashCondition($condition, &$params)
  1000. {
  1001. $parts = [];
  1002. foreach ($condition as $column => $value) {
  1003. if (ArrayHelper::isTraversable($value) || $value instanceof Query) {
  1004. // IN condition
  1005. $parts[] = $this->buildInCondition('IN', [$column, $value], $params);
  1006. } else {
  1007. if (strpos($column, '(') === false) {
  1008. $column = $this->db->quoteColumnName($column);
  1009. }
  1010. if ($value === null) {
  1011. $parts[] = "$column IS NULL";
  1012. } elseif ($value instanceof Expression) {
  1013. $parts[] = "$column=" . $value->expression;
  1014. foreach ($value->params as $n => $v) {
  1015. $params[$n] = $v;
  1016. }
  1017. } else {
  1018. $phName = self::PARAM_PREFIX . count($params);
  1019. $parts[] = "$column=$phName";
  1020. $params[$phName] = $value;
  1021. }
  1022. }
  1023. }
  1024. return count($parts) === 1 ? $parts[0] : '(' . implode(') AND (', $parts) . ')';
  1025. }
  1026. /**
  1027. * Connects two or more SQL expressions with the `AND` or `OR` operator.
  1028. * @param string $operator the operator to use for connecting the given operands
  1029. * @param array $operands the SQL expressions to connect.
  1030. * @param array $params the binding parameters to be populated
  1031. * @return string the generated SQL expression
  1032. */
  1033. public function buildAndCondition($operator, $operands, &$params)
  1034. {
  1035. $parts = [];
  1036. foreach ($operands as $operand) {
  1037. if (is_array($operand)) {
  1038. $operand = $this->buildCondition($operand, $params);
  1039. }
  1040. if ($operand instanceof Expression) {
  1041. foreach ($operand->params as $n => $v) {
  1042. $params[$n] = $v;
  1043. }
  1044. $operand = $operand->expression;
  1045. }
  1046. if ($operand !== '') {
  1047. $parts[] = $operand;
  1048. }
  1049. }
  1050. if (!empty($parts)) {
  1051. return '(' . implode(") $operator (", $parts) . ')';
  1052. } else {
  1053. return '';
  1054. }
  1055. }
  1056. /**
  1057. * Inverts an SQL expressions with `NOT` operator.
  1058. * @param string $operator the operator to use for connecting the given operands
  1059. * @param array $operands the SQL expressions to connect.
  1060. * @param array $params the binding parameters to be populated
  1061. * @return string the generated SQL expression
  1062. * @throws InvalidParamException if wrong number of operands have been given.
  1063. */
  1064. public function buildNotCondition($operator, $operands, &$params)
  1065. {
  1066. if (count($operands) !== 1) {
  1067. throw new InvalidParamException("Operator '$operator' requires exactly one operand.");
  1068. }
  1069. $operand = reset($operands);
  1070. if (is_array($operand)) {
  1071. $operand = $this->buildCondition($operand, $params);
  1072. }
  1073. if ($operand === '') {
  1074. return '';
  1075. }
  1076. return "$operator ($operand)";
  1077. }
  1078. /**
  1079. * Creates an SQL expressions with the `BETWEEN` operator.
  1080. * @param string $operator the operator to use (e.g. `BETWEEN` or `NOT BETWEEN`)
  1081. * @param array $operands the first operand is the column name. The second and third operands
  1082. * describe the interval that column value should be in.
  1083. * @param array $params the binding parameters to be populated
  1084. * @return string the generated SQL expression
  1085. * @throws InvalidParamException if wrong number of operands have been given.
  1086. */
  1087. public function buildBetweenCondition($operator, $operands, &$params)
  1088. {
  1089. if (!isset($operands[0], $operands[1], $operands[2])) {
  1090. throw new InvalidParamException("Operator '$operator' requires three operands.");
  1091. }
  1092. list($column, $value1, $value2) = $operands;
  1093. if (strpos($column, '(') === false) {
  1094. $column = $this->db->quoteColumnName($column);
  1095. }
  1096. if ($value1 instanceof Expression) {
  1097. foreach ($value1->params as $n => $v) {
  1098. $params[$n] = $v;
  1099. }
  1100. $phName1 = $value1->expression;
  1101. } else {
  1102. $phName1 = self::PARAM_PREFIX . count($params);
  1103. $params[$phName1] = $value1;
  1104. }
  1105. if ($value2 instanceof Expression) {
  1106. foreach ($value2->params as $n => $v) {
  1107. $params[$n] = $v;
  1108. }
  1109. $phName2 = $value2->expression;
  1110. } else {
  1111. $phName2 = self::PARAM_PREFIX . count($params);
  1112. $params[$phName2] = $value2;
  1113. }
  1114. return "$column $operator $phName1 AND $phName2";
  1115. }
  1116. /**
  1117. * Creates an SQL expressions with the `IN` operator.
  1118. * @param string $operator the operator to use (e.g. `IN` or `NOT IN`)
  1119. * @param array $operands the first operand is the column name. If it is an array
  1120. * a composite IN condition will be generated.
  1121. * The second operand is an array of values that column value should be among.
  1122. * If it is an empty array the generated expression will be a `false` value if
  1123. * operator is `IN` and empty if operator is `NOT IN`.
  1124. * @param array $params the binding parameters to be populated
  1125. * @return string the generated SQL expression
  1126. * @throws Exception if wrong number of operands have been given.
  1127. */
  1128. public function buildInCondition($operator, $operands, &$params)
  1129. {
  1130. if (!isset($operands[0], $operands[1])) {
  1131. throw new Exception("Operator '$operator' requires two operands.");
  1132. }
  1133. list($column, $values) = $operands;
  1134. if ($column === []) {
  1135. // no columns to test against
  1136. return $operator === 'IN' ? '0=1' : '';
  1137. }
  1138. if ($values instanceof Query) {
  1139. return $this->buildSubqueryInCondition($operator, $column, $values, $params);
  1140. }
  1141. if (!is_array($values) && !$values instanceof \Traversable) {
  1142. // ensure values is an array
  1143. $values = (array) $values;
  1144. }
  1145. if ($column instanceof \Traversable || count($column) > 1) {
  1146. return $this->buildCompositeInCondition($operator, $column, $values, $params);
  1147. } elseif (is_array($column)) {
  1148. $column = reset($column);
  1149. }
  1150. $sqlValues = [];
  1151. foreach ($values as $i => $value) {
  1152. if (is_array($value) || $value instanceof \ArrayAccess) {
  1153. $value = isset($value[$column]) ? $value[$column] : null;
  1154. }
  1155. if ($value === null) {
  1156. $sqlValues[$i] = 'NULL';
  1157. } elseif ($value instanceof Expression) {
  1158. $sqlValues[$i] = $value->expression;
  1159. foreach ($value->params as $n => $v) {
  1160. $params[$n] = $v;
  1161. }
  1162. } else {
  1163. $phName = self::PARAM_PREFIX . count($params);
  1164. $params[$phName] = $value;
  1165. $sqlValues[$i] = $phName;
  1166. }
  1167. }
  1168. if (empty($sqlValues)) {
  1169. return $operator === 'IN' ? '0=1' : '';
  1170. }
  1171. if (strpos($column, '(') === false) {
  1172. $column = $this->db->quoteColumnName($column);
  1173. }
  1174. if (count($sqlValues) > 1) {
  1175. return "$column $operator (" . implode(', ', $sqlValues) . ')';
  1176. } else {
  1177. $operator = $operator === 'IN' ? '=' : '<>';
  1178. return $column . $operator . reset($sqlValues);
  1179. }
  1180. }
  1181. /**
  1182. * Builds SQL for IN condition
  1183. *
  1184. * @param string $operator
  1185. * @param array $columns
  1186. * @param Query $values
  1187. * @param array $params
  1188. * @return string SQL
  1189. */
  1190. protected function buildSubqueryInCondition($operator, $columns, $values, &$params)
  1191. {
  1192. list($sql, $params) = $this->build($values, $params);
  1193. if (is_array($columns)) {
  1194. foreach ($columns as $i => $col) {
  1195. if (strpos($col, '(') === false) {
  1196. $columns[$i] = $this->db->quoteColumnName($col);
  1197. }
  1198. }
  1199. return '(' . implode(', ', $columns) . ") $operator ($sql)";
  1200. } else {
  1201. if (strpos($columns, '(') === false) {
  1202. $columns = $this->db->quoteColumnName($columns);
  1203. }
  1204. return "$columns $operator ($sql)";
  1205. }
  1206. }
  1207. /**
  1208. * Builds SQL for IN condition
  1209. *
  1210. * @param string $operator
  1211. * @param array|\Traversable $columns
  1212. * @param array $values
  1213. * @param array $params
  1214. * @return string SQL
  1215. */
  1216. protected function buildCompositeInCondition($operator, $columns, $values, &$params)
  1217. {
  1218. $vss = [];
  1219. foreach ($values as $value) {
  1220. $vs = [];
  1221. foreach ($columns as $column) {
  1222. if (isset($value[$column])) {
  1223. $phName = self::PARAM_PREFIX . count($params);
  1224. $params[$phName] = $value[$column];
  1225. $vs[] = $phName;
  1226. } else {
  1227. $vs[] = 'NULL';
  1228. }
  1229. }
  1230. $vss[] = '(' . implode(', ', $vs) . ')';
  1231. }
  1232. if (empty($vss)) {
  1233. return $operator === 'IN' ? '0=1' : '';
  1234. }
  1235. $sqlColumns = [];
  1236. foreach ($columns as $i => $column) {
  1237. $sqlColumns[] = strpos($column, '(') === false ? $this->db->quoteColumnName($column) : $column;
  1238. }
  1239. return '(' . implode(', ', $sqlColumns) . ") $operator (" . implode(', ', $vss) . ')';
  1240. }
  1241. /**
  1242. * Creates an SQL expressions with the `LIKE` operator.
  1243. * @param string $operator the operator to use (e.g. `LIKE`, `NOT LIKE`, `OR LIKE` or `OR NOT LIKE`)
  1244. * @param array $operands an array of two or three operands
  1245. *
  1246. * - The first operand is the column name.
  1247. * - The second operand is a single value or an array of values that column value
  1248. * should be compared with. If it is an empty array the generated expression will
  1249. * be a `false` value if operator is `LIKE` or `OR LIKE`, and empty if operator
  1250. * is `NOT LIKE` or `OR NOT LIKE`.
  1251. * - An optional third operand can also be provided to specify how to escape special characters
  1252. * in the value(s). The operand should be an array of mappings from the special characters to their
  1253. * escaped counterparts. If this operand is not provided, a default escape mapping will be used.
  1254. * You may use `false` or an empty array to indicate the values are already escaped and no escape
  1255. * should be applied. Note that when using an escape mapping (or the third operand is not provided),
  1256. * the values will be automatically enclosed within a pair of percentage characters.
  1257. * @param array $params the binding parameters to be populated
  1258. * @return string the generated SQL expression
  1259. * @throws InvalidParamException if wrong number of operands have been given.
  1260. */
  1261. public function buildLikeCondition($operator, $operands, &$params)
  1262. {
  1263. if (!isset($operands[0], $operands[1])) {
  1264. throw new InvalidParamException("Operator '$operator' requires two operands.");
  1265. }
  1266. $escape = isset($operands[2]) ? $operands[2] : $this->likeEscapingReplacements;
  1267. unset($operands[2]);
  1268. if (!preg_match('/^(AND |OR |)(((NOT |))I?LIKE)/', $operator, $matches)) {
  1269. throw new InvalidParamException("Invalid operator '$operator'.");
  1270. }
  1271. $andor = ' ' . (!empty($matches[1]) ? $matches[1] : 'AND ');
  1272. $not = !empty($matches[3]);
  1273. $operator = $matches[2];
  1274. list($column, $values) = $operands;
  1275. if (!is_array($values)) {
  1276. $values = [$values];
  1277. }
  1278. if (empty($values)) {
  1279. return $not ? '' : '0=1';
  1280. }
  1281. if (strpos($column, '(') === false) {
  1282. $column = $this->db->quoteColumnName($column);
  1283. }
  1284. $parts = [];
  1285. foreach ($values as $value) {
  1286. if ($value instanceof Expression) {
  1287. foreach ($value->params as $n => $v) {
  1288. $params[$n] = $v;
  1289. }
  1290. $phName = $value->expression;
  1291. } else {
  1292. $phName = self::PARAM_PREFIX . count($params);
  1293. $params[$phName] = empty($escape) ? $value : ('%' . strtr($value, $escape) . '%');
  1294. }
  1295. $escapeSql = '';
  1296. if ($this->likeEscapeCharacter !== null) {
  1297. $escapeSql = " ESCAPE '{$this->likeEscapeCharacter}'";
  1298. }
  1299. $parts[] = "{$column} {$operator} {$phName}{$escapeSql}";
  1300. }
  1301. return implode($andor, $parts);
  1302. }
  1303. /**
  1304. * Creates an SQL expressions with the `EXISTS` operator.
  1305. * @param string $operator the operator to use (e.g. `EXISTS` or `NOT EXISTS`)
  1306. * @param array $operands contains only one element which is a [[Query]] object representing the sub-query.
  1307. * @param array $params the binding parameters to be populated
  1308. * @return string the generated SQL expression
  1309. * @throws InvalidParamException if the operand is not a [[Query]] object.
  1310. */
  1311. public function buildExistsCondition($operator, $operands, &$params)
  1312. {
  1313. if ($operands[0] instanceof Query) {
  1314. list($sql, $params) = $this->build($operands[0], $params);
  1315. return "$operator ($sql)";
  1316. } else {
  1317. throw new InvalidParamException('Subquery for EXISTS operator must be a Query object.');
  1318. }
  1319. }
  1320. /**
  1321. * Creates an SQL expressions like `"column" operator value`.
  1322. * @param string $operator the operator to use. Anything could be used e.g. `>`, `<=`, etc.
  1323. * @param array $operands contains two column names.
  1324. * @param array $params the binding parameters to be populated
  1325. * @return string the generated SQL expression
  1326. * @throws InvalidParamException if wrong number of operands have been given.
  1327. */
  1328. public function buildSimpleCondition($operator, $operands, &$params)
  1329. {
  1330. if (count($operands) !== 2) {
  1331. throw new InvalidParamException("Operator '$operator' requires two operands.");
  1332. }
  1333. list($column, $value) = $operands;
  1334. if (strpos($column, '(') === false) {
  1335. $column = $this->db->quoteColumnName($column);
  1336. }
  1337. if ($value === null) {
  1338. return "$column $operator NULL";
  1339. } elseif ($value instanceof Expression) {
  1340. foreach ($value->params as $n => $v) {
  1341. $params[$n] = $v;
  1342. }
  1343. return "$column $operator {$value->expression}";
  1344. } elseif ($value instanceof Query) {
  1345. list($sql, $params) = $this->build($value, $params);
  1346. return "$column $operator ($sql)";
  1347. } else {
  1348. $phName = self::PARAM_PREFIX . count($params);
  1349. $params[$phName] = $value;
  1350. return "$column $operator $phName";
  1351. }
  1352. }
  1353. /**
  1354. * Creates a SELECT EXISTS() SQL statement.
  1355. * @param string $rawSql the subquery in a raw form to select from.
  1356. * @return string the SELECT EXISTS() SQL statement.
  1357. * @since 2.0.8
  1358. */
  1359. public function selectExists($rawSql)
  1360. {
  1361. return 'SELECT EXISTS(' . $rawSql . ')';
  1362. }
  1363. }