Skip to content

Commit bbbe6a9

Browse files
committed
Fix insert queries failing with expression objects.
Insert queries should support expression objects as values. This allows geo features from MySQL to be used, and enables other platform specific SQL functions. Refs #4671
1 parent b88a0d8 commit bbbe6a9

File tree

3 files changed

+37
-0
lines changed

3 files changed

+37
-0
lines changed

src/Database/Expression/ValuesExpression.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,9 @@ public function sql(ValueBinder $generator) {
149149
foreach ($this->_values as $row) {
150150
$row = array_merge($defaults, $row);
151151
foreach ($row as $column => $value) {
152+
if ($value instanceof ExpressionInterface) {
153+
$value = $value->sql($generator);
154+
}
152155
$type = $this->typeMap()->type($column);
153156
$generator->bind($i++, $value, $type);
154157
}

tests/TestCase/Database/QueryTest.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2294,6 +2294,27 @@ public function testInsertFailureMixingTypesQueryFirst() {
22942294
->values(['name' => 'mark']);
22952295
}
22962296

2297+
/**
2298+
* Test that insert can use expression objects as values.
2299+
*
2300+
* @return void
2301+
*/
2302+
public function testInsertExpressionValues() {
2303+
$query = new Query($this->connection);
2304+
$query->insert(['title'])
2305+
->into('articles')
2306+
->values(['title' => $query->newExpr("SELECT 'jose'")]);
2307+
2308+
$result = $query->sql();
2309+
$this->assertQuotedQuery(
2310+
"INSERT INTO <articles> \(<title>\) VALUES (?)",
2311+
$result,
2312+
true
2313+
);
2314+
$result = $query->execute();
2315+
$this->assertCount(1, $result);
2316+
}
2317+
22972318
/**
22982319
* Tests that functions are correctly transformed and their parameters are bound
22992320
*

tests/TestCase/ORM/QueryRegressionTest.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -292,6 +292,19 @@ public function testSaveWithCallbacks() {
292292
$this->assertSame($article, $articles->save($article));
293293
}
294294

295+
/**
296+
* Test that save() works with entities containing expressions
297+
* as properties.
298+
*
299+
* @return void
300+
*/
301+
public function testSaveWithExpressionProperty() {
302+
$articles = TableRegistry::get('Articles');
303+
$article = $articles->newEntity();
304+
$article->title = new \Cake\Database\Expression\QueryExpression("SELECT 'jose'");
305+
$this->assertSame($article, $articles->save($article));
306+
}
307+
295308
/**
296309
* Tests that whe saving deep associations for a belongsToMany property,
297310
* data is not removed becuase of excesive associations filtering.

0 commit comments

Comments
 (0)