Test Failed
Pull Request — master (#175)
by Def
29:08 queued 25:21
created

DMLQueryBuilder::insertEx()   B

Complexity

Conditions 9
Paths 56

Size

Total Lines 39
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 23
CRAP Score 9

Importance

Changes 0
Metric Value
cc 9
eloc 22
c 0
b 0
f 0
nc 56
nop 3
dl 0
loc 39
ccs 23
cts 23
cp 1
crap 9
rs 8.0555
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\QueryBuilder\DMLQueryBuilder as AbstractDMLQueryBuilder;
16
use Yiisoft\Db\QueryBuilder\QueryBuilderInterface;
17
use Yiisoft\Db\Query\QueryInterface;
18
use Yiisoft\Db\Schema\QuoterInterface;
19
use Yiisoft\Db\Schema\SchemaInterface;
20
21
use function implode;
22
use function in_array;
23
use function ltrim;
24
use function strrpos;
25
use function is_array;
26
27
final class DMLQueryBuilder extends AbstractDMLQueryBuilder
28
{
29 518
    public function __construct(
30
        private QueryBuilderInterface $queryBuilder,
31
        private QuoterInterface $quoter,
32
        private SchemaInterface $schema
33
    ) {
34 518
        parent::__construct($queryBuilder, $quoter, $schema);
35
    }
36
37
    /**
38
     * @throws Exception|InvalidArgumentException|InvalidConfigException|NotSupportedException
39
     */
40 11
    public function insertWithReturningPks(string $table, QueryInterface|array $columns, array &$params = []): string
41
    {
42
        /**
43
         * @psalm-var string[] $names
44
         * @psalm-var string[] $placeholders
45
         */
46 11
        [$names, $placeholders, $values, $params] = $this->prepareInsertValues($table, $columns, $params);
47
48
49 11
        $createdCols = $insertedCols = [];
50 11
        $tableSchema = $this->schema->getTableSchema($table);
51 11
        $returnColumns = $tableSchema?->getColumns() ?? [];
52 11
        foreach ($returnColumns as $returnColumn) {
53 11
            if ($returnColumn->isComputed()) {
54 1
                continue;
55
            }
56
57 11
            $dbType = $returnColumn->getDbType();
58 11
            if (in_array($dbType, ['char', 'varchar', 'nchar', 'nvarchar', 'binary', 'varbinary'])) {
59 1
                $dbType .= '(MAX)';
60
            }
61 11
            if ($returnColumn->getDbType() === Schema::TYPE_TIMESTAMP) {
62 3
                $dbType = $returnColumn->isAllowNull() ? 'varbinary(8)' : 'binary(8)';
63
            }
64
65 11
            $quotedName = $this->quoter->quoteColumnName($returnColumn->getName());
66 11
            $createdCols[] = $quotedName . ' ' . $dbType . ' ' . ($returnColumn->isAllowNull() ? 'NULL' : '');
67 11
            $insertedCols[] = 'INSERTED.' . $quotedName;
68
        }
69
70 11
        $sql = 'INSERT INTO '
71 11
            . $this->quoter->quoteTableName($table)
72 11
            . (!empty($names) ? ' (' . implode(', ', $names) . ')' : '')
73 11
            . ' OUTPUT ' . implode(',', $insertedCols) . ' INTO @temporary_inserted'
74 11
            . (!empty($placeholders) ? ' VALUES (' . implode(', ', $placeholders) . ')' : (string) $values);
75
76
77 11
        return 'SET NOCOUNT ON;DECLARE @temporary_inserted TABLE (' . implode(', ', $createdCols) . ');'
78 11
            . $sql . ';SELECT * FROM @temporary_inserted;';
79
    }
80
81
    /**
82
     * @throws InvalidArgumentException
83
     */
84 5
    public function resetSequence(string $tableName, int|string $value = null): string
85
    {
86 5
        $table = $this->schema->getTableSchema($tableName);
87
88 5
        if ($table === null) {
89 1
            throw new InvalidArgumentException("Table not found: '$tableName'.");
90
        }
91
92 4
        $sequenceName = $table->getSequenceName();
93
94 4
        if ($sequenceName === null) {
95 1
            throw new InvalidArgumentException("There is not sequence associated with table '$tableName'.'");
96
        }
97
98 3
        $tableName = $this->quoter->quoteTableName($tableName);
99
100 3
        if ($value === null) {
101 3
            return "DBCC CHECKIDENT ('$tableName', RESEED, 0) WITH NO_INFOMSGS;DBCC CHECKIDENT ('$tableName', RESEED)";
102
        }
103
104 1
        return "DBCC CHECKIDENT ('$tableName', RESEED, $value)";
105
    }
106
107
    /**
108
     * @throws Exception|InvalidArgumentException|InvalidConfigException|JsonException|NotSupportedException
109
     */
110 35
    public function upsert(
111
        string $table,
112
        QueryInterface|array $insertColumns,
113
        bool|array $updateColumns,
114
        array &$params = []
115
    ): string {
116
        /** @psalm-var Constraint[] $constraints */
117 35
        $constraints = [];
118
119
        /** @psalm-var string[] $insertNames */
120 35
        [$uniqueNames, $insertNames, $updateNames] = $this->prepareUpsertColumns(
121 35
            $table,
122 35
            $insertColumns,
123 35
            $updateColumns,
124 35
            $constraints
125 35
        );
126
127 35
        if (empty($uniqueNames)) {
128 2
            return $this->insert($table, $insertColumns, $params);
129
        }
130
131 33
        $onCondition = ['or'];
132 33
        $quotedTableName = $this->quoter->quoteTableName($table);
133
134 33
        foreach ($constraints as $constraint) {
135 33
            $constraintCondition = ['and'];
136
137 33
            $columnNames = $constraint->getColumnNames() ?? [];
138
139 33
            if (is_array($columnNames)) {
140
                /** @psalm-var string[] $columnNames */
141 33
                foreach ($columnNames as $name) {
142 33
                    $quotedName = $this->quoter->quoteColumnName($name);
143 33
                    $constraintCondition[] = "$quotedTableName.$quotedName=[EXCLUDED].$quotedName";
144
                }
145
            }
146
147 33
            $onCondition[] = $constraintCondition;
148
        }
149
150 33
        $on = $this->queryBuilder->buildCondition($onCondition, $params);
151
152
        /** @psalm-var string[] $placeholders */
153 33
        [, $placeholders, $values, $params] = $this->prepareInsertValues($table, $insertColumns, $params);
154 33
        $mergeSql = 'MERGE ' . $this->quoter->quoteTableName($table) . ' WITH (HOLDLOCK) '
155 33
            . 'USING (' . (!empty($placeholders)
156 20
            ? 'VALUES (' . implode(', ', $placeholders) . ')'
157 33
            : ltrim((string) $values, ' ')) . ') AS [EXCLUDED] (' . implode(', ', $insertNames) . ') ' . "ON ($on)";
158 33
        $insertValues = [];
159
160 33
        foreach ($insertNames as $name) {
161 33
            $quotedName = $this->quoter->quoteColumnName($name);
162
163 33
            if (strrpos($quotedName, '.') === false) {
164 33
                $quotedName = '[EXCLUDED].' . $quotedName;
165
            }
166
167 33
            $insertValues[] = $quotedName;
168
        }
169
170 33
        $insertSql = 'INSERT (' . implode(', ', $insertNames) . ')' . ' VALUES (' . implode(', ', $insertValues) . ')';
171
172 33
        if ($updateNames === []) {
0 ignored issues
show
introduced by
The condition $updateNames === array() is always false.
Loading history...
173
            /** there are no columns to update */
174 2
            $updateColumns = false;
175
        }
176
177 33
        if ($updateColumns === false) {
0 ignored issues
show
introduced by
The condition $updateColumns === false is always false.
Loading history...
178 14
            return "$mergeSql WHEN NOT MATCHED THEN $insertSql;";
179
        }
180
181 19
        if ($updateColumns === true) {
0 ignored issues
show
introduced by
The condition $updateColumns === true is always false.
Loading history...
182 8
            $updateColumns = [];
183
184
            /** @psalm-var string[] $updateNames */
185 8
            foreach ($updateNames as $name) {
186 8
                $quotedName = $this->quoter->quoteColumnName($name);
187 8
                if (strrpos($quotedName, '.') === false) {
188 8
                    $quotedName = '[EXCLUDED].' . $quotedName;
189
                }
190
191 8
                $updateColumns[$name] = new Expression($quotedName);
192
            }
193
        }
194
195
        /**
196
         * @var array $params
197
         * @psalm-var string[] $updates
198
         * @psalm-var array<string, ExpressionInterface|string> $updateColumns
199
         */
200 19
        [$updates, $params] = $this->prepareUpdateSets($table, $updateColumns, $params);
201 19
        $updateSql = 'UPDATE SET ' . implode(', ', $updates);
202
203 19
        return "$mergeSql WHEN MATCHED THEN $updateSql WHEN NOT MATCHED THEN $insertSql;";
204
    }
205
}
206