1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318 |
- <?php
- namespace yii\db;
- use Yii;
- use yii\base\Component;
- use yii\base\NotSupportedException;
- class Command extends Component
- {
-
- public $db;
-
- public $pdoStatement;
-
- public $fetchMode = \PDO::FETCH_ASSOC;
-
- public $params = [];
-
- public $queryCacheDuration;
-
- public $queryCacheDependency;
-
- private $_pendingParams = [];
-
- private $_sql;
-
- private $_refreshTableName;
-
- private $_isolationLevel = false;
-
- private $_retryHandler;
-
- public function cache($duration = null, $dependency = null)
- {
- $this->queryCacheDuration = $duration === null ? $this->db->queryCacheDuration : $duration;
- $this->queryCacheDependency = $dependency;
- return $this;
- }
-
- public function noCache()
- {
- $this->queryCacheDuration = -1;
- return $this;
- }
-
- public function getSql()
- {
- return $this->_sql;
- }
-
- public function setSql($sql)
- {
- if ($sql !== $this->_sql) {
- $this->cancel();
- $this->reset();
- $this->_sql = $this->db->quoteSql($sql);
- }
- return $this;
- }
-
- public function setRawSql($sql)
- {
- if ($sql !== $this->_sql) {
- $this->cancel();
- $this->reset();
- $this->_sql = $sql;
- }
- return $this;
- }
-
- public function getRawSql()
- {
- if (empty($this->params)) {
- return $this->_sql;
- }
- $params = [];
- foreach ($this->params as $name => $value) {
- if (is_string($name) && strncmp(':', $name, 1)) {
- $name = ':' . $name;
- }
- if (is_string($value)) {
- $params[$name] = $this->db->quoteValue($value);
- } elseif (is_bool($value)) {
- $params[$name] = ($value ? 'TRUE' : 'FALSE');
- } elseif ($value === null) {
- $params[$name] = 'NULL';
- } elseif ((!is_object($value) && !is_resource($value)) || $value instanceof Expression) {
- $params[$name] = $value;
- }
- }
- if (!isset($params[1])) {
- return strtr($this->_sql, $params);
- }
- $sql = '';
- foreach (explode('?', $this->_sql) as $i => $part) {
- $sql .= (isset($params[$i]) ? $params[$i] : '') . $part;
- }
- return $sql;
- }
-
- public function prepare($forRead = null)
- {
- if ($this->pdoStatement) {
- $this->bindPendingParams();
- return;
- }
- $sql = $this->getSql();
- if ($this->db->getTransaction()) {
-
- $forRead = false;
- }
- if ($forRead || $forRead === null && $this->db->getSchema()->isReadQuery($sql)) {
- $pdo = $this->db->getSlavePdo();
- } else {
- $pdo = $this->db->getMasterPdo();
- }
- try {
- $this->pdoStatement = $pdo->prepare($sql);
- $this->bindPendingParams();
- } catch (\Exception $e) {
- $message = $e->getMessage() . "\nFailed to prepare SQL: $sql";
- $errorInfo = $e instanceof \PDOException ? $e->errorInfo : null;
- throw new Exception($message, $errorInfo, (int) $e->getCode(), $e);
- }
- }
-
- public function cancel()
- {
- $this->pdoStatement = null;
- }
-
- public function bindParam($name, &$value, $dataType = null, $length = null, $driverOptions = null)
- {
- $this->prepare();
- if ($dataType === null) {
- $dataType = $this->db->getSchema()->getPdoType($value);
- }
- if ($length === null) {
- $this->pdoStatement->bindParam($name, $value, $dataType);
- } elseif ($driverOptions === null) {
- $this->pdoStatement->bindParam($name, $value, $dataType, $length);
- } else {
- $this->pdoStatement->bindParam($name, $value, $dataType, $length, $driverOptions);
- }
- $this->params[$name] = &$value;
- return $this;
- }
-
- protected function bindPendingParams()
- {
- foreach ($this->_pendingParams as $name => $value) {
- $this->pdoStatement->bindValue($name, $value[0], $value[1]);
- }
- $this->_pendingParams = [];
- }
-
- public function bindValue($name, $value, $dataType = null)
- {
- if ($dataType === null) {
- $dataType = $this->db->getSchema()->getPdoType($value);
- }
- $this->_pendingParams[$name] = [$value, $dataType];
- $this->params[$name] = $value;
- return $this;
- }
-
- public function bindValues($values)
- {
- if (empty($values)) {
- return $this;
- }
- $schema = $this->db->getSchema();
- foreach ($values as $name => $value) {
- if (is_array($value)) {
- $this->_pendingParams[$name] = $value;
- $this->params[$name] = $value[0];
- } elseif ($value instanceof PdoValue) {
- $this->_pendingParams[$name] = [$value->getValue(), $value->getType()];
- $this->params[$name] = $value->getValue();
- } else {
- $type = $schema->getPdoType($value);
- $this->_pendingParams[$name] = [$value, $type];
- $this->params[$name] = $value;
- }
- }
- return $this;
- }
-
- public function query()
- {
- return $this->queryInternal('');
- }
-
- public function queryAll($fetchMode = null)
- {
- return $this->queryInternal('fetchAll', $fetchMode);
- }
-
- public function queryOne($fetchMode = null)
- {
- return $this->queryInternal('fetch', $fetchMode);
- }
-
- public function queryScalar()
- {
- $result = $this->queryInternal('fetchColumn', 0);
- if (is_resource($result) && get_resource_type($result) === 'stream') {
- return stream_get_contents($result);
- }
- return $result;
- }
-
- public function queryColumn()
- {
- return $this->queryInternal('fetchAll', \PDO::FETCH_COLUMN);
- }
-
- public function insert($table, $columns)
- {
- $params = [];
- $sql = $this->db->getQueryBuilder()->insert($table, $columns, $params);
- return $this->setSql($sql)->bindValues($params);
- }
-
- public function batchInsert($table, $columns, $rows)
- {
- $table = $this->db->quoteSql($table);
- $columns = array_map(function ($column) {
- return $this->db->quoteSql($column);
- }, $columns);
- $params = [];
- $sql = $this->db->getQueryBuilder()->batchInsert($table, $columns, $rows, $params);
- $this->setRawSql($sql);
- $this->bindValues($params);
- return $this;
- }
-
- public function upsert($table, $insertColumns, $updateColumns = true, $params = [])
- {
- $sql = $this->db->getQueryBuilder()->upsert($table, $insertColumns, $updateColumns, $params);
- return $this->setSql($sql)->bindValues($params);
- }
-
- public function update($table, $columns, $condition = '', $params = [])
- {
- $sql = $this->db->getQueryBuilder()->update($table, $columns, $condition, $params);
- return $this->setSql($sql)->bindValues($params);
- }
-
- public function delete($table, $condition = '', $params = [])
- {
- $sql = $this->db->getQueryBuilder()->delete($table, $condition, $params);
- return $this->setSql($sql)->bindValues($params);
- }
-
- public function createTable($table, $columns, $options = null)
- {
- $sql = $this->db->getQueryBuilder()->createTable($table, $columns, $options);
- return $this->setSql($sql)->requireTableSchemaRefresh($table);
- }
-
- public function renameTable($table, $newName)
- {
- $sql = $this->db->getQueryBuilder()->renameTable($table, $newName);
- return $this->setSql($sql)->requireTableSchemaRefresh($table);
- }
-
- public function dropTable($table)
- {
- $sql = $this->db->getQueryBuilder()->dropTable($table);
- return $this->setSql($sql)->requireTableSchemaRefresh($table);
- }
-
- public function truncateTable($table)
- {
- $sql = $this->db->getQueryBuilder()->truncateTable($table);
- return $this->setSql($sql);
- }
-
- public function addColumn($table, $column, $type)
- {
- $sql = $this->db->getQueryBuilder()->addColumn($table, $column, $type);
- return $this->setSql($sql)->requireTableSchemaRefresh($table);
- }
-
- public function dropColumn($table, $column)
- {
- $sql = $this->db->getQueryBuilder()->dropColumn($table, $column);
- return $this->setSql($sql)->requireTableSchemaRefresh($table);
- }
-
- public function renameColumn($table, $oldName, $newName)
- {
- $sql = $this->db->getQueryBuilder()->renameColumn($table, $oldName, $newName);
- return $this->setSql($sql)->requireTableSchemaRefresh($table);
- }
-
- public function alterColumn($table, $column, $type)
- {
- $sql = $this->db->getQueryBuilder()->alterColumn($table, $column, $type);
- return $this->setSql($sql)->requireTableSchemaRefresh($table);
- }
-
- public function addPrimaryKey($name, $table, $columns)
- {
- $sql = $this->db->getQueryBuilder()->addPrimaryKey($name, $table, $columns);
- return $this->setSql($sql)->requireTableSchemaRefresh($table);
- }
-
- public function dropPrimaryKey($name, $table)
- {
- $sql = $this->db->getQueryBuilder()->dropPrimaryKey($name, $table);
- return $this->setSql($sql)->requireTableSchemaRefresh($table);
- }
-
- public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
- {
- $sql = $this->db->getQueryBuilder()->addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete, $update);
- return $this->setSql($sql)->requireTableSchemaRefresh($table);
- }
-
- public function dropForeignKey($name, $table)
- {
- $sql = $this->db->getQueryBuilder()->dropForeignKey($name, $table);
- return $this->setSql($sql)->requireTableSchemaRefresh($table);
- }
-
- public function createIndex($name, $table, $columns, $unique = false)
- {
- $sql = $this->db->getQueryBuilder()->createIndex($name, $table, $columns, $unique);
- return $this->setSql($sql)->requireTableSchemaRefresh($table);
- }
-
- public function dropIndex($name, $table)
- {
- $sql = $this->db->getQueryBuilder()->dropIndex($name, $table);
- return $this->setSql($sql)->requireTableSchemaRefresh($table);
- }
-
- public function addUnique($name, $table, $columns)
- {
- $sql = $this->db->getQueryBuilder()->addUnique($name, $table, $columns);
- return $this->setSql($sql)->requireTableSchemaRefresh($table);
- }
-
- public function dropUnique($name, $table)
- {
- $sql = $this->db->getQueryBuilder()->dropUnique($name, $table);
- return $this->setSql($sql)->requireTableSchemaRefresh($table);
- }
-
- public function addCheck($name, $table, $expression)
- {
- $sql = $this->db->getQueryBuilder()->addCheck($name, $table, $expression);
- return $this->setSql($sql)->requireTableSchemaRefresh($table);
- }
-
- public function dropCheck($name, $table)
- {
- $sql = $this->db->getQueryBuilder()->dropCheck($name, $table);
- return $this->setSql($sql)->requireTableSchemaRefresh($table);
- }
-
- public function addDefaultValue($name, $table, $column, $value)
- {
- $sql = $this->db->getQueryBuilder()->addDefaultValue($name, $table, $column, $value);
- return $this->setSql($sql)->requireTableSchemaRefresh($table);
- }
-
- public function dropDefaultValue($name, $table)
- {
- $sql = $this->db->getQueryBuilder()->dropDefaultValue($name, $table);
- return $this->setSql($sql)->requireTableSchemaRefresh($table);
- }
-
- public function resetSequence($table, $value = null)
- {
- $sql = $this->db->getQueryBuilder()->resetSequence($table, $value);
- return $this->setSql($sql);
- }
-
- public function executeResetSequence($table, $value = null)
- {
- return $this->db->getQueryBuilder()->executeResetSequence($table, $value);
- }
-
- public function checkIntegrity($check = true, $schema = '', $table = '')
- {
- $sql = $this->db->getQueryBuilder()->checkIntegrity($check, $schema, $table);
- return $this->setSql($sql);
- }
-
- public function addCommentOnColumn($table, $column, $comment)
- {
- $sql = $this->db->getQueryBuilder()->addCommentOnColumn($table, $column, $comment);
- return $this->setSql($sql)->requireTableSchemaRefresh($table);
- }
-
- public function addCommentOnTable($table, $comment)
- {
- $sql = $this->db->getQueryBuilder()->addCommentOnTable($table, $comment);
- return $this->setSql($sql);
- }
-
- public function dropCommentFromColumn($table, $column)
- {
- $sql = $this->db->getQueryBuilder()->dropCommentFromColumn($table, $column);
- return $this->setSql($sql)->requireTableSchemaRefresh($table);
- }
-
- public function dropCommentFromTable($table)
- {
- $sql = $this->db->getQueryBuilder()->dropCommentFromTable($table);
- return $this->setSql($sql);
- }
-
- public function createView($viewName, $subquery)
- {
- $sql = $this->db->getQueryBuilder()->createView($viewName, $subquery);
- return $this->setSql($sql)->requireTableSchemaRefresh($viewName);
- }
-
- public function dropView($viewName)
- {
- $sql = $this->db->getQueryBuilder()->dropView($viewName);
- return $this->setSql($sql)->requireTableSchemaRefresh($viewName);
- }
-
- public function execute()
- {
- $sql = $this->getSql();
- list($profile, $rawSql) = $this->logQuery(__METHOD__);
- if ($sql == '') {
- return 0;
- }
- $this->prepare(false);
- try {
- $profile and Yii::beginProfile($rawSql, __METHOD__);
- $this->internalExecute($rawSql);
- $n = $this->pdoStatement->rowCount();
- $profile and Yii::endProfile($rawSql, __METHOD__);
- $this->refreshTableSchema();
- return $n;
- } catch (Exception $e) {
- $profile and Yii::endProfile($rawSql, __METHOD__);
- throw $e;
- }
- }
-
- protected function logQuery($category)
- {
- if ($this->db->enableLogging) {
- $rawSql = $this->getRawSql();
- Yii::info($rawSql, $category);
- }
- if (!$this->db->enableProfiling) {
- return [false, isset($rawSql) ? $rawSql : null];
- }
- return [true, isset($rawSql) ? $rawSql : $this->getRawSql()];
- }
-
- protected function queryInternal($method, $fetchMode = null)
- {
- list($profile, $rawSql) = $this->logQuery('yii\db\Command::query');
- if ($method !== '') {
- $info = $this->db->getQueryCacheInfo($this->queryCacheDuration, $this->queryCacheDependency);
- if (is_array($info)) {
-
- $cache = $info[0];
- $rawSql = $rawSql ?: $this->getRawSql();
- $cacheKey = $this->getCacheKey($method, $fetchMode, $rawSql);
- $result = $cache->get($cacheKey);
- if (is_array($result) && isset($result[0])) {
- Yii::debug('Query result served from cache', 'yii\db\Command::query');
- return $result[0];
- }
- }
- }
- $this->prepare(true);
- try {
- $profile and Yii::beginProfile($rawSql, 'yii\db\Command::query');
- $this->internalExecute($rawSql);
- if ($method === '') {
- $result = new DataReader($this);
- } else {
- if ($fetchMode === null) {
- $fetchMode = $this->fetchMode;
- }
- $result = call_user_func_array([$this->pdoStatement, $method], (array) $fetchMode);
- $this->pdoStatement->closeCursor();
- }
- $profile and Yii::endProfile($rawSql, 'yii\db\Command::query');
- } catch (Exception $e) {
- $profile and Yii::endProfile($rawSql, 'yii\db\Command::query');
- throw $e;
- }
- if (isset($cache, $cacheKey, $info)) {
- $cache->set($cacheKey, [$result], $info[1], $info[2]);
- Yii::debug('Saved query result in cache', 'yii\db\Command::query');
- }
- return $result;
- }
-
- protected function getCacheKey($method, $fetchMode, $rawSql)
- {
- return [
- __CLASS__,
- $method,
- $fetchMode,
- $this->db->dsn,
- $this->db->username,
- $rawSql,
- ];
- }
-
- protected function requireTableSchemaRefresh($name)
- {
- $this->_refreshTableName = $name;
- return $this;
- }
-
- protected function refreshTableSchema()
- {
- if ($this->_refreshTableName !== null) {
- $this->db->getSchema()->refreshTableSchema($this->_refreshTableName);
- }
- }
-
- protected function requireTransaction($isolationLevel = null)
- {
- $this->_isolationLevel = $isolationLevel;
- return $this;
- }
-
- protected function setRetryHandler(callable $handler)
- {
- $this->_retryHandler = $handler;
- return $this;
- }
-
- protected function internalExecute($rawSql)
- {
- $attempt = 0;
- while (true) {
- try {
- if (
- ++$attempt === 1
- && $this->_isolationLevel !== false
- && $this->db->getTransaction() === null
- ) {
- $this->db->transaction(function () use ($rawSql) {
- $this->internalExecute($rawSql);
- }, $this->_isolationLevel);
- } else {
- $this->pdoStatement->execute();
- }
- break;
- } catch (\Exception $e) {
- $rawSql = $rawSql ?: $this->getRawSql();
- $e = $this->db->getSchema()->convertException($e, $rawSql);
- if ($this->_retryHandler === null || !call_user_func($this->_retryHandler, $e, $attempt)) {
- throw $e;
- }
- }
- }
- }
-
- protected function reset()
- {
- $this->_sql = null;
- $this->_pendingParams = [];
- $this->params = [];
- $this->_refreshTableName = null;
- $this->_isolationLevel = false;
- $this->_retryHandler = null;
- }
- }
|