Skip to content

Refactoring of batchInsert (for remove using of Quoter) #93

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Sep 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 11 additions & 28 deletions src/DMLQueryBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,11 @@
use Yiisoft\Db\Query\QueryInterface;
use Yiisoft\Db\Schema\QuoterInterface;
use Yiisoft\Db\Schema\SchemaInterface;
use Yiisoft\Strings\NumericHelper;

use function implode;
use function ltrim;
use function strrpos;
use function count;
use function is_string;
use function reset;

final class DMLQueryBuilder extends AbstractDMLQueryBuilder
Expand All @@ -45,45 +43,30 @@ public function batchInsert(string $table, array $columns, iterable|Generator $r
return '';
}

$schema = $this->schema;

if (($tableSchema = $schema->getTableSchema($table)) !== null) {
if (($tableSchema = $this->schema->getTableSchema($table)) !== null) {
$columnSchemas = $tableSchema->getColumns();
} else {
$columnSchemas = [];
}

$values = [];

/** @psalm-var string[][] $rows */
/** @psalm-var array<array-key, array<array-key, string>> $rows */
foreach ($rows as $row) {
$vs = [];
foreach ($row as $i => $value) {
if (isset($columns[$i], $columnSchemas[$columns[$i]])) {
$placeholders = [];
foreach ($row as $index => $value) {
if (isset($columns[$index], $columnSchemas[$columns[$index]])) {
/** @var mixed $value */
$value = $columnSchemas[$columns[$i]]->dbTypecast($value);
$value = $this->getTypecastValue($value, $columnSchemas[$columns[$index]]);
}

if (is_string($value)) {
/** @var mixed $value */
$value = $this->quoter->quoteValue($value);
} elseif (is_float($value)) {
/* ensure type cast always has . as decimal separator in all locales */
$value = NumericHelper::normalize($value);
} elseif ($value === false) {
$value = 0;
} elseif ($value === null) {
$value = 'NULL';
} elseif ($value instanceof ExpressionInterface) {
$value = $this->queryBuilder->buildExpression($value, $params);
if ($value instanceof ExpressionInterface) {
$placeholders[] = $this->queryBuilder->buildExpression($value, $params);
} else {
$placeholders[] = $this->queryBuilder->bindParam($value, $params);
}

/** @var mixed */
$vs[] = $value;
}

/** @psalm-var string[] $vs */
$values[] = '(' . implode(', ', $vs) . ')';
$values[] = '(' . implode(', ', $placeholders) . ')';
}

if (empty($values)) {
Expand Down
26 changes: 19 additions & 7 deletions tests/CommandTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -714,12 +714,19 @@ public function batchInsertSqlProvider(): array
{
$data = $this->batchInsertSqlProviderTrait();

$data['issue11242']['expected'] = 'INSERT ALL INTO "type" ("int_col", "float_col", "char_col") ' .
"VALUES (NULL, NULL, 'Kyiv {{city}}, Ukraine') SELECT 1 FROM SYS.DUAL";
$data['wrongBehavior']['expected'] = 'INSERT ALL INTO "type" ("type"."int_col", "float_col", "char_col") ' .
"VALUES ('', '', 'Kyiv {{city}}, Ukraine') SELECT 1 FROM SYS.DUAL";
$data['batchInsert binds params from expression']['expected'] = 'INSERT ALL INTO "type" ("int_col") ' .
'VALUES (:qp1) SELECT 1 FROM SYS.DUAL';
$data['multirow']['expected'] = 'INSERT ALL INTO "type" ("int_col", "float_col", "char_col", "bool_col") ' .
'VALUES (:qp0, :qp1, :qp2, :qp3) INTO "type" ("int_col", "float_col", "char_col", "bool_col") VALUES (:qp4, :qp5, :qp6, :qp7) SELECT 1 FROM SYS.DUAL';
$data['multirow']['expectedParams'][':qp3'] = '1';
$data['multirow']['expectedParams'][':qp7'] = '0';

$this->changeSqlForOracleBatchInsert($data['issue11242']['expected']);
$data['issue11242']['expectedParams'][':qp3'] = '1';

$this->changeSqlForOracleBatchInsert($data['wrongBehavior']['expected']);
$data['wrongBehavior']['expectedParams'][':qp3'] = '0';

$this->changeSqlForOracleBatchInsert($data['batchInsert binds params from expression']['expected']);
$data['batchInsert binds params from expression']['expectedParams'][':qp3'] = '0';

return $data;
}
Expand All @@ -734,6 +741,7 @@ public function batchInsertSqlProvider(): array
* @param array $values
* @param string $expected
* @param array $expectedParams
* @param int $insertedRow
*
* @throws Exception|InvalidConfigException|NotSupportedException
*
Expand All @@ -744,7 +752,8 @@ public function testBatchInsertSQL(
array $columns,
array $values,
string $expected,
array $expectedParams = []
array $expectedParams = [],
int $insertedRow = 1
): void {
$db = $this->getConnection(true);

Expand All @@ -756,6 +765,9 @@ public function testBatchInsertSQL(

$this->assertSame($expected, $command->getSql());
$this->assertSame($expectedParams, $command->getParams());

$command->execute();
$this->assertEquals($insertedRow, (new Query($db))->from($table)->count());
}

public function testAddDropCheck(): void
Expand Down
15 changes: 15 additions & 0 deletions tests/ConnectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -238,4 +238,19 @@ public function testSettingDefaultAttributes(): void
$this->assertEquals(PDO::ERRMODE_EXCEPTION, $db->getActivePDO()->getAttribute(PDO::ATTR_ERRMODE));
$db->close();
}

public function testLastInsertIdTwoConnection()
{
$db1 = $this->getConnection();
$db2 = $this->getConnection();

$sql = 'INSERT INTO {{profile}}([[description]]) VALUES (\'non duplicate1\')';
$db1->createCommand($sql)->execute();

$sql = 'INSERT INTO {{profile}}([[description]]) VALUES (\'non duplicate2\')';
$db2->createCommand($sql)->execute();

$this->assertNotEquals($db1->getLastInsertID('profile_SEQ'), $db2->getLastInsertID('profile_SEQ'));
$this->assertNotEquals($db2->getLastInsertID('profile_SEQ'), $db1->getLastInsertID('profile_SEQ'));
}
}
23 changes: 7 additions & 16 deletions tests/Provider/QueryBuilderProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,24 +81,15 @@ public function batchInsertProvider(): array
{
$data = (new BaseQueryBuilderProvider($this->getConnection()))->batchInsertProvider();

$data[0][3] = 'INSERT ALL INTO "customer" ("email", "name", "address") ' .
"VALUES ('test@example.com', 'silverfire', 'Kyiv {{city}}, Ukraine') SELECT 1 FROM SYS.DUAL";
$this->changeSqlForOracleBatchInsert($data['simple']['expected']) ;
$this->changeSqlForOracleBatchInsert($data['escape-danger-chars']['expected']) ;
$this->changeSqlForOracleBatchInsert($data['customer3']['expected']) ;
$this->changeSqlForOracleBatchInsert($data['bool-false, bool2-null']['expected']);

$data['escape-danger-chars']['expected'] = 'INSERT ALL INTO "customer" ("address") ' .
"VALUES ('SQL-danger chars are escaped: ''); --') SELECT 1 FROM SYS.DUAL";
$data['wrong']['expected'] = 'INSERT ALL INTO {{%type}} ({{%type}}.[[float_col]], [[time]]) ' .
'VALUES (:qp0, now()) INTO {{%type}} ({{%type}}.[[float_col]], [[time]]) VALUES (:qp1, now()) SELECT 1 FROM SYS.DUAL';

$data[2][3] = 'INSERT ALL INTO "customer" () ' .
"VALUES ('no columns passed') SELECT 1 FROM SYS.DUAL";

$data['bool-false, bool2-null'][1] = ['[[bool_col]]', '[[bool_col2]]'];
$data['bool-false, bool2-null']['expected'] = 'INSERT ALL INTO "type" ([[bool_col]], [[bool_col2]]) ' .
'VALUES (0, NULL) SELECT 1 FROM SYS.DUAL';

$data[3][3] = 'INSERT ALL INTO {{%type}} ({{%type}}.[[float_col]], [[time]]) ' .
'VALUES (NULL, now()) SELECT 1 FROM SYS.DUAL';

$data['bool-false, time-now()']['expected'] = 'INSERT ALL INTO {{%type}} ({{%type}}.[[bool_col]], [[time]]) ' .
'VALUES (0, now()) SELECT 1 FROM SYS.DUAL';
$this->changeSqlForOracleBatchInsert($data['bool-false, time-now()']['expected']);

return $data;
}
Expand Down
10 changes: 8 additions & 2 deletions tests/QueryBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -79,13 +79,19 @@ public function testAddDropUnique(string $sql, Closure $builder): void
* @param array $columns
* @param array $value
* @param string $expected
* @param array $expectedParams
*
* @throws Exception|InvalidArgumentException|InvalidConfigException|NotSupportedException
*/
public function testBatchInsert(string $table, array $columns, array $value, string $expected): void
public function testBatchInsert(string $table, array $columns, array $value, string $expected, array $expectedParams = []): void
{
$params = [];
$db = $this->getConnection();
$this->assertEquals($expected, $db->getQueryBuilder()->batchInsert($table, $columns, $value));

$sql = $db->getQueryBuilder()->batchInsert($table, $columns, $value, $params);

$this->assertEquals($expected, $sql);
$this->assertEquals($expectedParams, $params);
}

/**
Expand Down
5 changes: 5 additions & 0 deletions tests/TestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,4 +65,9 @@ protected function tearDown(): void
$this->profiler
);
}

protected function changeSqlForOracleBatchInsert(string &$str)
{
$str = str_replace('INSERT INTO', 'INSERT ALL INTO', $str) . ' SELECT 1 FROM SYS.DUAL';
}
}