diff --git a/src/Query/InsertQuery.php b/src/Query/InsertQuery.php index ae802f6..dedc14d 100644 --- a/src/Query/InsertQuery.php +++ b/src/Query/InsertQuery.php @@ -16,6 +16,7 @@ class InsertQuery extends Query } protected string $into; + protected bool $replace; /** @var string[] */ protected array $columns; /** @var list> */ @@ -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; } /** @@ -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 { @@ -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; diff --git a/tests/Query/InsertQueryTest.php b/tests/Query/InsertQueryTest.php index 3aca536..6692a31 100644 --- a/tests/Query/InsertQueryTest.php +++ b/tests/Query/InsertQueryTest.php @@ -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 [ @@ -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); + } }