1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345 |
- <?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)
- {
- $this->select = $this->normalizeSelect($columns);
- $this->selectOption = $option;
- return $this;
- }
-
- public function addSelect($columns)
- {
- if ($this->select === null) {
- return $this->select($columns);
- }
- if (!is_array($this->select)) {
- $this->select = $this->normalizeSelect($this->select);
- }
- $this->select = array_merge($this->select, $this->normalizeSelect($columns));
- return $this;
- }
-
- protected function normalizeSelect($columns)
- {
- if ($columns instanceof ExpressionInterface) {
- $columns = [$columns];
- } elseif (!is_array($columns)) {
- $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
- }
- $select = [];
- foreach ($columns as $columnAlias => $columnDefinition) {
- if (is_string($columnAlias)) {
-
- $select[$columnAlias] = $columnDefinition;
- continue;
- }
- if (is_string($columnDefinition)) {
- if (
- preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_\.]+)$/', $columnDefinition, $matches) &&
- !preg_match('/^\d+$/', $matches[2]) &&
- strpos($matches[2], '.') === false
- ) {
-
- $select[$matches[2]] = $matches[1];
- continue;
- }
- if (strpos($columnDefinition, '(') === false) {
-
- $select[$columnDefinition] = $columnDefinition;
- continue;
- }
- }
-
- $select[] = $columnDefinition;
- }
- return $select;
- }
-
- 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);
- }
- }
|