Passed
Pull Request — master (#126)
by Wilmer
25:49 queued 21:45
created

DMLQueryBuilder   A

Complexity

Total Complexity 26

Size/Duplication

Total Lines 166
Duplicated Lines 0 %

Test Coverage

Coverage 98.61%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 73
dl 0
loc 166
ccs 71
cts 72
cp 0.9861
rs 10
c 1
b 0
f 0
wmc 26

4 Methods

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