123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752 |
- <?php
- namespace yii\db;
- use yii\base\InvalidArgumentException;
- use yii\base\NotSupportedException;
- use yii\db\conditions\ConditionInterface;
- use yii\db\conditions\HashCondition;
- use yii\helpers\StringHelper;
- class QueryBuilder extends \yii\base\BaseObject
- {
-
- const PARAM_PREFIX = ':qp';
-
- public $db;
-
- public $separator = ' ';
-
- public $typeMap = [];
-
- protected $conditionBuilders = [];
-
- protected $conditionClasses = [];
-
- protected $expressionBuilders = [];
-
- public function __construct($connection, $config = [])
- {
- $this->db = $connection;
- parent::__construct($config);
- }
-
- public function init()
- {
- parent::init();
- $this->expressionBuilders = array_merge($this->defaultExpressionBuilders(), $this->expressionBuilders);
- $this->conditionClasses = array_merge($this->defaultConditionClasses(), $this->conditionClasses);
- }
-
- protected function defaultConditionClasses()
- {
- return [
- 'NOT' => 'yii\db\conditions\NotCondition',
- 'AND' => 'yii\db\conditions\AndCondition',
- 'OR' => 'yii\db\conditions\OrCondition',
- 'BETWEEN' => 'yii\db\conditions\BetweenCondition',
- 'NOT BETWEEN' => 'yii\db\conditions\BetweenCondition',
- 'IN' => 'yii\db\conditions\InCondition',
- 'NOT IN' => 'yii\db\conditions\InCondition',
- 'LIKE' => 'yii\db\conditions\LikeCondition',
- 'NOT LIKE' => 'yii\db\conditions\LikeCondition',
- 'OR LIKE' => 'yii\db\conditions\LikeCondition',
- 'OR NOT LIKE' => 'yii\db\conditions\LikeCondition',
- 'EXISTS' => 'yii\db\conditions\ExistsCondition',
- 'NOT EXISTS' => 'yii\db\conditions\ExistsCondition',
- ];
- }
-
- protected function defaultExpressionBuilders()
- {
- return [
- 'yii\db\Query' => 'yii\db\QueryExpressionBuilder',
- 'yii\db\PdoValue' => 'yii\db\PdoValueBuilder',
- 'yii\db\Expression' => 'yii\db\ExpressionBuilder',
- 'yii\db\conditions\ConjunctionCondition' => 'yii\db\conditions\ConjunctionConditionBuilder',
- 'yii\db\conditions\NotCondition' => 'yii\db\conditions\NotConditionBuilder',
- 'yii\db\conditions\AndCondition' => 'yii\db\conditions\ConjunctionConditionBuilder',
- 'yii\db\conditions\OrCondition' => 'yii\db\conditions\ConjunctionConditionBuilder',
- 'yii\db\conditions\BetweenCondition' => 'yii\db\conditions\BetweenConditionBuilder',
- 'yii\db\conditions\InCondition' => 'yii\db\conditions\InConditionBuilder',
- 'yii\db\conditions\LikeCondition' => 'yii\db\conditions\LikeConditionBuilder',
- 'yii\db\conditions\ExistsCondition' => 'yii\db\conditions\ExistsConditionBuilder',
- 'yii\db\conditions\SimpleCondition' => 'yii\db\conditions\SimpleConditionBuilder',
- 'yii\db\conditions\HashCondition' => 'yii\db\conditions\HashConditionBuilder',
- 'yii\db\conditions\BetweenColumnsCondition' => 'yii\db\conditions\BetweenColumnsConditionBuilder',
- ];
- }
-
- public function setExpressionBuilders($builders)
- {
- $this->expressionBuilders = array_merge($this->expressionBuilders, $builders);
- }
-
- public function setConditionClasses($classes)
- {
- $this->conditionClasses = array_merge($this->conditionClasses, $classes);
- }
-
- public function build($query, $params = [])
- {
- $query = $query->prepare($this);
- $params = empty($params) ? $query->params : array_merge($params, $query->params);
- $clauses = [
- $this->buildSelect($query->select, $params, $query->distinct, $query->selectOption),
- $this->buildFrom($query->from, $params),
- $this->buildJoin($query->join, $params),
- $this->buildWhere($query->where, $params),
- $this->buildGroupBy($query->groupBy),
- $this->buildHaving($query->having, $params),
- ];
- $sql = implode($this->separator, array_filter($clauses));
- $sql = $this->buildOrderByAndLimit($sql, $query->orderBy, $query->limit, $query->offset);
- if (!empty($query->orderBy)) {
- foreach ($query->orderBy as $expression) {
- if ($expression instanceof ExpressionInterface) {
- $this->buildExpression($expression, $params);
- }
- }
- }
- if (!empty($query->groupBy)) {
- foreach ($query->groupBy as $expression) {
- if ($expression instanceof ExpressionInterface) {
- $this->buildExpression($expression, $params);
- }
- }
- }
- $union = $this->buildUnion($query->union, $params);
- if ($union !== '') {
- $sql = "($sql){$this->separator}$union";
- }
- return [$sql, $params];
- }
-
- public function buildExpression(ExpressionInterface $expression, &$params = [])
- {
- $builder = $this->getExpressionBuilder($expression);
- return $builder->build($expression, $params);
- }
-
- public function getExpressionBuilder(ExpressionInterface $expression)
- {
- $className = get_class($expression);
- if (!isset($this->expressionBuilders[$className])) {
- foreach (array_reverse($this->expressionBuilders) as $expressionClass => $builderClass) {
- if (is_subclass_of($expression, $expressionClass)) {
- $this->expressionBuilders[$className] = $builderClass;
- break;
- }
- }
- if (!isset($this->expressionBuilders[$className])) {
- throw new InvalidArgumentException('Expression of class ' . $className . ' can not be built in ' . get_class($this));
- }
- }
- if ($this->expressionBuilders[$className] === __CLASS__) {
- return $this;
- }
- if (!is_object($this->expressionBuilders[$className])) {
- $this->expressionBuilders[$className] = new $this->expressionBuilders[$className]($this);
- }
- return $this->expressionBuilders[$className];
- }
-
- public function insert($table, $columns, &$params)
- {
- list($names, $placeholders, $values, $params) = $this->prepareInsertValues($table, $columns, $params);
- return 'INSERT INTO ' . $this->db->quoteTableName($table)
- . (!empty($names) ? ' (' . implode(', ', $names) . ')' : '')
- . (!empty($placeholders) ? ' VALUES (' . implode(', ', $placeholders) . ')' : $values);
- }
-
- protected function prepareInsertValues($table, $columns, $params = [])
- {
- $schema = $this->db->getSchema();
- $tableSchema = $schema->getTableSchema($table);
- $columnSchemas = $tableSchema !== null ? $tableSchema->columns : [];
- $names = [];
- $placeholders = [];
- $values = ' DEFAULT VALUES';
- if ($columns instanceof Query) {
- list($names, $values, $params) = $this->prepareInsertSelectSubQuery($columns, $schema, $params);
- } else {
- foreach ($columns as $name => $value) {
- $names[] = $schema->quoteColumnName($name);
- $value = isset($columnSchemas[$name]) ? $columnSchemas[$name]->dbTypecast($value) : $value;
- if ($value instanceof ExpressionInterface) {
- $placeholders[] = $this->buildExpression($value, $params);
- } elseif ($value instanceof \yii\db\Query) {
- list($sql, $params) = $this->build($value, $params);
- $placeholders[] = "($sql)";
- } else {
- $placeholders[] = $this->bindParam($value, $params);
- }
- }
- }
- return [$names, $placeholders, $values, $params];
- }
-
- protected function prepareInsertSelectSubQuery($columns, $schema, $params = [])
- {
- if (!is_array($columns->select) || empty($columns->select) || in_array('*', $columns->select)) {
- throw new InvalidArgumentException('Expected select query object with enumerated (named) parameters');
- }
- list($values, $params) = $this->build($columns, $params);
- $names = [];
- $values = ' ' . $values;
- foreach ($columns->select as $title => $field) {
- if (is_string($title)) {
- $names[] = $schema->quoteColumnName($title);
- } elseif (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_\.]+)$/', $field, $matches)) {
- $names[] = $schema->quoteColumnName($matches[2]);
- } else {
- $names[] = $schema->quoteColumnName($field);
- }
- }
- return [$names, $values, $params];
- }
-
- public function batchInsert($table, $columns, $rows, &$params = [])
- {
- if (empty($rows)) {
- return '';
- }
- $schema = $this->db->getSchema();
- if (($tableSchema = $schema->getTableSchema($table)) !== null) {
- $columnSchemas = $tableSchema->columns;
- } else {
- $columnSchemas = [];
- }
- $values = [];
- foreach ($rows as $row) {
- $vs = [];
- foreach ($row as $i => $value) {
- if (isset($columns[$i], $columnSchemas[$columns[$i]])) {
- $value = $columnSchemas[$columns[$i]]->dbTypecast($value);
- }
- if (is_string($value)) {
- $value = $schema->quoteValue($value);
- } elseif (is_float($value)) {
-
- $value = StringHelper::floatToString($value);
- } elseif ($value === false) {
- $value = 0;
- } elseif ($value === null) {
- $value = 'NULL';
- } elseif ($value instanceof ExpressionInterface) {
- $value = $this->buildExpression($value, $params);
- }
- $vs[] = $value;
- }
- $values[] = '(' . implode(', ', $vs) . ')';
- }
- if (empty($values)) {
- return '';
- }
- foreach ($columns as $i => $name) {
- $columns[$i] = $schema->quoteColumnName($name);
- }
- return 'INSERT INTO ' . $schema->quoteTableName($table)
- . ' (' . implode(', ', $columns) . ') VALUES ' . implode(', ', $values);
- }
-
- public function upsert($table, $insertColumns, $updateColumns, &$params)
- {
- throw new NotSupportedException($this->db->getDriverName() . ' does not support upsert statements.');
- }
-
- protected function prepareUpsertColumns($table, $insertColumns, $updateColumns, &$constraints = [])
- {
- if ($insertColumns instanceof Query) {
- list($insertNames) = $this->prepareInsertSelectSubQuery($insertColumns, $this->db->getSchema());
- } else {
- $insertNames = array_map([$this->db, 'quoteColumnName'], array_keys($insertColumns));
- }
- $uniqueNames = $this->getTableUniqueColumnNames($table, $insertNames, $constraints);
- $uniqueNames = array_map([$this->db, 'quoteColumnName'], $uniqueNames);
- if ($updateColumns !== true) {
- return [$uniqueNames, $insertNames, null];
- }
- return [$uniqueNames, $insertNames, array_diff($insertNames, $uniqueNames)];
- }
-
- private function getTableUniqueColumnNames($name, $columns, &$constraints = [])
- {
- $schema = $this->db->getSchema();
- if (!$schema instanceof ConstraintFinderInterface) {
- return [];
- }
- $constraints = [];
- $primaryKey = $schema->getTablePrimaryKey($name);
- if ($primaryKey !== null) {
- $constraints[] = $primaryKey;
- }
- foreach ($schema->getTableIndexes($name) as $constraint) {
- if ($constraint->isUnique) {
- $constraints[] = $constraint;
- }
- }
- $constraints = array_merge($constraints, $schema->getTableUniques($name));
-
- $constraints = array_combine(array_map(function (Constraint $constraint) {
- $columns = $constraint->columnNames;
- sort($columns, SORT_STRING);
- return json_encode($columns);
- }, $constraints), $constraints);
- $columnNames = [];
-
- $constraints = array_values(array_filter($constraints, function (Constraint $constraint) use ($schema, $columns, &$columnNames) {
- $constraintColumnNames = array_map([$schema, 'quoteColumnName'], $constraint->columnNames);
- $result = !array_diff($constraintColumnNames, $columns);
- if ($result) {
- $columnNames = array_merge($columnNames, $constraintColumnNames);
- }
- return $result;
- }));
- return array_unique($columnNames);
- }
-
- public function update($table, $columns, $condition, &$params)
- {
- list($lines, $params) = $this->prepareUpdateSets($table, $columns, $params);
- $sql = 'UPDATE ' . $this->db->quoteTableName($table) . ' SET ' . implode(', ', $lines);
- $where = $this->buildWhere($condition, $params);
- return $where === '' ? $sql : $sql . ' ' . $where;
- }
-
- protected function prepareUpdateSets($table, $columns, $params = [])
- {
- $tableSchema = $this->db->getTableSchema($table);
- $columnSchemas = $tableSchema !== null ? $tableSchema->columns : [];
- $sets = [];
- foreach ($columns as $name => $value) {
- $value = isset($columnSchemas[$name]) ? $columnSchemas[$name]->dbTypecast($value) : $value;
- if ($value instanceof ExpressionInterface) {
- $placeholder = $this->buildExpression($value, $params);
- } else {
- $placeholder = $this->bindParam($value, $params);
- }
- $sets[] = $this->db->quoteColumnName($name) . '=' . $placeholder;
- }
- return [$sets, $params];
- }
-
- public function delete($table, $condition, &$params)
- {
- $sql = 'DELETE FROM ' . $this->db->quoteTableName($table);
- $where = $this->buildWhere($condition, $params);
- return $where === '' ? $sql : $sql . ' ' . $where;
- }
-
- public function createTable($table, $columns, $options = null)
- {
- $cols = [];
- foreach ($columns as $name => $type) {
- if (is_string($name)) {
- $cols[] = "\t" . $this->db->quoteColumnName($name) . ' ' . $this->getColumnType($type);
- } else {
- $cols[] = "\t" . $type;
- }
- }
- $sql = 'CREATE TABLE ' . $this->db->quoteTableName($table) . " (\n" . implode(",\n", $cols) . "\n)";
- return $options === null ? $sql : $sql . ' ' . $options;
- }
-
- public function renameTable($oldName, $newName)
- {
- return 'RENAME TABLE ' . $this->db->quoteTableName($oldName) . ' TO ' . $this->db->quoteTableName($newName);
- }
-
- public function dropTable($table)
- {
- return 'DROP TABLE ' . $this->db->quoteTableName($table);
- }
-
- public function addPrimaryKey($name, $table, $columns)
- {
- if (is_string($columns)) {
- $columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
- }
- foreach ($columns as $i => $col) {
- $columns[$i] = $this->db->quoteColumnName($col);
- }
- return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT '
- . $this->db->quoteColumnName($name) . ' PRIMARY KEY ('
- . implode(', ', $columns) . ')';
- }
-
- public function dropPrimaryKey($name, $table)
- {
- return 'ALTER TABLE ' . $this->db->quoteTableName($table)
- . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
- }
-
- public function truncateTable($table)
- {
- return 'TRUNCATE TABLE ' . $this->db->quoteTableName($table);
- }
-
- public function addColumn($table, $column, $type)
- {
- return 'ALTER TABLE ' . $this->db->quoteTableName($table)
- . ' ADD ' . $this->db->quoteColumnName($column) . ' '
- . $this->getColumnType($type);
- }
-
- public function dropColumn($table, $column)
- {
- return 'ALTER TABLE ' . $this->db->quoteTableName($table)
- . ' DROP COLUMN ' . $this->db->quoteColumnName($column);
- }
-
- public function renameColumn($table, $oldName, $newName)
- {
- return 'ALTER TABLE ' . $this->db->quoteTableName($table)
- . ' RENAME COLUMN ' . $this->db->quoteColumnName($oldName)
- . ' TO ' . $this->db->quoteColumnName($newName);
- }
-
- public function alterColumn($table, $column, $type)
- {
- return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' CHANGE '
- . $this->db->quoteColumnName($column) . ' '
- . $this->db->quoteColumnName($column) . ' '
- . $this->getColumnType($type);
- }
-
- public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
- {
- $sql = 'ALTER TABLE ' . $this->db->quoteTableName($table)
- . ' ADD CONSTRAINT ' . $this->db->quoteColumnName($name)
- . ' FOREIGN KEY (' . $this->buildColumns($columns) . ')'
- . ' REFERENCES ' . $this->db->quoteTableName($refTable)
- . ' (' . $this->buildColumns($refColumns) . ')';
- if ($delete !== null) {
- $sql .= ' ON DELETE ' . $delete;
- }
- if ($update !== null) {
- $sql .= ' ON UPDATE ' . $update;
- }
- return $sql;
- }
-
- public function dropForeignKey($name, $table)
- {
- return 'ALTER TABLE ' . $this->db->quoteTableName($table)
- . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
- }
-
- public function createIndex($name, $table, $columns, $unique = false)
- {
- return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ')
- . $this->db->quoteTableName($name) . ' ON '
- . $this->db->quoteTableName($table)
- . ' (' . $this->buildColumns($columns) . ')';
- }
-
- public function dropIndex($name, $table)
- {
- return 'DROP INDEX ' . $this->db->quoteTableName($name) . ' ON ' . $this->db->quoteTableName($table);
- }
-
- public function addUnique($name, $table, $columns)
- {
- if (is_string($columns)) {
- $columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
- }
- foreach ($columns as $i => $col) {
- $columns[$i] = $this->db->quoteColumnName($col);
- }
- return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT '
- . $this->db->quoteColumnName($name) . ' UNIQUE ('
- . implode(', ', $columns) . ')';
- }
-
- public function dropUnique($name, $table)
- {
- return 'ALTER TABLE ' . $this->db->quoteTableName($table)
- . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
- }
-
- public function addCheck($name, $table, $expression)
- {
- return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT '
- . $this->db->quoteColumnName($name) . ' CHECK (' . $this->db->quoteSql($expression) . ')';
- }
-
- public function dropCheck($name, $table)
- {
- return 'ALTER TABLE ' . $this->db->quoteTableName($table)
- . ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
- }
-
- public function addDefaultValue($name, $table, $column, $value)
- {
- throw new NotSupportedException($this->db->getDriverName() . ' does not support adding default value constraints.');
- }
-
- public function dropDefaultValue($name, $table)
- {
- throw new NotSupportedException($this->db->getDriverName() . ' does not support dropping default value constraints.');
- }
-
- public function resetSequence($table, $value = null)
- {
- throw new NotSupportedException($this->db->getDriverName() . ' does not support resetting sequence.');
- }
-
- public function executeResetSequence($table, $value = null)
- {
- $this->db->createCommand()->resetSequence($table, $value)->execute();
- }
-
- public function checkIntegrity($check = true, $schema = '', $table = '')
- {
- throw new NotSupportedException($this->db->getDriverName() . ' does not support enabling/disabling integrity check.');
- }
-
- public function addCommentOnColumn($table, $column, $comment)
- {
- return 'COMMENT ON COLUMN ' . $this->db->quoteTableName($table) . '.' . $this->db->quoteColumnName($column) . ' IS ' . $this->db->quoteValue($comment);
- }
-
- public function addCommentOnTable($table, $comment)
- {
- return 'COMMENT ON TABLE ' . $this->db->quoteTableName($table) . ' IS ' . $this->db->quoteValue($comment);
- }
-
- public function dropCommentFromColumn($table, $column)
- {
- return 'COMMENT ON COLUMN ' . $this->db->quoteTableName($table) . '.' . $this->db->quoteColumnName($column) . ' IS NULL';
- }
-
- public function dropCommentFromTable($table)
- {
- return 'COMMENT ON TABLE ' . $this->db->quoteTableName($table) . ' IS NULL';
- }
-
- public function createView($viewName, $subQuery)
- {
- if ($subQuery instanceof Query) {
- list($rawQuery, $params) = $this->build($subQuery);
- array_walk(
- $params,
- function (&$param) {
- $param = $this->db->quoteValue($param);
- }
- );
- $subQuery = strtr($rawQuery, $params);
- }
- return 'CREATE VIEW ' . $this->db->quoteTableName($viewName) . ' AS ' . $subQuery;
- }
-
- public function dropView($viewName)
- {
- return 'DROP VIEW ' . $this->db->quoteTableName($viewName);
- }
-
- public function getColumnType($type)
- {
- if ($type instanceof ColumnSchemaBuilder) {
- $type = $type->__toString();
- }
- if (isset($this->typeMap[$type])) {
- return $this->typeMap[$type];
- } elseif (preg_match('/^(\w+)\((.+?)\)(.*)$/', $type, $matches)) {
- if (isset($this->typeMap[$matches[1]])) {
- return preg_replace('/\(.+\)/', '(' . $matches[2] . ')', $this->typeMap[$matches[1]]) . $matches[3];
- }
- } elseif (preg_match('/^(\w+)\s+/', $type, $matches)) {
- if (isset($this->typeMap[$matches[1]])) {
- return preg_replace('/^\w+/', $this->typeMap[$matches[1]], $type);
- }
- }
- return $type;
- }
-
- public function buildSelect($columns, &$params, $distinct = false, $selectOption = null)
- {
- $select = $distinct ? 'SELECT DISTINCT' : 'SELECT';
- if ($selectOption !== null) {
- $select .= ' ' . $selectOption;
- }
- if (empty($columns)) {
- return $select . ' *';
- }
- foreach ($columns as $i => $column) {
- if ($column instanceof ExpressionInterface) {
- if (is_int($i)) {
- $columns[$i] = $this->buildExpression($column, $params);
- } else {
- $columns[$i] = $this->buildExpression($column, $params) . ' AS ' . $this->db->quoteColumnName($i);
- }
- } elseif ($column instanceof Query) {
- list($sql, $params) = $this->build($column, $params);
- $columns[$i] = "($sql) AS " . $this->db->quoteColumnName($i);
- } elseif (is_string($i) && $i !== $column) {
- if (strpos($column, '(') === false) {
- $column = $this->db->quoteColumnName($column);
- }
- $columns[$i] = "$column AS " . $this->db->quoteColumnName($i);
- } elseif (strpos($column, '(') === false) {
- if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_\.]+)$/', $column, $matches)) {
- $columns[$i] = $this->db->quoteColumnName($matches[1]) . ' AS ' . $this->db->quoteColumnName($matches[2]);
- } else {
- $columns[$i] = $this->db->quoteColumnName($column);
- }
- }
- }
- return $select . ' ' . implode(', ', $columns);
- }
-
- public function buildFrom($tables, &$params)
- {
- if (empty($tables)) {
- return '';
- }
- $tables = $this->quoteTableNames($tables, $params);
- return 'FROM ' . implode(', ', $tables);
- }
-
- public function buildJoin($joins, &$params)
- {
- if (empty($joins)) {
- return '';
- }
- foreach ($joins as $i => $join) {
- if (!is_array($join) || !isset($join[0], $join[1])) {
- throw new Exception('A join clause must be specified as an array of join type, join table, and optionally join condition.');
- }
-
- list($joinType, $table) = $join;
- $tables = $this->quoteTableNames((array)$table, $params);
- $table = reset($tables);
- $joins[$i] = "$joinType $table";
- if (isset($join[2])) {
- $condition = $this->buildCondition($join[2], $params);
- if ($condition !== '') {
- $joins[$i] .= ' ON ' . $condition;
- }
- }
- }
- return implode($this->separator, $joins);
- }
-
- private function quoteTableNames($tables, &$params)
- {
- foreach ($tables as $i => $table) {
- if ($table instanceof Query) {
- list($sql, $params) = $this->build($table, $params);
- $tables[$i] = "($sql) " . $this->db->quoteTableName($i);
- } elseif (is_string($i)) {
- if (strpos($table, '(') === false) {
- $table = $this->db->quoteTableName($table);
- }
- $tables[$i] = "$table " . $this->db->quoteTableName($i);
- } elseif (strpos($table, '(') === false) {
- if ($tableWithAlias = $this->extractAlias($table)) {
- $tables[$i] = $this->db->quoteTableName($tableWithAlias[1]) . ' ' . $this->db->quoteTableName($tableWithAlias[2]);
- } else {
- $tables[$i] = $this->db->quoteTableName($table);
- }
- }
- }
- return $tables;
- }
-
- public function buildWhere($condition, &$params)
- {
- $where = $this->buildCondition($condition, $params);
- return $where === '' ? '' : 'WHERE ' . $where;
- }
-
- public function buildGroupBy($columns)
- {
- if (empty($columns)) {
- return '';
- }
- foreach ($columns as $i => $column) {
- if ($column instanceof ExpressionInterface) {
- $columns[$i] = $this->buildExpression($column);
- } elseif (strpos($column, '(') === false) {
- $columns[$i] = $this->db->quoteColumnName($column);
- }
- }
- return 'GROUP BY ' . implode(', ', $columns);
- }
-
- public function buildHaving($condition, &$params)
- {
- $having = $this->buildCondition($condition, $params);
- return $having === '' ? '' : 'HAVING ' . $having;
- }
-
- public function buildOrderByAndLimit($sql, $orderBy, $limit, $offset)
- {
- $orderBy = $this->buildOrderBy($orderBy);
- if ($orderBy !== '') {
- $sql .= $this->separator . $orderBy;
- }
- $limit = $this->buildLimit($limit, $offset);
- if ($limit !== '') {
- $sql .= $this->separator . $limit;
- }
- return $sql;
- }
-
- public function buildOrderBy($columns)
- {
- if (empty($columns)) {
- return '';
- }
- $orders = [];
- foreach ($columns as $name => $direction) {
- if ($direction instanceof ExpressionInterface) {
- $orders[] = $this->buildExpression($direction);
- } else {
- $orders[] = $this->db->quoteColumnName($name) . ($direction === SORT_DESC ? ' DESC' : '');
- }
- }
- return 'ORDER BY ' . implode(', ', $orders);
- }
-
- public function buildLimit($limit, $offset)
- {
- $sql = '';
- if ($this->hasLimit($limit)) {
- $sql = 'LIMIT ' . $limit;
- }
- if ($this->hasOffset($offset)) {
- $sql .= ' OFFSET ' . $offset;
- }
- return ltrim($sql);
- }
-
- protected function hasLimit($limit)
- {
- return ($limit instanceof ExpressionInterface) || ctype_digit((string)$limit);
- }
-
- protected function hasOffset($offset)
- {
- return ($offset instanceof ExpressionInterface) || ctype_digit((string)$offset) && (string)$offset !== '0';
- }
-
- public function buildUnion($unions, &$params)
- {
- if (empty($unions)) {
- return '';
- }
- $result = '';
- foreach ($unions as $i => $union) {
- $query = $union['query'];
- if ($query instanceof Query) {
- list($unions[$i]['query'], $params) = $this->build($query, $params);
- }
- $result .= 'UNION ' . ($union['all'] ? 'ALL ' : '') . '( ' . $unions[$i]['query'] . ' ) ';
- }
- return trim($result);
- }
-
- public function buildColumns($columns)
- {
- if (!is_array($columns)) {
- if (strpos($columns, '(') !== false) {
- return $columns;
- }
- $rawColumns = $columns;
- $columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
- if ($columns === false) {
- throw new InvalidArgumentException("$rawColumns is not valid columns.");
- }
- }
- foreach ($columns as $i => $column) {
- if ($column instanceof ExpressionInterface) {
- $columns[$i] = $this->buildExpression($column);
- } elseif (strpos($column, '(') === false) {
- $columns[$i] = $this->db->quoteColumnName($column);
- }
- }
- return implode(', ', $columns);
- }
-
- public function buildCondition($condition, &$params)
- {
- if (is_array($condition)) {
- if (empty($condition)) {
- return '';
- }
- $condition = $this->createConditionFromArray($condition);
- }
- if ($condition instanceof ExpressionInterface) {
- return $this->buildExpression($condition, $params);
- }
- return (string)$condition;
- }
-
- public function createConditionFromArray($condition)
- {
- if (isset($condition[0])) {
- $operator = strtoupper(array_shift($condition));
- if (isset($this->conditionClasses[$operator])) {
- $className = $this->conditionClasses[$operator];
- } else {
- $className = 'yii\db\conditions\SimpleCondition';
- }
-
- return $className::fromArrayDefinition($operator, $condition);
- }
-
- return new HashCondition($condition);
- }
-
- public function buildHashCondition($condition, &$params)
- {
- return $this->buildCondition(new HashCondition($condition), $params);
- }
-
- public function buildAndCondition($operator, $operands, &$params)
- {
- array_unshift($operands, $operator);
- return $this->buildCondition($operands, $params);
- }
-
- public function buildNotCondition($operator, $operands, &$params)
- {
- array_unshift($operands, $operator);
- return $this->buildCondition($operands, $params);
- }
-
- public function buildBetweenCondition($operator, $operands, &$params)
- {
- array_unshift($operands, $operator);
- return $this->buildCondition($operands, $params);
- }
-
- public function buildInCondition($operator, $operands, &$params)
- {
- array_unshift($operands, $operator);
- return $this->buildCondition($operands, $params);
- }
-
- public function buildLikeCondition($operator, $operands, &$params)
- {
- array_unshift($operands, $operator);
- return $this->buildCondition($operands, $params);
- }
-
- public function buildExistsCondition($operator, $operands, &$params)
- {
- array_unshift($operands, $operator);
- return $this->buildCondition($operands, $params);
- }
-
- public function buildSimpleCondition($operator, $operands, &$params)
- {
- array_unshift($operands, $operator);
- return $this->buildCondition($operands, $params);
- }
-
- public function selectExists($rawSql)
- {
- return 'SELECT EXISTS(' . $rawSql . ')';
- }
-
- public function bindParam($value, &$params)
- {
- $phName = self::PARAM_PREFIX . count($params);
- $params[$phName] = $value;
- return $phName;
- }
-
- protected function extractAlias($table)
- {
- if (preg_match('/^(.*?)(?i:\s+as|)\s+([^ ]+)$/', $table, $matches)) {
- return $matches;
- }
- return false;
- }
- }
|