Commit 14496c8c authored by Nigel McNie's avatar Nigel McNie
Browse files

Added a new function, insert_record_if_not_exists.

This uses the postgres SELECT FOR UPDATE syntax to ensure we don't have a race condition when inserting a record that previously didn't exist. The other database one is a bit more race condition-ey.
parent 26ecd6bd
......@@ -1031,6 +1031,49 @@ function insert_record($table, $dataobject, $primarykey=false, $returnpk=false)
return (integer)$id;
}
/**
* Inserts a record, only if the record does not already exist. Does not error
* if the record does already exist.
*
* @uses $db
* @param string $table The database table to be checked against.
* @param array $dataobject A data object with values for one or more fields in the record
* @param string $primarykey The primary key of the table we are inserting into (almost always "id")
* @param bool $returnpk Should the id of the newly created record entry be returned? If this option is not requested then true/false is returned.
* @throws SQLException
*/
function insert_record_if_not_exists($table, $dataobject, $primarykey=false, $returnpk=false) {
if (is_postgres()) {
$columns = (array)$dataobject;
$field = '*';
$where = array();
foreach ($columns as $key => $value) {
if ($field == '*') {
$field = $key;
}
$where[] = db_quote_identifier($key) . ' = ' . db_quote($value);
}
$where = implode(' AND ', $where);
db_begin();
if (!record_exists_select($table, $where . ' FOR UPDATE')) {
insert_record('artefact_parent_cache', $dataobject);
}
db_commit();
}
else {
// This is race condition-ey. MySQL apparently supports some kind of
// insert or update syntax. Anyone with mysql knowledge is welcome to
// submit a patch to make this better
if (!record_exists('artefact_parent_cache', 'parent', $this->get('parent'), 'artefact', $artefactid)) {
insert_record('artefact_parent_cache', $dataobject);
}
}
}
/**
* Update a record in a table
*
......
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