Test Failed
Pull Request — master (#165)
by Def
17:45 queued 05:56
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
eloc 1
c 1
b 0
f 0
dl 0
loc 6
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 3
crap 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\QueryBuilder\DMLQueryBuilder as AbstractDMLQueryBuilder;
17
use Yiisoft\Db\QueryBuilder\QueryBuilderInterface;
18
use Yiisoft\Db\Query\QueryInterface;
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 459
    public function __construct(
29
        QueryBuilderInterface $queryBuilder,
30
        private QuoterInterface $quoter,
31
        private SchemaInterface $schema
32
    ) {
33 459
        parent::__construct($queryBuilder, $quoter, $schema);
34
    }
35
36
    /**
37
     * @throws Exception|Throwable
38
     */
39 4
    public function resetSequence(string $tableName, int|string $value = null): string
40
    {
41 4
        $table = $this->schema->getTableSchema($tableName);
42
43 4
        if ($table === null) {
44 1
            throw new InvalidArgumentException("Table not found: '$tableName'.");
45
        }
46
47 3
        $sequenceName = $table->getSequenceName();
48
49 3
        if ($sequenceName === null) {
50 1
            throw new InvalidArgumentException("There is not sequence associated with table '$tableName'.'");
51
        }
52
53 2
        $tableName = $this->quoter->quoteTableName($tableName);
54
55 2
        if ($value !== null) {
56 2
            $value = "'" . ((int) $value - 1) . "'";
57
        } else {
58 2
            $pk = $table->getPrimaryKey();
59 2
            $key = $this->quoter->quoteColumnName(reset($pk));
60 2
            $value = '(SELECT MAX(' . $key . ') FROM ' . $tableName . ')';
61
        }
62
63 2
        return 'UPDATE sqlite_sequence SET seq=' . $value . " WHERE name='" . $table->getName() . "'";
64
    }
65
66
    /**
67
     * @throws Exception|InvalidArgumentException|InvalidConfigException|JsonException|NotSupportedException
68
     */
69 19
    public function upsert(
70
        string $table,
71
        QueryInterface|array $insertColumns,
72
        bool|array $updateColumns,
73
        array &$params
74
    ): string {
75
        /** @var Constraint[] $constraints */
76 19
        $constraints = [];
77
78
        /**
79
         * @psalm-var string[] $insertNames
80
         * @psalm-var string[] $updateNames
81
         * @psalm-var array<string, ExpressionInterface|string>|bool $updateColumns
82
         */
83 19
        [$uniqueNames, $insertNames, $updateNames] = $this->prepareUpsertColumns(
84 19
            $table,
85 19
            $insertColumns,
86 19
            $updateColumns,
87 19
            $constraints
88 19
        );
89
90 19
        if (empty($uniqueNames)) {
91 3
            return $this->insert($table, $insertColumns, $params);
92
        }
93
94
        /**
95
         * @psalm-var string[] $placeholders
96
         */
97 16
        [, $placeholders, $values, $params] = $this->prepareInsertValues($table, $insertColumns, $params);
98
99 16
        $insertSql = 'INSERT OR IGNORE INTO '
100 16
            . $this->quoter->quoteTableName($table)
101 16
            . (!empty($insertNames) ? ' (' . implode(', ', $insertNames) . ')' : '')
102 16
            . (!empty($placeholders) ? ' VALUES (' . implode(', ', $placeholders) . ')' : "$values");
103
104 16
        if ($updateColumns === false) {
0 ignored issues
show
introduced by
The condition $updateColumns === false is always false.
Loading history...
105 5
            return $insertSql;
106
        }
107
108 11
        $updateCondition = ['or'];
109 11
        $quotedTableName = $this->quoter->quoteTableName($table);
110
111 11
        foreach ($constraints as $constraint) {
112 11
            $constraintCondition = ['and'];
113
            /** @psalm-var string[] */
114 11
            $columnsNames = $constraint->getColumnNames();
115 11
            foreach ($columnsNames as $name) {
116 11
                $quotedName = $this->quoter->quoteColumnName($name);
117 11
                $constraintCondition[] = "$quotedTableName.$quotedName=(SELECT $quotedName FROM `EXCLUDED`)";
118
            }
119 11
            $updateCondition[] = $constraintCondition;
120
        }
121
122 11
        if ($updateColumns === true) {
0 ignored issues
show
introduced by
The condition $updateColumns === true is always false.
Loading history...
123 5
            $updateColumns = [];
124 5
            foreach ($updateNames as $name) {
125 4
                $quotedName = $this->quoter->quoteColumnName($name);
126
127 4
                if (strrpos($quotedName, '.') === false) {
128 4
                    $quotedName = "(SELECT $quotedName FROM `EXCLUDED`)";
129
                }
130 4
                $updateColumns[$name] = new Expression($quotedName);
131
            }
132
        }
133
134
        if ($updateColumns === []) {
135 11
            return $insertSql;
136 11
        }
137 11
138 5
        /** @var array $params */
139 11
        $updateSql = 'WITH "EXCLUDED" ('
140 11
            . implode(', ', $insertNames)
141
            . ') AS (' . (!empty($placeholders)
142 11
                ? 'VALUES (' . implode(', ', $placeholders) . ')'
143
                : ltrim("$values", ' ')) . ') ' .
144
                $this->update($table, $updateColumns, $updateCondition, $params);
145
146
        return "$updateSql; $insertSql;";
147
    }
148
}
149