Test Failed
Push — master ( b3e2ff...a8cc09 )
by Wilmer
07:17 queued 03:20
created

DMLQueryBuilder   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 135
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 18
eloc 56
c 3
b 0
f 0
dl 0
loc 135
ccs 58
cts 58
cp 1
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A resetSequence() 0 25 4
C upsert() 0 76 12
A insertWithReturningPks() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Sqlite;
6
7
use JsonException;
8
use Throwable;
9
use Yiisoft\Db\Constraint\Constraint;
10
use Yiisoft\Db\Exception\Exception;
11
use Yiisoft\Db\Exception\InvalidArgumentException;
12
use Yiisoft\Db\Exception\InvalidConfigException;
13
use Yiisoft\Db\Exception\NotSupportedException;
14
use Yiisoft\Db\Expression\Expression;
15
use Yiisoft\Db\Expression\ExpressionInterface;
16
use Yiisoft\Db\Query\QueryInterface;
17
use Yiisoft\Db\QueryBuilder\AbstractDMLQueryBuilder;
0 ignored issues
show
Bug introduced by
The type Yiisoft\Db\QueryBuilder\AbstractDMLQueryBuilder 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...
18
use Yiisoft\Db\QueryBuilder\QueryBuilderInterface;
19
use Yiisoft\Db\Schema\QuoterInterface;
20
use Yiisoft\Db\Schema\SchemaInterface;
21
22
use function implode;
23
use function ltrim;
24
use function reset;
25
26
final class DMLQueryBuilder extends AbstractDMLQueryBuilder
27
{
28 490
    public function __construct(
29
        QueryBuilderInterface $queryBuilder,
30
        private QuoterInterface $quoter,
31
        private SchemaInterface $schema
32
    ) {
33 490
        parent::__construct($queryBuilder, $quoter, $schema);
34
    }
35
36
    /**
37
     * @throws Exception
38
     * @throws InvalidArgumentException
39 5
     * @throws InvalidConfigException
40
     * @throws NotSupportedException
41 5
     */
42
    public function insertWithReturningPks(string $table, QueryInterface|array $columns, array &$params = []): string
43 5
    {
44 1
        throw new NotSupportedException(__METHOD__ . '() is not supported by SQLite.');
45
    }
46
47 4
    /**
48
     * @throws Exception
49 4
     * @throws Throwable
50 1
     */
51
    public function resetSequence(string $tableName, int|string $value = null): string
52
    {
53 3
        $table = $this->schema->getTableSchema($tableName);
54
55 3
        if ($table === null) {
56 2
            throw new InvalidArgumentException("Table not found: '$tableName'.");
57
        }
58 3
59 3
        $sequenceName = $table->getSequenceName();
60 3
61
        if ($sequenceName === null) {
62
            throw new InvalidArgumentException("There is not sequence associated with table '$tableName'.'");
63 3
        }
64
65
        $tableName = $this->quoter->quoteTableName($tableName);
66
67
        if ($value !== null) {
68
            $value = "'" . ((int) $value - 1) . "'";
69 34
        } else {
70
            $pk = $table->getPrimaryKey();
71
            $key = $this->quoter->quoteColumnName(reset($pk));
72
            $value = '(SELECT MAX(' . $key . ') FROM ' . $tableName . ')';
73
        }
74
75
        return 'UPDATE sqlite_sequence SET seq=' . $value . " WHERE name='" . $table->getName() . "'";
76 34
    }
77
78
    /**
79
     * @throws Exception
80
     * @throws InvalidArgumentException
81
     * @throws InvalidConfigException
82
     * @throws JsonException
83 34
     * @throws NotSupportedException
84 34
     */
85 34
    public function upsert(
86 34
        string $table,
87 34
        QueryInterface|array $insertColumns,
88 34
        bool|array $updateColumns,
89
        array &$params
90 34
    ): string {
91 2
        /** @psalm-var Constraint[] $constraints */
92
        $constraints = [];
93
94
        /**
95
         * @psalm-var string[] $insertNames
96
         * @psalm-var string[] $updateNames
97 32
         * @psalm-var array<string, ExpressionInterface|string>|bool $updateColumns
98
         */
99 32
        [$uniqueNames, $insertNames, $updateNames] = $this->prepareUpsertColumns(
100 32
            $table,
101 32
            $insertColumns,
102 32
            $updateColumns,
103
            $constraints
104 32
        );
105 12
106
        if (empty($uniqueNames)) {
107
            return $this->insert($table, $insertColumns, $params);
108 20
        }
109 20
110
        /** @psalm-var string[] $placeholders */
111 20
        [, $placeholders, $values, $params] = $this->prepareInsertValues($table, $insertColumns, $params);
112 20
113
        $insertSql = 'INSERT OR IGNORE INTO '
114 20
            . $this->quoter->quoteTableName($table)
115 20
            . (!empty($insertNames) ? ' (' . implode(', ', $insertNames) . ')' : '')
116 20
            . (!empty($placeholders) ? ' VALUES (' . implode(', ', $placeholders) . ')' : "$values");
117 20
118
        if ($updateColumns === false) {
0 ignored issues
show
introduced by
The condition $updateColumns === false is always false.
Loading history...
119 20
            return $insertSql;
120
        }
121
122 20
        $updateCondition = ['or'];
123 10
        $quotedTableName = $this->quoter->quoteTableName($table);
124 10
125 8
        foreach ($constraints as $constraint) {
126
            $constraintCondition = ['and'];
127 8
            /** @psalm-var string[] $columnsNames */
128 8
            $columnsNames = $constraint->getColumnNames();
129
            foreach ($columnsNames as $name) {
130 8
                $quotedName = $this->quoter->quoteColumnName($name);
131
                $constraintCondition[] = "$quotedTableName.$quotedName=(SELECT $quotedName FROM `EXCLUDED`)";
132
            }
133
            $updateCondition[] = $constraintCondition;
134 20
        }
135 2
136
        if ($updateColumns === true) {
0 ignored issues
show
introduced by
The condition $updateColumns === true is always false.
Loading history...
137
            $updateColumns = [];
138
            foreach ($updateNames as $name) {
139 18
                $quotedName = $this->quoter->quoteColumnName($name);
140 18
141 18
                if (strrpos($quotedName, '.') === false) {
142 10
                    $quotedName = "(SELECT $quotedName FROM `EXCLUDED`)";
143 18
                }
144 18
                $updateColumns[$name] = new Expression($quotedName);
145
            }
146 18
        }
147
148
        if ($updateColumns === []) {
149
            return $insertSql;
150
        }
151
152
        /** @psalm-var array $params */
153
        $updateSql = 'WITH "EXCLUDED" ('
154
            . implode(', ', $insertNames)
155
            . ') AS (' . (!empty($placeholders)
156
                ? 'VALUES (' . implode(', ', $placeholders) . ')'
157
                : ltrim("$values", ' ')) . ') ' .
158
                $this->update($table, $updateColumns, $updateCondition, $params);
159
160
        return "$updateSql; $insertSql;";
161
    }
162
}
163