123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532 |
- <?php
- namespace yii\db\pgsql;
- use yii\base\InvalidArgumentException;
- use yii\db\Constraint;
- use yii\db\Expression;
- use yii\db\ExpressionInterface;
- use yii\db\Query;
- use yii\db\PdoValue;
- use yii\helpers\StringHelper;
- class QueryBuilder extends \yii\db\QueryBuilder
- {
-
- const INDEX_UNIQUE = 'unique';
-
- const INDEX_B_TREE = 'btree';
-
- const INDEX_HASH = 'hash';
-
- const INDEX_GIST = 'gist';
-
- const INDEX_GIN = 'gin';
-
- public $typeMap = [
- Schema::TYPE_PK => 'serial NOT NULL PRIMARY KEY',
- Schema::TYPE_UPK => 'serial NOT NULL PRIMARY KEY',
- Schema::TYPE_BIGPK => 'bigserial NOT NULL PRIMARY KEY',
- Schema::TYPE_UBIGPK => 'bigserial NOT NULL PRIMARY KEY',
- Schema::TYPE_CHAR => 'char(1)',
- Schema::TYPE_STRING => 'varchar(255)',
- Schema::TYPE_TEXT => 'text',
- Schema::TYPE_TINYINT => 'smallint',
- Schema::TYPE_SMALLINT => 'smallint',
- Schema::TYPE_INTEGER => 'integer',
- Schema::TYPE_BIGINT => 'bigint',
- Schema::TYPE_FLOAT => 'double precision',
- Schema::TYPE_DOUBLE => 'double precision',
- Schema::TYPE_DECIMAL => 'numeric(10,0)',
- Schema::TYPE_DATETIME => 'timestamp(0)',
- Schema::TYPE_TIMESTAMP => 'timestamp(0)',
- Schema::TYPE_TIME => 'time(0)',
- Schema::TYPE_DATE => 'date',
- Schema::TYPE_BINARY => 'bytea',
- Schema::TYPE_BOOLEAN => 'boolean',
- Schema::TYPE_MONEY => 'numeric(19,4)',
- Schema::TYPE_JSON => 'jsonb',
- ];
-
- protected function defaultConditionClasses()
- {
- return array_merge(parent::defaultConditionClasses(), [
- 'ILIKE' => 'yii\db\conditions\LikeCondition',
- 'NOT ILIKE' => 'yii\db\conditions\LikeCondition',
- 'OR ILIKE' => 'yii\db\conditions\LikeCondition',
- 'OR NOT ILIKE' => 'yii\db\conditions\LikeCondition',
- ]);
- }
-
- protected function defaultExpressionBuilders()
- {
- return array_merge(parent::defaultExpressionBuilders(), [
- 'yii\db\ArrayExpression' => 'yii\db\pgsql\ArrayExpressionBuilder',
- 'yii\db\JsonExpression' => 'yii\db\pgsql\JsonExpressionBuilder',
- ]);
- }
-
- public function createIndex($name, $table, $columns, $unique = false)
- {
- if ($unique === self::INDEX_UNIQUE || $unique === true) {
- $index = false;
- $unique = true;
- } else {
- $index = $unique;
- $unique = false;
- }
- return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ') .
- $this->db->quoteTableName($name) . ' ON ' .
- $this->db->quoteTableName($table) .
- ($index !== false ? " USING $index" : '') .
- ' (' . $this->buildColumns($columns) . ')';
- }
-
- public function dropIndex($name, $table)
- {
- if (strpos($table, '.') !== false && strpos($name, '.') === false) {
- if (strpos($table, '{{') !== false) {
- $table = preg_replace('/\\{\\{(.*?)\\}\\}/', '\1', $table);
- list($schema, $table) = explode('.', $table);
- if (strpos($schema, '%') === false)
- $name = $schema.'.'.$name;
- else
- $name = '{{'.$schema.'.'.$name.'}}';
- } else {
- list($schema) = explode('.', $table);
- $name = $schema.'.'.$name;
- }
- }
- return 'DROP INDEX ' . $this->db->quoteTableName($name);
- }
-
- public function renameTable($oldName, $newName)
- {
- return 'ALTER TABLE ' . $this->db->quoteTableName($oldName) . ' RENAME TO ' . $this->db->quoteTableName($newName);
- }
-
- public function resetSequence($tableName, $value = null)
- {
- $table = $this->db->getTableSchema($tableName);
- if ($table !== null && $table->sequenceName !== null) {
-
- $sequence = $this->db->quoteTableName($table->sequenceName);
- $tableName = $this->db->quoteTableName($tableName);
- if ($value === null) {
- $key = $this->db->quoteColumnName(reset($table->primaryKey));
- $value = "(SELECT COALESCE(MAX({$key}),0) FROM {$tableName})+1";
- } else {
- $value = (int) $value;
- }
- return "SELECT SETVAL('$sequence',$value,false)";
- } elseif ($table === null) {
- throw new InvalidArgumentException("Table not found: $tableName");
- }
- throw new InvalidArgumentException("There is not sequence associated with table '$tableName'.");
- }
-
- public function checkIntegrity($check = true, $schema = '', $table = '')
- {
- $enable = $check ? 'ENABLE' : 'DISABLE';
- $schema = $schema ?: $this->db->getSchema()->defaultSchema;
- $tableNames = $table ? [$table] : $this->db->getSchema()->getTableNames($schema);
- $viewNames = $this->db->getSchema()->getViewNames($schema);
- $tableNames = array_diff($tableNames, $viewNames);
- $command = '';
- foreach ($tableNames as $tableName) {
- $tableName = $this->db->quoteTableName("{$schema}.{$tableName}");
- $command .= "ALTER TABLE $tableName $enable TRIGGER ALL; ";
- }
-
- $this->db->getMasterPdo()->setAttribute(\PDO::ATTR_EMULATE_PREPARES, true);
- return $command;
- }
-
- public function truncateTable($table)
- {
- return 'TRUNCATE TABLE ' . $this->db->quoteTableName($table) . ' RESTART IDENTITY';
- }
-
- public function alterColumn($table, $column, $type)
- {
- $columnName = $this->db->quoteColumnName($column);
- $tableName = $this->db->quoteTableName($table);
-
-
- if (preg_match('/^(DROP|SET|RESET)\s+/i', $type)) {
- return "ALTER TABLE {$tableName} ALTER COLUMN {$columnName} {$type}";
- }
- $type = 'TYPE ' . $this->getColumnType($type);
- $multiAlterStatement = [];
- $constraintPrefix = preg_replace('/[^a-z0-9_]/i', '', $table . '_' . $column);
- if (preg_match('/\s+DEFAULT\s+(["\']?\w+["\']?)/i', $type, $matches)) {
- $type = preg_replace('/\s+DEFAULT\s+(["\']?\w+["\']?)/i', '', $type);
- $multiAlterStatement[] = "ALTER COLUMN {$columnName} SET DEFAULT {$matches[1]}";
- } else {
-
- $multiAlterStatement[] = "ALTER COLUMN {$columnName} DROP DEFAULT";
- }
- $type = preg_replace('/\s+NOT\s+NULL/i', '', $type, -1, $count);
- if ($count) {
- $multiAlterStatement[] = "ALTER COLUMN {$columnName} SET NOT NULL";
- } else {
-
- $type = preg_replace('/\s+NULL/i', '', $type);
-
- $multiAlterStatement[] = "ALTER COLUMN {$columnName} DROP NOT NULL";
- }
- if (preg_match('/\s+CHECK\s+\((.+)\)/i', $type, $matches)) {
- $type = preg_replace('/\s+CHECK\s+\((.+)\)/i', '', $type);
- $multiAlterStatement[] = "ADD CONSTRAINT {$constraintPrefix}_check CHECK ({$matches[1]})";
- }
- $type = preg_replace('/\s+UNIQUE/i', '', $type, -1, $count);
- if ($count) {
- $multiAlterStatement[] = "ADD UNIQUE ({$columnName})";
- }
-
- array_unshift($multiAlterStatement, "ALTER COLUMN {$columnName} {$type}");
- return 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $multiAlterStatement);
- }
-
- public function insert($table, $columns, &$params)
- {
- return parent::insert($table, $this->normalizeTableRowData($table, $columns), $params);
- }
-
- public function upsert($table, $insertColumns, $updateColumns, &$params)
- {
- $insertColumns = $this->normalizeTableRowData($table, $insertColumns);
- if (!is_bool($updateColumns)) {
- $updateColumns = $this->normalizeTableRowData($table, $updateColumns);
- }
- if (version_compare($this->db->getServerVersion(), '9.5', '<')) {
- return $this->oldUpsert($table, $insertColumns, $updateColumns, $params);
- }
- return $this->newUpsert($table, $insertColumns, $updateColumns, $params);
- }
-
- private function newUpsert($table, $insertColumns, $updateColumns, &$params)
- {
- $insertSql = $this->insert($table, $insertColumns, $params);
- list($uniqueNames, , $updateNames) = $this->prepareUpsertColumns($table, $insertColumns, $updateColumns);
- if (empty($uniqueNames)) {
- return $insertSql;
- }
- if ($updateColumns === false) {
- return "$insertSql ON CONFLICT DO NOTHING";
- }
- if ($updateColumns === true) {
- $updateColumns = [];
- foreach ($updateNames as $name) {
- $updateColumns[$name] = new Expression('EXCLUDED.' . $this->db->quoteColumnName($name));
- }
- }
- list($updates, $params) = $this->prepareUpdateSets($table, $updateColumns, $params);
- return $insertSql . ' ON CONFLICT (' . implode(', ', $uniqueNames) . ') DO UPDATE SET ' . implode(', ', $updates);
- }
-
- private function oldUpsert($table, $insertColumns, $updateColumns, &$params)
- {
-
- list($uniqueNames, $insertNames, $updateNames) = $this->prepareUpsertColumns($table, $insertColumns, $updateColumns, $constraints);
- if (empty($uniqueNames)) {
- return $this->insert($table, $insertColumns, $params);
- }
-
- $schema = $this->db->getSchema();
- if (!$insertColumns instanceof Query) {
- $tableSchema = $schema->getTableSchema($table);
- $columnSchemas = $tableSchema !== null ? $tableSchema->columns : [];
- foreach ($insertColumns as $name => $value) {
-
-
- if (isset($columnSchemas[$name])) {
- $phName = self::PARAM_PREFIX . count($params);
- $params[$phName] = $value;
- $insertColumns[$name] = new Expression("CAST($phName AS {$columnSchemas[$name]->dbType})");
- }
- }
- }
- list(, $placeholders, $values, $params) = $this->prepareInsertValues($table, $insertColumns, $params);
- $updateCondition = ['or'];
- $insertCondition = ['or'];
- $quotedTableName = $schema->quoteTableName($table);
- foreach ($constraints as $constraint) {
- $constraintUpdateCondition = ['and'];
- $constraintInsertCondition = ['and'];
- foreach ($constraint->columnNames as $name) {
- $quotedName = $schema->quoteColumnName($name);
- $constraintUpdateCondition[] = "$quotedTableName.$quotedName=\"EXCLUDED\".$quotedName";
- $constraintInsertCondition[] = "\"upsert\".$quotedName=\"EXCLUDED\".$quotedName";
- }
- $updateCondition[] = $constraintUpdateCondition;
- $insertCondition[] = $constraintInsertCondition;
- }
- $withSql = 'WITH "EXCLUDED" (' . implode(', ', $insertNames)
- . ') AS (' . (!empty($placeholders) ? 'VALUES (' . implode(', ', $placeholders) . ')' : ltrim($values, ' ')) . ')';
- if ($updateColumns === false) {
- $selectSubQuery = (new Query())
- ->select(new Expression('1'))
- ->from($table)
- ->where($updateCondition);
- $insertSelectSubQuery = (new Query())
- ->select($insertNames)
- ->from('EXCLUDED')
- ->where(['not exists', $selectSubQuery]);
- $insertSql = $this->insert($table, $insertSelectSubQuery, $params);
- return "$withSql $insertSql";
- }
- if ($updateColumns === true) {
- $updateColumns = [];
- foreach ($updateNames as $name) {
- $quotedName = $this->db->quoteColumnName($name);
- if (strrpos($quotedName, '.') === false) {
- $quotedName = '"EXCLUDED".' . $quotedName;
- }
- $updateColumns[$name] = new Expression($quotedName);
- }
- }
- list($updates, $params) = $this->prepareUpdateSets($table, $updateColumns, $params);
- $updateSql = 'UPDATE ' . $this->db->quoteTableName($table) . ' SET ' . implode(', ', $updates)
- . ' FROM "EXCLUDED" ' . $this->buildWhere($updateCondition, $params)
- . ' RETURNING ' . $this->db->quoteTableName($table) .'.*';
- $selectUpsertSubQuery = (new Query())
- ->select(new Expression('1'))
- ->from('upsert')
- ->where($insertCondition);
- $insertSelectSubQuery = (new Query())
- ->select($insertNames)
- ->from('EXCLUDED')
- ->where(['not exists', $selectUpsertSubQuery]);
- $insertSql = $this->insert($table, $insertSelectSubQuery, $params);
- return "$withSql, \"upsert\" AS ($updateSql) $insertSql";
- }
-
- public function update($table, $columns, $condition, &$params)
- {
- return parent::update($table, $this->normalizeTableRowData($table, $columns), $condition, $params);
- }
-
- private function normalizeTableRowData($table, $columns)
- {
- if ($columns instanceof Query) {
- return $columns;
- }
- if (($tableSchema = $this->db->getSchema()->getTableSchema($table)) !== null) {
- $columnSchemas = $tableSchema->columns;
- foreach ($columns as $name => $value) {
- if (isset($columnSchemas[$name]) && $columnSchemas[$name]->type === Schema::TYPE_BINARY && is_string($value)) {
- $columns[$name] = new PdoValue($value, \PDO::PARAM_LOB);
- }
- }
- }
- return $columns;
- }
-
- 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 === true) {
- $value = 'TRUE';
- } elseif ($value === false) {
- $value = 'FALSE';
- } 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);
- }
- }
|