Passed
Push — master ( 1f4c93...dcd4be )
by Alexander
13:16 queued 10:08
created

DMLQueryBuilder::resetSequence()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 24
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
c 1
b 0
f 0
dl 0
loc 24
ccs 13
cts 13
cp 1
rs 9.8333
cc 4
nc 4
nop 2
crap 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Mysql;
6
7
use JsonException;
8
use Throwable;
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\Query;
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 reset;
24
25
final class DMLQueryBuilder extends AbstractDMLQueryBuilder
26
{
27 356
    public function __construct(
28
        QueryBuilderInterface $queryBuilder,
29
        private QuoterInterface $quoter,
30
        private SchemaInterface $schema
31
    ) {
32 356
        parent::__construct($queryBuilder, $quoter, $schema);
33
    }
34
35
    /**
36
     * Creates a SQL statement for resetting the sequence value of a table's primary key.
37
     *
38
     * The sequence will be reset such that the primary key of the next new row inserted will have the specified value
39
     * or 1.
40
     *
41
     * @param string $tableName the name of the table whose primary key sequence will be reset.
42
     * @param array|int|string|null $value the value for the primary key of the next new row inserted. If this is not
43
     * set, the next new row's primary key will have a value 1.
44
     *
45
     * @throws Exception|InvalidArgumentException|Throwable
46
     *
47
     * @return string the SQL statement for resetting sequence.
48
     */
49 3
    public function resetSequence(string $tableName, array|int|string|null $value = null): string
50
    {
51 3
        $table = $this->schema->getTableSchema($tableName);
52
53 3
        if ($table === null) {
54 1
            throw new InvalidArgumentException("Table not found: $tableName");
55
        }
56
57 2
        $sequenceName = $table->getSequenceName();
58 2
        if ($sequenceName === null) {
59 1
            throw new InvalidArgumentException("There is no sequence associated with table '$tableName'.");
60
        }
61
62 1
        $tableName = $this->quoter->quoteTableName($tableName);
63
64 1
        if ($value !== null) {
65 1
            return 'ALTER TABLE ' . $tableName . ' AUTO_INCREMENT=' . (int)$value . ';';
66
        }
67
68 1
        $pk = $table->getPrimaryKey();
69 1
        $key = (string) reset($pk);
70
71 1
        return "SET @new_autoincrement_value := (SELECT MAX(`$key`) + 1 FROM $tableName);
72
SET @sql = CONCAT('ALTER TABLE $tableName AUTO_INCREMENT =', @new_autoincrement_value);
73
PREPARE autoincrement_stmt FROM @sql;
74
EXECUTE autoincrement_stmt";
75
    }
76
77
    /**
78
     * Creates an SQL statement to insert rows into a database table if they do not already exist (matching unique
79
     * constraints), or update them if they do.
80
     *
81
     * For example,
82
     *
83
     * ```php
84
     * $sql = $queryBuilder->upsert('pages', [
85
     *     'name' => 'Front page',
86
     *     'url' => 'http://example.com/', // url is unique
87
     *     'visits' => 0,
88
     * ], [
89
     *     'visits' => new Expression('visits + 1'),
90
     * ], $params);
91
     * ```
92
     *
93
     * The method will properly escape the table and column names.
94
     *
95
     * @param string $table the table that new rows will be inserted into/updated in.
96
     * @param array|QueryInterface $insertColumns the column data (name => value) to be inserted into the table or
97
     * instance of {@see Query} to perform `INSERT INTO ... SELECT` SQL statement.
98
     * @param array|bool $updateColumns the column data (name => value) to be updated if they already exist. If `true`
99
     * is passed, the column data will be updated to match the insert column data. If `false` is passed, no update will
100
     * be performed if the column data already exists.
101
     * @param array $params the binding parameters that will be generated by this method. They should be bound to the DB
102
     * command later.
103
     *
104
     * @throws Exception|InvalidConfigException|JsonException|NotSupportedException if this is not supported by the
105
     * underlying DBMS.
106
     *
107
     * @return string the resulting SQL.
108
     */
109 18
    public function upsert(
110
        string $table,
111
        QueryInterface|array $insertColumns,
112
        bool|array $updateColumns,
113
        array &$params
114
    ): string {
115 18
        $insertSql = $this->insert($table, $insertColumns, $params);
116
117
        /** @var array $uniqueNames */
118 18
        [$uniqueNames, , $updateNames] = $this->prepareUpsertColumns(
119
            $table,
120
            $insertColumns,
121
            $updateColumns,
122
        );
123
124 18
        if (empty($uniqueNames)) {
125 3
            return $insertSql;
126
        }
127
128 15
        if ($updateColumns === true) {
0 ignored issues
show
introduced by
The condition $updateColumns === true is always false.
Loading history...
129 4
            $updateColumns = [];
130
            /** @var string $name */
131 4
            foreach ($updateNames as $name) {
132 4
                $updateColumns[$name] = new Expression(
133 4
                    'VALUES(' . $this->quoter->quoteColumnName($name) . ')'
134
                );
135
            }
136 11
        } elseif ($updateColumns === false) {
0 ignored issues
show
introduced by
The condition $updateColumns === false is always false.
Loading history...
137 5
            $columnName = (string) reset($uniqueNames);
138 5
            $name = $this->quoter->quoteColumnName($columnName);
139 5
            $updateColumns = [$name => new Expression($this->quoter->quoteTableName($table) . '.' . $name)];
140
        }
141
142
        /**
143
         *  @psalm-var array<array-key, string> $updates
144
         *  @psalm-var array<string, ExpressionInterface|string> $updateColumns
145
         */
146 15
        [$updates, $params] = $this->prepareUpdateSets($table, $updateColumns, $params);
147
148 15
        return $insertSql . ' ON DUPLICATE KEY UPDATE ' . implode(', ', $updates);
149
    }
150
151
    /**
152
     * Prepares a `VALUES` part for an `INSERT` SQL statement.
153
     *
154
     * @param string $table the table that new rows will be inserted into.
155
     * @param array|QueryInterface $columns the column data (name => value) to be inserted into the table or instance of
156
     * {@see Query|Query} to perform INSERT INTO ... SELECT SQL statement.
157
     * @param array $params the binding parameters that will be generated by this method. They should be bound to the DB
158
     * command later.
159
     *
160
     * @throws Exception|InvalidArgumentException|InvalidConfigException|JsonException|NotSupportedException
161
     *
162
     * @return array array of column names, placeholders, values and params.
163
     */
164 53
    protected function prepareInsertValues(string $table, QueryInterface|array $columns, array $params = []): array
165
    {
166
        /**
167
         * @var array $names
168
         * @var array $placeholders
169
         */
170 53
        [$names, $placeholders, $values, $params] = parent::prepareInsertValues($table, $columns, $params);
171
172 50
        if (!$columns instanceof QueryInterface && empty($names)) {
0 ignored issues
show
introduced by
$columns is never a sub-type of Yiisoft\Db\Query\QueryInterface.
Loading history...
173
            $tableSchema = $this->schema->getTableSchema($table);
174
175
            if ($tableSchema !== null) {
176
                $columns = $tableSchema->getColumns();
177
                $columns = !empty($tableSchema->getPrimaryKey())
178
                    ? $tableSchema->getPrimaryKey() : [reset($columns)->getName()];
179
                foreach ($columns as $name) {
180
                    $names[] = $this->quoter->quoteColumnName($name);
181
                    $placeholders[] = 'DEFAULT';
182
                }
183
            }
184
        }
185
186 50
        return [$names, $placeholders, $values, $params];
187
    }
188
}
189