Commit 44c8391d authored by Dries's avatar Dries

- Patch #321100 by hswong3i: empty insert statements are better handled now. Comes with tests.

parent a269b9cc
......@@ -16,6 +16,10 @@ public function execute() {
throw new PDOException('You may not specify the same field to have a value and a schema-default value.');
}
if (count($this->insertFields) + count($this->defaultFields) == 0) {
return NULL;
}
$last_insert_id = 0;
$max_placeholder = 0;
......
......@@ -22,6 +22,10 @@ public function execute() {
throw new PDOException('You may not specify the same field to have a value and a schema-default value.');
}
if (count($this->insertFields) + count($this->defaultFields) == 0) {
return NULL;
}
$schema = drupal_get_schema($this->table);
$stmt = $this->connection->prepareQuery((string)$this);
......
......@@ -382,7 +382,9 @@ public function delay($delay = TRUE) {
* was given multiple sets of values to insert, the return value is
* undefined. If the query is flagged "delayed", then the insert ID
* won't be created until later when the query actually runs so the
* return value is also undefined.
* return value is also undefined. If no fields are specified, this
* method will do nothing and return NULL. That makes it safe to use
* in multi-insert loops.
*/
public function execute() {
......@@ -394,6 +396,10 @@ public function execute() {
throw new PDOException('You may not specify the same field to have a value and a schema-default value.');
}
if (count($this->insertFields) + count($this->defaultFields) == 0) {
return NULL;
}
// Each insert happens in its own query in the degenerate case. However,
// we wrap it in a transaction so that it is atomic where possible. On many
// databases, such as SQLite, this is also a notable performance boost.
......
......@@ -562,6 +562,24 @@ class DatabaseInsertDefaultsTestCase extends DatabaseTestCase {
}
}
/**
* Test that no action will be preformed if no fields are specified.
*/
function testDefaultEmptyInsert() {
try {
$num_records_before = (int) db_query("SELECT COUNT(*) FROM {test}")->fetchField();
$result = db_insert('test')->execute();
$this->assertNull($result, t('Return NULL as no fields are specified.'));
$num_records_after = (int) db_query("SELECT COUNT(*) FROM {test}")->fetchField();
$this->assertIdentical($num_records_before, $num_records_after, t('Do nothing as no fields are specified.'));
}
catch (Exception $e) {
$this->assertTrue(FALSE, $e->getMessage());
}
}
/**
* Test that we can insert fields with values and defaults in the same query.
*/
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment