Passed
Branch master (796db2)
by Wilmer
06:48 queued 02:23
created

DMLQueryBuilder::truncateTable()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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