Permalink
Browse files

Automatically adding RETURNING * to all insert queries generated by the

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 74463fc108c0cc77748f737760a7a66fae8e9438
@@ -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
@@ -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'));
}
}
@@ -1668,7 +1668,7 @@ public function testInsertSimple() {
'body' => 'test insert'
]);
$result = $query->sql();
$this->assertEquals(
$this->assertContains(
'INSERT INTO articles (title, body) VALUES (?, ?)',
$result
);
@@ -1701,7 +1701,7 @@ public function testInsertSparseRow() {
'title' => 'mark',
]);
$result = $query->sql();
$this->assertEquals(
$this->assertContains(
'INSERT INTO articles (title, body) VALUES (?, ?)',
$result
);

0 comments on commit 74463fc

Please sign in to comment.