Passed
Pull Request — master (#144)
by Wilmer
14:32
created

DMLQueryBuilder::resetSequence()   A

Complexity

Conditions 6
Paths 5

Size

Total Lines 20
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 7.7305

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 10
c 1
b 0
f 0
nc 5
nop 2
dl 0
loc 20
ccs 7
cts 11
cp 0.6364
crap 7.7305
rs 9.2222
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 486
    public function __construct(
30
        private QueryBuilderInterface $queryBuilder,
31
        private QuoterInterface $quoter,
32
        private SchemaInterface $schema
33
    ) {
34 486
        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 1
                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 2
    public function resetSequence(string $tableName, int|string $value = null): string
85
    {
86 2
        $table = $this->schema->getTableSchema($tableName);
87
88 2
        if ($table !== null && ($sequenceName = $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
        if ($table === null) {
99
            throw new InvalidArgumentException("Table not found: '$tableName'.");
100
        }
101
102
        if ($sequenceName === null) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $sequenceName does not seem to be defined for all execution paths leading up to this point.
Loading history...
103
            throw new InvalidArgumentException("There is not sequence associated with table '$tableName'.'");
104
        }
0 ignored issues
show
Bug Best Practice introduced by
The function implicitly returns null when the if condition on line 102 is false. This is incompatible with the type-hinted return string. Consider adding a return statement or allowing null as return value.

For hinted functions/methods where all return statements with the correct type are only reachable via conditions, ?null? gets implicitly returned which may be incompatible with the hinted type. Let?s take a look at an example:

interface ReturnsInt {
    public function returnsIntHinted(): int;
}

class MyClass implements ReturnsInt {
    public function returnsIntHinted(): int
    {
        if (foo()) {
            return 123;
        }
        // here: null is implicitly returned
    }
}
Loading history...
105
    }
106
107
    /**
108
     * @throws Exception|InvalidArgumentException|InvalidConfigException|JsonException|NotSupportedException
109
     */
110 19
    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 19
        $constraints = [];
118
119
        /** @psalm-var string[] $insertNames */
120 19
        [$uniqueNames, $insertNames, $updateNames] = $this->prepareUpsertColumns(
121
            $table,
122
            $insertColumns,
123
            $updateColumns,
124
            $constraints
125
        );
126
127 19
        if (empty($uniqueNames)) {
128 3
            return $this->insert($table, $insertColumns, $params);
129
        }
130
131 16
        $onCondition = ['or'];
132 16
        $quotedTableName = $this->quoter->quoteTableName($table);
133
134 16
        foreach ($constraints as $constraint) {
135 16
            $constraintCondition = ['and'];
136
137 16
            $columnNames = $constraint->getColumnNames() ?? [];
138
139 16
            if (is_array($columnNames)) {
140
                /** @psalm-var string[] $columnNames */
141 16
                foreach ($columnNames as $name) {
142 16
                    $quotedName = $this->quoter->quoteColumnName($name);
143 16
                    $constraintCondition[] = "$quotedTableName.$quotedName=[EXCLUDED].$quotedName";
144
                }
145
            }
146
147 16
            $onCondition[] = $constraintCondition;
148
        }
149
150 16
        $on = $this->queryBuilder->buildCondition($onCondition, $params);
151
152
        /** @psalm-var string[] $placeholders */
153 16
        [, $placeholders, $values, $params] = $this->prepareInsertValues($table, $insertColumns, $params);
154 16
        $mergeSql = 'MERGE ' . $this->quoter->quoteTableName($table) . ' WITH (HOLDLOCK) '
155 16
            . 'USING (' . (!empty($placeholders)
156 8
            ? 'VALUES (' . implode(', ', $placeholders) . ')'
157 16
            : ltrim((string) $values, ' ')) . ') AS [EXCLUDED] (' . implode(', ', $insertNames) . ') ' . "ON ($on)";
158 16
        $insertValues = [];
159
160 16
        foreach ($insertNames as $name) {
161 16
            $quotedName = $this->quoter->quoteColumnName($name);
162
163 16
            if (strrpos($quotedName, '.') === false) {
164 16
                $quotedName = '[EXCLUDED].' . $quotedName;
165
            }
166
167 16
            $insertValues[] = $quotedName;
168
        }
169
170 16
        $insertSql = 'INSERT (' . implode(', ', $insertNames) . ')' . ' VALUES (' . implode(', ', $insertValues) . ')';
171
172 16
        if ($updateColumns === false) {
0 ignored issues
show
introduced by
The condition $updateColumns === false is always false.
Loading history...
173 5
            return "$mergeSql WHEN NOT MATCHED THEN $insertSql;";
174
        }
175
176 11
        if ($updateColumns === true) {
0 ignored issues
show
introduced by
The condition $updateColumns === true is always false.
Loading history...
177 4
            $updateColumns = [];
178
179
            /** @psalm-var string[] $updateNames */
180 4
            foreach ($updateNames as $name) {
181 4
                $quotedName = $this->quoter->quoteColumnName($name);
182 4
                if (strrpos($quotedName, '.') === false) {
183 4
                    $quotedName = '[EXCLUDED].' . $quotedName;
184
                }
185
186 4
                $updateColumns[$name] = new Expression($quotedName);
187
            }
188
        }
189
190
        /**
191
         * @var array $params
192
         * @psalm-var string[] $updates
193
         * @psalm-var array<string, ExpressionInterface|string> $updateColumns
194
         */
195 11
        [$updates, $params] = $this->prepareUpdateSets($table, $updateColumns, $params);
196 11
        $updateSql = 'UPDATE SET ' . implode(', ', $updates);
197
198 11
        return "$mergeSql WHEN MATCHED THEN $updateSql WHEN NOT MATCHED THEN $insertSql;";
199
    }
200
}
201