Use an atomic implementation on sqlite for insertIfNotExist()

This commit is contained in:
Thomas Müller 2015-03-06 14:50:51 +01:00
parent d11f040720
commit 987b683895

View file

@ -19,11 +19,13 @@ class AdapterSqlite extends Adapter {
} }
public function insertIfNotExist($table, $input) { public function insertIfNotExist($table, $input) {
// NOTE: For SQLite we have to use this clumsy approach $fieldList = '`' . implode('`,`', array_keys($input)) . '`';
// otherwise all fieldnames used must have a unique key. $query = "INSERT INTO `$table` ($fieldList) SELECT "
$query = 'SELECT COUNT(*) FROM `' . $table . '` WHERE '; . str_repeat('?,', count($input)-1).'? '
$inserts = array(); . " WHERE NOT EXISTS (SELECT 1 FROM `$table` WHERE ";
foreach ($input as $key => $value) {
$inserts = array_values($input);
foreach($input as $key => $value) {
$query .= '`' . $key . '`'; $query .= '`' . $key . '`';
if (is_null($value)) { if (is_null($value)) {
$query .= ' IS NULL AND '; $query .= ' IS NULL AND ';
@ -33,34 +35,10 @@ class AdapterSqlite extends Adapter {
} }
} }
$query = substr($query, 0, strlen($query) - 5); $query = substr($query, 0, strlen($query) - 5);
$query .= ')';
try { try {
$stmt = $this->conn->prepare($query); return $this->conn->executeUpdate($query, $inserts);
$result = $stmt->execute($inserts);
} catch(\Doctrine\DBAL\DBALException $e) {
$entry = 'DB Error: "'.$e->getMessage() . '"<br />';
$entry .= 'Offending command was: ' . $query . '<br />';
\OC_Log::write('core', $entry, \OC_Log::FATAL);
$l = \OC::$server->getL10N('lib');
throw new \OC\HintException(
$l->t('Database Error'),
$l->t('Please contact your system administrator.'),
0,
$e
);
}
if ($stmt->fetchColumn() === '0') {
$query = 'INSERT INTO `' . $table . '` (`'
. implode('`,`', array_keys($input)) . '`) VALUES('
. str_repeat('?,', count($input)-1).'? ' . ')';
} else {
return 0; //no rows updated
}
try {
$statement = $this->conn->prepare($query);
$result = $statement->execute(array_values($input));
} catch(\Doctrine\DBAL\DBALException $e) { } catch(\Doctrine\DBAL\DBALException $e) {
$entry = 'DB Error: "'.$e->getMessage() . '"<br />'; $entry = 'DB Error: "'.$e->getMessage() . '"<br />';
$entry .= 'Offending command was: ' . $query.'<br />'; $entry .= 'Offending command was: ' . $query.'<br />';
@ -73,7 +51,5 @@ class AdapterSqlite extends Adapter {
$e $e
); );
} }
return $result;
} }
} }