Test Failed
Pull Request — dev (#118)
by Def
09:16 queued 06:49
created

DMLQueryBuilder::prepareInsertValues()   A

Complexity

Conditions 6
Paths 4

Size

Total Lines 23
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
eloc 11
c 0
b 0
f 0
dl 0
loc 23
ccs 0
cts 0
cp 0
rs 9.2222
cc 6
nc 4
nop 3
crap 42
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\Query\DMLQueryBuilder as AbstractDMLQueryBuilder;
16
use Yiisoft\Db\Query\Query;
17
use Yiisoft\Db\Query\QueryBuilderInterface;
0 ignored issues
show
Bug introduced by
The type Yiisoft\Db\Query\QueryBuilderInterface 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\Query\QueryInterface;
19
20
use function implode;
21 355
use function reset;
22
23 355
final class DMLQueryBuilder extends AbstractDMLQueryBuilder
24
{
25
    public function __construct(private QueryBuilderInterface $queryBuilder)
26
    {
27
        parent::__construct($queryBuilder);
28
    }
29
30
    /**
31
     * Creates a SQL statement for resetting the sequence value of a table's primary key.
32
     *
33
     * The sequence will be reset such that the primary key of the next new row inserted will have the specified value
34
     * or 1.
35
     *
36
     * @param string $tableName the name of the table whose primary key sequence will be reset.
37
     * @param array|int|string|null $value the value for the primary key of the next new row inserted. If this is not
38
     * set, the next new row's primary key will have a value 1.
39
     *
40 3
     * @throws Exception|InvalidArgumentException|InvalidConfigException|Throwable
41
     *
42 3
     * @return string the SQL statement for resetting sequence.
43
     */
44 3
    public function resetSequence(string $tableName, array|int|string|null $value = null): string
45 1
    {
46
        $table = $this->schema->getTableSchema($tableName);
0 ignored issues
show
Bug Best Practice introduced by
The property schema does not exist on Yiisoft\Db\Mysql\DMLQueryBuilder. Did you maybe forget to declare it?
Loading history...
47 1
48 1
        if ($table === null) {
49 1
            throw new InvalidArgumentException("Table not found: $tableName");
50 1
        }
51 1
52 1
        $sequenceName = $table->getSequenceName();
53 1
        if ($sequenceName === null) {
54
            throw new InvalidArgumentException("There is no sequence associated with table '$tableName'.");
55 1
        }
56
57
        $tableName = $this->quoter->quoteTableName($tableName);
0 ignored issues
show
Bug Best Practice introduced by
The property quoter does not exist on Yiisoft\Db\Mysql\DMLQueryBuilder. Did you maybe forget to declare it?
Loading history...
58 1
59
        if ($value !== null) {
60
            return 'ALTER TABLE ' . $tableName . ' AUTO_INCREMENT=' . (int)$value . ';';
61 2
        }
62 1
63
        $pk = $table->getPrimaryKey();
64
        $key = (string) reset($pk);
65 1
66
        return "SET @new_autoincrement_value := (SELECT MAX(`$key`) + 1 FROM $tableName);
67
SET @sql = CONCAT('ALTER TABLE $tableName AUTO_INCREMENT =', @new_autoincrement_value);
68
PREPARE autoincrement_stmt FROM @sql;
69
EXECUTE autoincrement_stmt";
70
    }
71
72
    /**
73
     * Creates an SQL statement to insert rows into a database table if they do not already exist (matching unique
74
     * constraints), or update them if they do.
75
     *
76
     * For example,
77
     *
78
     * ```php
79
     * $sql = $queryBuilder->upsert('pages', [
80
     *     'name' => 'Front page',
81
     *     'url' => 'http://example.com/', // url is unique
82
     *     'visits' => 0,
83
     * ], [
84
     *     'visits' => new Expression('visits + 1'),
85
     * ], $params);
86
     * ```
87
     *
88
     * The method will properly escape the table and column names.
89
     *
90
     * @param string $table the table that new rows will be inserted into/updated in.
91
     * @param array|QueryInterface $insertColumns the column data (name => value) to be inserted into the table or
92
     * instance of {@see Query} to perform `INSERT INTO ... SELECT` SQL statement.
93
     * @param array|bool $updateColumns the column data (name => value) to be updated if they already exist. If `true`
94
     * is passed, the column data will be updated to match the insert column data. If `false` is passed, no update will
95
     * be performed if the column data already exists.
96
     * @param array $params the binding parameters that will be generated by this method. They should be bound to the DB
97
     * command later.
98
     *
99
     * @throws Exception|InvalidConfigException|JsonException|NotSupportedException if this is not supported by the
100 18
     * underlying DBMS.
101
     *
102
     * @return string the resulting SQL.
103
     */
104
    public function upsert(
105
        string $table,
106 18
        QueryInterface|array $insertColumns,
107
        bool|array $updateColumns,
108
        array &$params
109 18
    ): string {
110
        $insertSql = $this->insert($table, $insertColumns, $params);
111
112
        /** @var array $uniqueNames */
113
        [$uniqueNames, , $updateNames] = $this->prepareUpsertColumns(
0 ignored issues
show
Bug introduced by
The method prepareUpsertColumns() does not exist on Yiisoft\Db\Mysql\DMLQueryBuilder. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

113
        /** @scrutinizer ignore-call */ 
114
        [$uniqueNames, , $updateNames] = $this->prepareUpsertColumns(

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
114
            $table,
115 18
            $insertColumns,
116 3
            $updateColumns,
117
        );
118
119 15
        if (empty($uniqueNames)) {
120 4
            return $insertSql;
121
        }
122 4
123 4
        if ($updateColumns === true) {
0 ignored issues
show
introduced by
The condition $updateColumns === true is always false.
Loading history...
124 4
            $updateColumns = [];
125
            /** @var string $name */
126
            foreach ($updateNames as $name) {
127 11
                $updateColumns[$name] = new Expression(
128 5
                    'VALUES(' . $this->quoter->quoteColumnName($name) . ')'
129 5
                );
130 5
            }
131
        } elseif ($updateColumns === false) {
0 ignored issues
show
introduced by
The condition $updateColumns === false is always false.
Loading history...
132
            $columnName = (string) reset($uniqueNames);
133
            $name = $this->quoter->quoteColumnName($columnName);
134
            $updateColumns = [$name => new Expression($this->quoter->quoteTableName($table) . '.' . $name)];
135
        }
136
137 15
        /**
138
         *  @psalm-var array<array-key, string> $updates
139 15
         *  @psalm-var array<string, ExpressionInterface|string> $updateColumns
140
         */
141
        [$updates, $params] = $this->prepareUpdateSets($table, $updateColumns, $params);
0 ignored issues
show
Bug introduced by
The method prepareUpdateSets() does not exist on Yiisoft\Db\Mysql\DMLQueryBuilder. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

141
        /** @scrutinizer ignore-call */ 
142
        [$updates, $params] = $this->prepareUpdateSets($table, $updateColumns, $params);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
142
143
        return $insertSql . ' ON DUPLICATE KEY UPDATE ' . implode(', ', $updates);
144
    }
145
146
    /**
147
     * Prepares a `VALUES` part for an `INSERT` SQL statement.
148
     *
149
     * @param string $table the table that new rows will be inserted into.
150
     * @param array|QueryInterface $columns the column data (name => value) to be inserted into the table or instance of
151
     * {@see Query|Query} to perform INSERT INTO ... SELECT SQL statement.
152
     * @param array $params the binding parameters that will be generated by this method. They should be bound to the DB
153
     * command later.
154
     *
155
     * @throws Exception|InvalidArgumentException|InvalidConfigException|JsonException|NotSupportedException
156
     *
157
     * @return array array of column names, placeholders, values and params.
158
     */
159
    protected function prepareInsertValues(string $table, QueryInterface|array $columns, array $params = []): array
160
    {
161
        /**
162
         * @var array $names
163
         * @var array $placeholders
164
         */
165
        [$names, $placeholders, $values, $params] = parent::prepareInsertValues($table, $columns, $params);
166
167
        if (!$columns instanceof Query && empty($names)) {
0 ignored issues
show
introduced by
$columns is never a sub-type of Yiisoft\Db\Query\Query.
Loading history...
168
            $tableSchema = $this->schema->getTableSchema($table);
0 ignored issues
show
Bug Best Practice introduced by
The property schema does not exist on Yiisoft\Db\Mysql\DMLQueryBuilder. Did you maybe forget to declare it?
Loading history...
169
170
            if ($tableSchema !== null) {
171
                $columns = $tableSchema->getColumns();
172
                $columns = !empty($tableSchema->getPrimaryKey())
173
                    ? $tableSchema->getPrimaryKey() : [reset($columns)->getName()];
174
                foreach ($columns as $name) {
175
                    $names[] = $this->quoter->quoteColumnName($name);
0 ignored issues
show
Bug Best Practice introduced by
The property quoter does not exist on Yiisoft\Db\Mysql\DMLQueryBuilder. Did you maybe forget to declare it?
Loading history...
176
                    $placeholders[] = 'DEFAULT';
177
                }
178
            }
179
        }
180
181
        return [$names, $placeholders, $values, $params];
182
    }
183
}
184