Test Failed
Pull Request — dev (#73)
by Def
04:16
created

DMLQueryBuilder   A

Complexity

Total Complexity 23

Size/Duplication

Total Lines 154
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 75
c 1
b 0
f 0
dl 0
loc 154
ccs 68
cts 68
cp 1
rs 10
wmc 23

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
C upsert() 0 89 12
A resetSequence() 0 19 4
A insertEx() 0 29 6
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Mssql;
6
7
use JsonException;
8
use Yiisoft\Db\Constraint\Constraint;
9
use Yiisoft\Db\Exception\Exception;
10
use Yiisoft\Db\Exception\InvalidArgumentException;
11
use Yiisoft\Db\Exception\InvalidConfigException;
12
use Yiisoft\Db\Exception\NotSupportedException;
13
use Yiisoft\Db\Expression\Expression;
14
use Yiisoft\Db\Expression\ExpressionInterface;
15
use Yiisoft\Db\Query\DMLQueryBuilder as AbstractDMLQueryBuilder;
16
use Yiisoft\Db\Query\QueryBuilderInterface;
0 ignored issues
show
Bug introduced by
The type Yiisoft\Db\Query\QueryBuilderInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
17
use Yiisoft\Db\Query\QueryInterface;
18
19
final class DMLQueryBuilder extends AbstractDMLQueryBuilder
20
{
21 366
    public function __construct(private QueryBuilderInterface $queryBuilder)
22
    {
23 366
        parent::__construct($queryBuilder);
24
    }
25
26
    /**
27
     * @throws Exception|InvalidArgumentException|InvalidConfigException|NotSupportedException
28
     */
29 30
    public function insertEx(string $table, QueryInterface|array $columns, array &$params = []): string
30
    {
31 30
        /**
32
         * @psalm-var string[] $names
33
         * @psalm-var string[] $placeholders
34
         */
35
        [$names, $placeholders, $values, $params] = $this->queryBuilder->prepareInsertValues($table, $columns, $params);
36
37 30
        $sql = 'INSERT INTO '
38
            . $this->queryBuilder->quoter()->quoteTableName($table)
39 27
            . (!empty($names) ? ' (' . implode(', ', $names) . ')' : '')
40 27
            . ' OUTPUT INSERTED.* INTO @temporary_inserted'
41 27
            . (!empty($placeholders) ? ' VALUES (' . implode(', ', $placeholders) . ')' : (string) $values);
42
43 27
        $cols = [];
44
        $tableSchema = $this->queryBuilder->schema()->getTableSchema($table);
45 27
        $returnColumns = $tableSchema?->getColumns() ?? [];
46
        foreach($returnColumns as $returnColumn) {
47 27
            $cols[] = $this->queryBuilder->quoter()->quoteColumnName($returnColumn->getName()) . ' '
48 27
                . $returnColumn->getDbType()
49 27
                . (in_array(
50 27
                    $returnColumn->getDbType(),
51 27
                    ['char', 'varchar', 'nchar', 'nvarchar', 'binary', 'varbinary']
52 27
                ) ? '(MAX)' : '')
53
                . ' ' . ($returnColumn->isAllowNull() ? 'NULL' : '');
54 27
        }
55 27
56
        return 'SET NOCOUNT ON;DECLARE @temporary_inserted TABLE (' . implode(', ', $cols) . ');'
57
            . $sql . ';SELECT * FROM @temporary_inserted';
58
    }
59 27
60
    public function resetSequence(string $tableName, mixed $value = null): string
61
    {
62
        $table = $this->queryBuilder->schema()->getTableSchema($tableName);
63 2
64
        if ($table !== null && $table->getSequenceName() !== null) {
65 2
            $tableName = $this->queryBuilder->quoter()->quoteTableName($tableName);
66
67 2
            if ($value === null) {
68 1
                $pk = $table->getPrimaryKey();
69
                $key = $this->queryBuilder->quoter()->quoteColumnName(reset($pk));
70 1
                $value = "(SELECT COALESCE(MAX($key),0) FROM $tableName)+1";
71 1
            } else {
72 1
                $value = (int)$value;
73 1
            }
74
75 1
            return "DBCC CHECKIDENT ('$tableName', RESEED, $value)";
76
        }
77
78 1
        throw new InvalidArgumentException("There is not sequence associated with table '$tableName'.");
79
    }
80
81 1
    /**
82
     * @throws Exception|InvalidArgumentException|InvalidConfigException|JsonException|NotSupportedException
83
     */
84
    public function upsert(
85
        string $table,
86
        QueryInterface|array $insertColumns,
87 19
        bool|array $updateColumns,
88
        array &$params = []
89
    ): string {
90
        /** @psalm-var Constraint[] $constraints */
91
        $constraints = [];
92
93
        /** @psalm-var string[] $insertNames */
94 19
        [$uniqueNames, $insertNames, $updateNames] = $this->queryBuilder->prepareUpsertColumns(
95
            $table,
96
            $insertColumns,
97 19
            $updateColumns,
98
            $constraints
99
        );
100
101
        if (empty($uniqueNames)) {
102
            return $this->insert($table, $insertColumns, $params);
103
        }
104 19
105 3
        $onCondition = ['or'];
106
        $quotedTableName = $this->queryBuilder->quoter()->quoteTableName($table);
107
108 16
        foreach ($constraints as $constraint) {
109 16
            $constraintCondition = ['and'];
110
111 16
            $columnNames = $constraint->getColumnNames() ?? [];
112 16
113
            if (is_array($columnNames)) {
114 16
                /** @psalm-var string[] $columnNames */
115
                foreach ($columnNames as $name) {
116 16
                    $quotedName = $this->queryBuilder->quoter()->quoteColumnName($name);
117
                    $constraintCondition[] = "$quotedTableName.$quotedName=[EXCLUDED].$quotedName";
118 16
                }
119 16
            }
120 16
121
            $onCondition[] = $constraintCondition;
122
        }
123
124 16
        $on = $this->queryBuilder->buildCondition($onCondition, $params);
125
126
        /** @psalm-var string[] $placeholders */
127 16
        [, $placeholders, $values, $params] = $this->queryBuilder->prepareInsertValues($table, $insertColumns, $params);
128
        $mergeSql = 'MERGE ' . $this->queryBuilder->quoter()->quoteTableName($table) . ' WITH (HOLDLOCK) '
129
            . 'USING (' . (!empty($placeholders)
130 16
            ? 'VALUES (' . implode(', ', $placeholders) . ')'
131 16
            : ltrim((string) $values, ' ')) . ') AS [EXCLUDED] (' . implode(', ', $insertNames) . ') ' . "ON ($on)";
132 16
        $insertValues = [];
133 8
134 16
        foreach ($insertNames as $name) {
135 16
            $quotedName = $this->queryBuilder->quoter()->quoteColumnName($name);
136
137 16
            if (strrpos($quotedName, '.') === false) {
138 16
                $quotedName = '[EXCLUDED].' . $quotedName;
139
            }
140 16
141 16
            $insertValues[] = $quotedName;
142
        }
143
144 16
        $insertSql = 'INSERT (' . implode(', ', $insertNames) . ')' . ' VALUES (' . implode(', ', $insertValues) . ')';
145
146
        if ($updateColumns === false) {
0 ignored issues
show
introduced by
The condition $updateColumns === false is always false.
Loading history...
147 16
            return "$mergeSql WHEN NOT MATCHED THEN $insertSql;";
148
        }
149 16
150 5
        if ($updateColumns === true) {
0 ignored issues
show
introduced by
The condition $updateColumns === true is always false.
Loading history...
151
            $updateColumns = [];
152
153 11
            /** @psalm-var string[] $updateNames */
154 4
            foreach ($updateNames as $name) {
155
                $quotedName = $this->queryBuilder->quoter()->quoteColumnName($name);
156
                if (strrpos($quotedName, '.') === false) {
157 4
                    $quotedName = '[EXCLUDED].' . $quotedName;
158 4
                }
159 4
160 4
                $updateColumns[$name] = new Expression($quotedName);
161
            }
162
        }
163 4
164
        /**
165
         * @var array $params
166
         * @psalm-var string[] $updates
167
         * @psalm-var array<string, ExpressionInterface|string> $updateColumns
168
         */
169
        [$updates, $params] = $this->queryBuilder->prepareUpdateSets($table, $updateColumns, $params);
170
        $updateSql = 'UPDATE SET ' . implode(', ', $updates);
171
172 11
        return "$mergeSql WHEN MATCHED THEN $updateSql WHEN NOT MATCHED THEN $insertSql;";
173 11
    }
174
}
175