Passed
Push — master ( 71f0aa...0eda87 )
by Wilmer
18:29 queued 14:41
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 Method

Rating   Name   Duplication   Size   Complexity  
A DMLQueryBuilder::insertWithReturningPks() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Mysql;
6
7
use Yiisoft\Db\Exception\Exception;
8
use Yiisoft\Db\Exception\InvalidArgumentException;
9
use Yiisoft\Db\Exception\InvalidConfigException;
10
use Yiisoft\Db\Exception\NotSupportedException;
11
use Yiisoft\Db\Expression\Expression;
12
use Yiisoft\Db\Expression\ExpressionInterface;
13
use Yiisoft\Db\Query\Query;
14
use Yiisoft\Db\Query\QueryInterface;
15
use Yiisoft\Db\QueryBuilder\AbstractDMLQueryBuilder;
16
17
use function implode;
18
use function reset;
19
20
/**
21
 * Implements a DML (Data Manipulation Language) SQL statements for MySQL, MariaDB.
22
 */
23
final class DMLQueryBuilder extends AbstractDMLQueryBuilder
24
{
25
    /**
26
     * @throws Exception
27
     * @throws NotSupportedException
28
     */
29 1
    public function insertWithReturningPks(string $table, QueryInterface|array $columns, array &$params = []): string
30
    {
31 1
        throw new NotSupportedException(__METHOD__ . ' is not supported by Mysql.');
32
    }
33
34 4
    public function resetSequence(string $tableName, int|string $value = null): string
35
    {
36 4
        $table = $this->schema->getTableSchema($tableName);
37
38 4
        if ($table === null) {
39 1
            throw new InvalidArgumentException("Table not found: '$tableName'.");
40
        }
41
42 3
        $sequenceName = $table->getSequenceName();
43 3
        if ($sequenceName === null) {
44 1
            throw new InvalidArgumentException("There is not sequence associated with table '$tableName'.");
45
        }
46
47 2
        $tableName = $this->quoter->quoteTableName($tableName);
48
49 2
        if ($value !== null) {
50 1
            return 'ALTER TABLE ' . $tableName . ' AUTO_INCREMENT=' . $value . ';';
51
        }
52
53 2
        $pk = $table->getPrimaryKey();
54 2
        $key = (string) reset($pk);
55
56 2
        return "SET @new_autoincrement_value := (SELECT MAX(`$key`) + 1 FROM $tableName);
57 2
SET @sql = CONCAT('ALTER TABLE $tableName AUTO_INCREMENT =', @new_autoincrement_value);
58
PREPARE autoincrement_stmt FROM @sql;
59 2
EXECUTE autoincrement_stmt";
60
    }
61
62 34
    public function upsert(
63
        string $table,
64
        QueryInterface|array $insertColumns,
65
        bool|array $updateColumns,
66
        array &$params
67
    ): string {
68 34
        $insertSql = $this->insert($table, $insertColumns, $params);
69
70
        /** @psalm-var array $uniqueNames */
71 34
        [$uniqueNames, , $updateNames] = $this->prepareUpsertColumns(
72 34
            $table,
73 34
            $insertColumns,
74 34
            $updateColumns,
75 34
        );
76
77 34
        if (empty($uniqueNames)) {
78 2
            return $insertSql;
79
        }
80
81 32
        if ($updateColumns === true) {
0 ignored issues
show
introduced by
The condition $updateColumns === true is always false.
Loading history...
82 10
            $updateColumns = [];
83
            /** @psalm-var string $name */
84 10
            foreach ($updateNames as $name) {
85 8
                $updateColumns[$name] = new Expression(
86 8
                    'VALUES(' . $this->quoter->quoteColumnName($name) . ')'
87 8
                );
88
            }
89
        }
90
91 32
        if (empty($updateColumns)) {
92 14
            return str_replace('INSERT INTO', 'INSERT IGNORE INTO', $insertSql);
93
        }
94
95
        /**
96
         *  @psalm-var array<array-key, string> $updates
97
         *  @psalm-var array<string, ExpressionInterface|string> $updateColumns
98
         */
99 18
        [$updates, $params] = $this->prepareUpdateSets($table, $updateColumns, $params);
100
101 18
        return $insertSql . ' ON DUPLICATE KEY UPDATE ' . implode(', ', $updates);
102
    }
103
104
    /**
105
     * Prepares a `VALUES` part for an `INSERT` SQL statement.
106
     *
107
     * @param string $table The table to insert new rows into.
108
     * @param array|QueryInterface $columns The column data (name => value) to insert into the table or instance of
109
     * {@see Query} to perform `INSERT INTO ... SELECT` SQL statement.
110
     * @param array $params The binding parameters that will be generated by this method.
111
     * They should be bound to the DB command later.
112
     *
113
     * @throws Exception
114
     * @throws InvalidArgumentException
115
     * @throws InvalidConfigException
116
     * @throws NotSupportedException
117
     *
118
     * @return array Array of column names, placeholders, values, and params.
119
     */
120 80
    protected function prepareInsertValues(string $table, QueryInterface|array $columns, array $params = []): array
121
    {
122
        /**
123
         * @psalm-var array $names
124
         * @psalm-var array $placeholders
125
         */
126 80
        [$names, $placeholders, $values, $params] = parent::prepareInsertValues($table, $columns, $params);
127
128 77
        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...
129 2
            $tableSchema = $this->schema->getTableSchema($table);
130
131 2
            if ($tableSchema !== null) {
132 2
                if (!empty($tableSchema->getPrimaryKey())) {
133 2
                    $columns = $tableSchema->getPrimaryKey();
134 2
                    $defaultValue = 'NULL';
135
                } else {
136 1
                    $columns = [current($tableSchema->getColumns())->getName()];
137 1
                    $defaultValue = 'DEFAULT';
138
                }
139 2
                foreach ($columns as $name) {
140 2
                    $names[] = $this->quoter->quoteColumnName($name);
141 2
                    $placeholders[] = $defaultValue;
142
                }
143
            }
144
        }
145
146 77
        return [$names, $placeholders, $values, $params];
147
    }
148
}
149