Skip to content

Commit

Permalink
Automatically adding RETURNING * to all insert queries generated by the
Browse files Browse the repository at this point in the history
postgres dirver. This will help significanlty in getting the correct las
insert id regardless of the table or sequence used
  • Loading branch information
lorenzo committed Oct 21, 2013
1 parent af20284 commit 74463fc
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 2 deletions.
14 changes: 14 additions & 0 deletions Cake/Database/Dialect/PostgresDialectTrait.php
Expand Up @@ -55,6 +55,20 @@ protected function _selectQueryTranslator($query) {
return $query;
}

/**
* Modifies the original insert query to append a "RETURNING *" epilogue
* so that the latest insert id can be retrieved
*
* @param Cake\Database\Query $query
* @return Cake\Database\Query
*/
protected function _insertQueryTranslator($query) {
if (!$query->clause('append')) {
$query->append('RETURNING *');
}
return $query;
}

/**
* Returns an dictionary of expressions to be transformed when compiling a Query
* to SQL. Array keys are method names to be called in this class
Expand Down
28 changes: 28 additions & 0 deletions Cake/Test/TestCase/Database/Driver/PostgresTest.php
Expand Up @@ -134,4 +134,32 @@ public function testConnectionConfigCustom() {
$driver->connect();
}

/**
* Tests that insert queries get a "RETURNING *" string at the end
*
* @return void
*/
public function testInsertReturning() {
$driver = $this->getMock(
'Cake\Database\Driver\Postgres',
['_connect', 'connection'],
[['dsn' => 'foo']]
);
$connection = $this->getMock(
'\Cake\Database\Connection',
['connect'],
[['log' => false]]
);
$query = new \Cake\Database\Query($connection);
$query->insert('articles', ['id', 'title'])->values([1, 'foo']);
$translator = $driver->queryTranslator('insert');
$query = $translator($query);
$this->assertEquals('RETURNING *', $query->clause('append'));

$query = new \Cake\Database\Query($connection);
$query->insert('articles', ['id', 'title'])->values([1, 'foo'])->append('FOO');
$query = $translator($query);
$this->assertEquals('FOO', $query->clause('append'));
}

}
4 changes: 2 additions & 2 deletions Cake/Test/TestCase/Database/QueryTest.php
Expand Up @@ -1668,7 +1668,7 @@ public function testInsertSimple() {
'body' => 'test insert'
]);
$result = $query->sql();
$this->assertEquals(
$this->assertContains(
'INSERT INTO articles (title, body) VALUES (?, ?)',
$result
);
Expand Down Expand Up @@ -1701,7 +1701,7 @@ public function testInsertSparseRow() {
'title' => 'mark',
]);
$result = $query->sql();
$this->assertEquals(
$this->assertContains(
'INSERT INTO articles (title, body) VALUES (?, ?)',
$result
);
Expand Down

0 comments on commit 74463fc

Please sign in to comment.