Passed
Pull Request — master (#144)
by
unknown
20:49 queued 17:02
created

DMLQueryBuilder::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 3
dl 0
loc 6
ccs 2
cts 2
cp 1
crap 1
rs 10
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
        $sequenceName = null;
87 2
        $table = $this->schema->getTableSchema($tableName);
88
89 2
        if ($table !== null && ($sequenceName = $table->getSequenceName()) !== null) {
90 2
            $tableName = $this->quoter->quoteTableName($tableName);
91
92 2
            if ($value === null) {
93 2
                return "DBCC CHECKIDENT ('$tableName', RESEED, 0) WITH NO_INFOMSGS;DBCC CHECKIDENT ('$tableName', RESEED)";
94
            }
95
96 1
            return "DBCC CHECKIDENT ('$tableName', RESEED, $value)";
97
        }
98
99
        if ($table === null) {
100
            throw new InvalidArgumentException("Table not found: '$tableName'.");
101
        }
102
103
        if ($sequenceName === null) {
0 ignored issues
show
introduced by
The condition $sequenceName === null is always true.
Loading history...
104
            throw new InvalidArgumentException("There is not sequence associated with table '$tableName'.'");
105
        }
0 ignored issues
show
Bug Best Practice introduced by
The function implicitly returns null when the if condition on line 103 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...
106
    }
107
108
    /**
109
     * @throws Exception|InvalidArgumentException|InvalidConfigException|JsonException|NotSupportedException
110
     */
111 19
    public function upsert(
112
        string $table,
113
        QueryInterface|array $insertColumns,
114
        bool|array $updateColumns,
115
        array &$params = []
116
    ): string {
117
        /** @psalm-var Constraint[] $constraints */
118 19
        $constraints = [];
119
120
        /** @psalm-var string[] $insertNames */
121 19
        [$uniqueNames, $insertNames, $updateNames] = $this->prepareUpsertColumns(
122
            $table,
123
            $insertColumns,
124
            $updateColumns,
125
            $constraints
126
        );
127
128 19
        if (empty($uniqueNames)) {
129 3
            return $this->insert($table, $insertColumns, $params);
130
        }
131
132 16
        $onCondition = ['or'];
133 16
        $quotedTableName = $this->quoter->quoteTableName($table);
134
135 16
        foreach ($constraints as $constraint) {
136 16
            $constraintCondition = ['and'];
137
138 16
            $columnNames = $constraint->getColumnNames() ?? [];
139
140 16
            if (is_array($columnNames)) {
141
                /** @psalm-var string[] $columnNames */
142 16
                foreach ($columnNames as $name) {
143 16
                    $quotedName = $this->quoter->quoteColumnName($name);
144 16
                    $constraintCondition[] = "$quotedTableName.$quotedName=[EXCLUDED].$quotedName";
145
                }
146
            }
147
148 16
            $onCondition[] = $constraintCondition;
149
        }
150
151 16
        $on = $this->queryBuilder->buildCondition($onCondition, $params);
152
153
        /** @psalm-var string[] $placeholders */
154 16
        [, $placeholders, $values, $params] = $this->prepareInsertValues($table, $insertColumns, $params);
155 16
        $mergeSql = 'MERGE ' . $this->quoter->quoteTableName($table) . ' WITH (HOLDLOCK) '
156 16
            . 'USING (' . (!empty($placeholders)
157 8
            ? 'VALUES (' . implode(', ', $placeholders) . ')'
158 16
            : ltrim((string) $values, ' ')) . ') AS [EXCLUDED] (' . implode(', ', $insertNames) . ') ' . "ON ($on)";
159 16
        $insertValues = [];
160
161 16
        foreach ($insertNames as $name) {
162 16
            $quotedName = $this->quoter->quoteColumnName($name);
163
164 16
            if (strrpos($quotedName, '.') === false) {
165 16
                $quotedName = '[EXCLUDED].' . $quotedName;
166
            }
167
168 16
            $insertValues[] = $quotedName;
169
        }
170
171 16
        $insertSql = 'INSERT (' . implode(', ', $insertNames) . ')' . ' VALUES (' . implode(', ', $insertValues) . ')';
172
173 16
        if ($updateColumns === false) {
0 ignored issues
show
introduced by
The condition $updateColumns === false is always false.
Loading history...
174 5
            return "$mergeSql WHEN NOT MATCHED THEN $insertSql;";
175
        }
176
177 11
        if ($updateColumns === true) {
0 ignored issues
show
introduced by
The condition $updateColumns === true is always false.
Loading history...
178 4
            $updateColumns = [];
179
180
            /** @psalm-var string[] $updateNames */
181 4
            foreach ($updateNames as $name) {
182 4
                $quotedName = $this->quoter->quoteColumnName($name);
183 4
                if (strrpos($quotedName, '.') === false) {
184 4
                    $quotedName = '[EXCLUDED].' . $quotedName;
185
                }
186
187 4
                $updateColumns[$name] = new Expression($quotedName);
188
            }
189
        }
190
191
        /**
192
         * @var array $params
193
         * @psalm-var string[] $updates
194
         * @psalm-var array<string, ExpressionInterface|string> $updateColumns
195
         */
196 11
        [$updates, $params] = $this->prepareUpdateSets($table, $updateColumns, $params);
197 11
        $updateSql = 'UPDATE SET ' . implode(', ', $updates);
198
199 11
        return "$mergeSql WHEN MATCHED THEN $updateSql WHEN NOT MATCHED THEN $insertSql;";
200
    }
201
}
202