123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311 |
- <?php
- namespace yii\db;
- use Yii;
- use yii\base\Component;
- use yii\base\InvalidArgumentException;
- use yii\helpers\ArrayHelper;
- use yii\base\InvalidConfigException;
- class Query extends Component implements QueryInterface, ExpressionInterface
- {
- use QueryTrait;
-
- public $select;
-
- public $selectOption;
-
- public $distinct;
-
- public $from;
-
- public $groupBy;
-
- public $join;
-
- public $having;
-
- public $union;
-
- public $params = [];
-
- public $queryCacheDuration;
-
- public $queryCacheDependency;
-
- public function createCommand($db = null)
- {
- if ($db === null) {
- $db = Yii::$app->getDb();
- }
- list($sql, $params) = $db->getQueryBuilder()->build($this);
- $command = $db->createCommand($sql, $params);
- $this->setCommandCache($command);
- return $command;
- }
-
- public function prepare($builder)
- {
- return $this;
- }
-
- public function batch($batchSize = 100, $db = null)
- {
- return Yii::createObject([
- 'class' => BatchQueryResult::className(),
- 'query' => $this,
- 'batchSize' => $batchSize,
- 'db' => $db,
- 'each' => false,
- ]);
- }
-
- public function each($batchSize = 100, $db = null)
- {
- return Yii::createObject([
- 'class' => BatchQueryResult::className(),
- 'query' => $this,
- 'batchSize' => $batchSize,
- 'db' => $db,
- 'each' => true,
- ]);
- }
-
- public function all($db = null)
- {
- if ($this->emulateExecution) {
- return [];
- }
- $rows = $this->createCommand($db)->queryAll();
- return $this->populate($rows);
- }
-
- public function populate($rows)
- {
- if ($this->indexBy === null) {
- return $rows;
- }
- $result = [];
- foreach ($rows as $row) {
- $result[ArrayHelper::getValue($row, $this->indexBy)] = $row;
- }
- return $result;
- }
-
- public function one($db = null)
- {
- if ($this->emulateExecution) {
- return false;
- }
- return $this->createCommand($db)->queryOne();
- }
-
- public function scalar($db = null)
- {
- if ($this->emulateExecution) {
- return null;
- }
- return $this->createCommand($db)->queryScalar();
- }
-
- public function column($db = null)
- {
- if ($this->emulateExecution) {
- return [];
- }
- if ($this->indexBy === null) {
- return $this->createCommand($db)->queryColumn();
- }
- if (is_string($this->indexBy) && is_array($this->select) && count($this->select) === 1) {
- if (strpos($this->indexBy, '.') === false && count($tables = $this->getTablesUsedInFrom()) > 0) {
- $this->select[] = key($tables) . '.' . $this->indexBy;
- } else {
- $this->select[] = $this->indexBy;
- }
- }
- $rows = $this->createCommand($db)->queryAll();
- $results = [];
- foreach ($rows as $row) {
- $value = reset($row);
- if ($this->indexBy instanceof \Closure) {
- $results[call_user_func($this->indexBy, $row)] = $value;
- } else {
- $results[$row[$this->indexBy]] = $value;
- }
- }
- return $results;
- }
-
- public function count($q = '*', $db = null)
- {
- if ($this->emulateExecution) {
- return 0;
- }
- return $this->queryScalar("COUNT($q)", $db);
- }
-
- public function sum($q, $db = null)
- {
- if ($this->emulateExecution) {
- return 0;
- }
- return $this->queryScalar("SUM($q)", $db);
- }
-
- public function average($q, $db = null)
- {
- if ($this->emulateExecution) {
- return 0;
- }
- return $this->queryScalar("AVG($q)", $db);
- }
-
- public function min($q, $db = null)
- {
- return $this->queryScalar("MIN($q)", $db);
- }
-
- public function max($q, $db = null)
- {
- return $this->queryScalar("MAX($q)", $db);
- }
-
- public function exists($db = null)
- {
- if ($this->emulateExecution) {
- return false;
- }
- $command = $this->createCommand($db);
- $params = $command->params;
- $command->setSql($command->db->getQueryBuilder()->selectExists($command->getSql()));
- $command->bindValues($params);
- return (bool) $command->queryScalar();
- }
-
- protected function queryScalar($selectExpression, $db)
- {
- if ($this->emulateExecution) {
- return null;
- }
- if (
- !$this->distinct
- && empty($this->groupBy)
- && empty($this->having)
- && empty($this->union)
- ) {
- $select = $this->select;
- $order = $this->orderBy;
- $limit = $this->limit;
- $offset = $this->offset;
- $this->select = [$selectExpression];
- $this->orderBy = null;
- $this->limit = null;
- $this->offset = null;
- $command = $this->createCommand($db);
- $this->select = $select;
- $this->orderBy = $order;
- $this->limit = $limit;
- $this->offset = $offset;
- return $command->queryScalar();
- }
- $command = (new self())
- ->select([$selectExpression])
- ->from(['c' => $this])
- ->createCommand($db);
- $this->setCommandCache($command);
- return $command->queryScalar();
- }
-
- public function getTablesUsedInFrom()
- {
- if (empty($this->from)) {
- return [];
- }
- if (is_array($this->from)) {
- $tableNames = $this->from;
- } elseif (is_string($this->from)) {
- $tableNames = preg_split('/\s*,\s*/', trim($this->from), -1, PREG_SPLIT_NO_EMPTY);
- } elseif ($this->from instanceof Expression) {
- $tableNames = [$this->from];
- } else {
- throw new InvalidConfigException(gettype($this->from) . ' in $from is not supported.');
- }
- return $this->cleanUpTableNames($tableNames);
- }
-
- protected function cleanUpTableNames($tableNames)
- {
- $cleanedUpTableNames = [];
- foreach ($tableNames as $alias => $tableName) {
- if (is_string($tableName) && !is_string($alias)) {
- $pattern = <<<PATTERN
- ~
- ^
- \s*
- (
- (?:['"`\[]|{{)
- .*?
- (?:['"`\]]|}})
- |
- \(.*?\)
- |
- .*?
- )
- (?:
- (?:
- \s+
- (?:as)?
- \s*
- )
- (
- (?:['"`\[]|{{)
- .*?
- (?:['"`\]]|}})
- |
- .*?
- )
- )?
- \s*
- $
- ~iux
- PATTERN;
- if (preg_match($pattern, $tableName, $matches)) {
- if (isset($matches[2])) {
- list(, $tableName, $alias) = $matches;
- } else {
- $tableName = $alias = $matches[1];
- }
- }
- }
- if ($tableName instanceof Expression) {
- if (!is_string($alias)) {
- throw new InvalidArgumentException('To use Expression in from() method, pass it in array format with alias.');
- }
- $cleanedUpTableNames[$this->ensureNameQuoted($alias)] = $tableName;
- } elseif ($tableName instanceof self) {
- $cleanedUpTableNames[$this->ensureNameQuoted($alias)] = $tableName;
- } else {
- $cleanedUpTableNames[$this->ensureNameQuoted($alias)] = $this->ensureNameQuoted($tableName);
- }
- }
- return $cleanedUpTableNames;
- }
-
- private function ensureNameQuoted($name)
- {
- $name = str_replace(["'", '"', '`', '[', ']'], '', $name);
- if ($name && !preg_match('/^{{.*}}$/', $name)) {
- return '{{' . $name . '}}';
- }
- return $name;
- }
-
- public function select($columns, $option = null)
- {
- if ($columns instanceof ExpressionInterface) {
- $columns = [$columns];
- } elseif (!is_array($columns)) {
- $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
- }
-
-
- $this->select = [];
- $this->select = $this->getUniqueColumns($columns);
- $this->selectOption = $option;
- return $this;
- }
-
- public function addSelect($columns)
- {
- if ($columns instanceof ExpressionInterface) {
- $columns = [$columns];
- } elseif (!is_array($columns)) {
- $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
- }
- $columns = $this->getUniqueColumns($columns);
- if ($this->select === null) {
- $this->select = $columns;
- } else {
- $this->select = array_merge($this->select, $columns);
- }
- return $this;
- }
-
- protected function getUniqueColumns($columns)
- {
- $unaliasedColumns = $this->getUnaliasedColumnsFromSelect();
- $result = [];
- foreach ($columns as $columnAlias => $columnDefinition) {
- if (!$columnDefinition instanceof Query) {
- if (is_string($columnAlias)) {
- $existsInSelect = isset($this->select[$columnAlias]) && $this->select[$columnAlias] === $columnDefinition;
- if ($existsInSelect) {
- continue;
- }
- } elseif (is_int($columnAlias)) {
- $existsInSelect = in_array($columnDefinition, $unaliasedColumns, true);
- $existsInResultSet = in_array($columnDefinition, $result, true);
- if ($existsInSelect || $existsInResultSet) {
- continue;
- }
- }
- }
- $result[$columnAlias] = $columnDefinition;
- }
- return $result;
- }
-
- protected function getUnaliasedColumnsFromSelect()
- {
- $result = [];
- if (is_array($this->select)) {
- foreach ($this->select as $name => $value) {
- if (is_int($name)) {
- $result[] = $value;
- }
- }
- }
- return array_unique($result);
- }
-
- public function distinct($value = true)
- {
- $this->distinct = $value;
- return $this;
- }
-
- public function from($tables)
- {
- if ($tables instanceof ExpressionInterface) {
- $tables = [$tables];
- }
- if (is_string($tables)) {
- $tables = preg_split('/\s*,\s*/', trim($tables), -1, PREG_SPLIT_NO_EMPTY);
- }
- $this->from = $tables;
- return $this;
- }
-
- public function where($condition, $params = [])
- {
- $this->where = $condition;
- $this->addParams($params);
- return $this;
- }
-
- public function andWhere($condition, $params = [])
- {
- if ($this->where === null) {
- $this->where = $condition;
- } elseif (is_array($this->where) && isset($this->where[0]) && strcasecmp($this->where[0], 'and') === 0) {
- $this->where[] = $condition;
- } else {
- $this->where = ['and', $this->where, $condition];
- }
- $this->addParams($params);
- return $this;
- }
-
- public function orWhere($condition, $params = [])
- {
- if ($this->where === null) {
- $this->where = $condition;
- } else {
- $this->where = ['or', $this->where, $condition];
- }
- $this->addParams($params);
- return $this;
- }
-
- public function andFilterCompare($name, $value, $defaultOperator = '=')
- {
- if (preg_match('/^(<>|>=|>|<=|<|=)/', $value, $matches)) {
- $operator = $matches[1];
- $value = substr($value, strlen($operator));
- } else {
- $operator = $defaultOperator;
- }
- return $this->andFilterWhere([$operator, $name, $value]);
- }
-
- public function join($type, $table, $on = '', $params = [])
- {
- $this->join[] = [$type, $table, $on];
- return $this->addParams($params);
- }
-
- public function innerJoin($table, $on = '', $params = [])
- {
- $this->join[] = ['INNER JOIN', $table, $on];
- return $this->addParams($params);
- }
-
- public function leftJoin($table, $on = '', $params = [])
- {
- $this->join[] = ['LEFT JOIN', $table, $on];
- return $this->addParams($params);
- }
-
- public function rightJoin($table, $on = '', $params = [])
- {
- $this->join[] = ['RIGHT JOIN', $table, $on];
- return $this->addParams($params);
- }
-
- public function groupBy($columns)
- {
- if ($columns instanceof ExpressionInterface) {
- $columns = [$columns];
- } elseif (!is_array($columns)) {
- $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
- }
- $this->groupBy = $columns;
- return $this;
- }
-
- public function addGroupBy($columns)
- {
- if ($columns instanceof ExpressionInterface) {
- $columns = [$columns];
- } elseif (!is_array($columns)) {
- $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
- }
- if ($this->groupBy === null) {
- $this->groupBy = $columns;
- } else {
- $this->groupBy = array_merge($this->groupBy, $columns);
- }
- return $this;
- }
-
- public function having($condition, $params = [])
- {
- $this->having = $condition;
- $this->addParams($params);
- return $this;
- }
-
- public function andHaving($condition, $params = [])
- {
- if ($this->having === null) {
- $this->having = $condition;
- } else {
- $this->having = ['and', $this->having, $condition];
- }
- $this->addParams($params);
- return $this;
- }
-
- public function orHaving($condition, $params = [])
- {
- if ($this->having === null) {
- $this->having = $condition;
- } else {
- $this->having = ['or', $this->having, $condition];
- }
- $this->addParams($params);
- return $this;
- }
-
- public function filterHaving(array $condition)
- {
- $condition = $this->filterCondition($condition);
- if ($condition !== []) {
- $this->having($condition);
- }
- return $this;
- }
-
- public function andFilterHaving(array $condition)
- {
- $condition = $this->filterCondition($condition);
- if ($condition !== []) {
- $this->andHaving($condition);
- }
- return $this;
- }
-
- public function orFilterHaving(array $condition)
- {
- $condition = $this->filterCondition($condition);
- if ($condition !== []) {
- $this->orHaving($condition);
- }
- return $this;
- }
-
- public function union($sql, $all = false)
- {
- $this->union[] = ['query' => $sql, 'all' => $all];
- return $this;
- }
-
- public function params($params)
- {
- $this->params = $params;
- return $this;
- }
-
- public function addParams($params)
- {
- if (!empty($params)) {
- if (empty($this->params)) {
- $this->params = $params;
- } else {
- foreach ($params as $name => $value) {
- if (is_int($name)) {
- $this->params[] = $value;
- } else {
- $this->params[$name] = $value;
- }
- }
- }
- }
- return $this;
- }
-
- public function cache($duration = true, $dependency = null)
- {
- $this->queryCacheDuration = $duration;
- $this->queryCacheDependency = $dependency;
- return $this;
- }
-
- public function noCache()
- {
- $this->queryCacheDuration = -1;
- return $this;
- }
-
- protected function setCommandCache($command)
- {
- if ($this->queryCacheDuration !== null || $this->queryCacheDependency !== null) {
- $duration = $this->queryCacheDuration === true ? null : $this->queryCacheDuration;
- $command->cache($duration, $this->queryCacheDependency);
- }
- return $command;
- }
-
- public static function create($from)
- {
- return new self([
- 'where' => $from->where,
- 'limit' => $from->limit,
- 'offset' => $from->offset,
- 'orderBy' => $from->orderBy,
- 'indexBy' => $from->indexBy,
- 'select' => $from->select,
- 'selectOption' => $from->selectOption,
- 'distinct' => $from->distinct,
- 'from' => $from->from,
- 'groupBy' => $from->groupBy,
- 'join' => $from->join,
- 'having' => $from->having,
- 'union' => $from->union,
- 'params' => $from->params,
- ]);
- }
-
- public function __toString()
- {
- return serialize($this);
- }
- }
|