Skip to content

Commit

Permalink
feat: turn insert queries into replace queries
Browse files Browse the repository at this point in the history
  • Loading branch information
mecha committed Feb 13, 2024
1 parent a12fb20 commit 29986fb
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
21 changes: 19 additions & 2 deletions src/Query/InsertQuery.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ class InsertQuery extends Query
}

protected string $into;
protected bool $replace;
/** @var string[] */
protected array $columns;
/** @var list<array<string,mixed>> */
Expand All @@ -35,13 +36,15 @@ public function __construct(
string $into = '',
array $columns = [],
array $values = [],
array $assign = []
array $assign = [],
bool $replace = false
) {
parent::__construct($adapter);
$this->into = $into;
$this->columns = $columns;
$this->values = $values;
$this->assign = $assign;
$this->replace = $replace;
}

/**
Expand Down Expand Up @@ -83,6 +86,19 @@ public function values(array $values): self
return $new;
}

/**
* Changes the INSERT query to a REPLACE query, or vice-versa.
*
* @param bool $replace Whether to use REPLACE instead of INSERT.
* @return self The new instance.
*/
public function replace(bool $replace = true): self
{
$new = clone $this;
$new->replace = $replace;
return $new;
}

/** @inheritDoc */
public function toSql(): string
{
Expand All @@ -99,7 +115,8 @@ public function toSql(): string
$valuesStr = $this->compileInsertValues();
$onDupeKey = $this->compileAssignment('UPDATE');

$result = "INSERT INTO `$table` ($columnsStr) VALUES $valuesStr";
$type = $this->replace ? 'REPLACE' : 'INSERT';
$result = "$type INTO `$table` ($columnsStr) VALUES $valuesStr";

if (!empty($onDupeKey)) {
$result .= ' ON DUPLICATE KEY ' . $onDupeKey;
Expand Down
18 changes: 18 additions & 0 deletions tests/Query/InsertQueryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,15 @@ public function testOnDuplicate()
$this->assertEquals($assign, $this->expose($new)->assign);
}

public function testReplace()
{
$query = new InsertQuery();
$new = $query->replace();

$this->assertNotSame($query, $new);
$this->assertTrue($this->expose($new)->replace);
}

public function provideExecNumRowsAffected()
{
return [
Expand Down Expand Up @@ -150,4 +159,13 @@ public function testCompileOnDuplicateKey()

$this->assertEquals($expected, $actual);
}

public function testCompileReplace()
{
$insert = new InsertQuery(null, 'foo', ['a', 'b'], [[1, 2]], [], true);
$actual = $insert->toSql();
$expected = "REPLACE INTO `foo` (`a`, `b`) VALUES (1, 2)";

$this->assertEquals($expected, $actual);
}
}

0 comments on commit 29986fb

Please sign in to comment.