function insertUpdate($table, $rows, $primary) {
$fields = fields($table);
+ $update = array();
+ $where = array();
+ $set = reset($rows);
+ $columns = "c" . implode(", c", range(1, count($set)));
+ $c = 0;
+ foreach ($set as $key => $val) {
+ $c++;
+ $name = idf_unescape($key);
+ if (!$fields[$name]["auto_increment"]) {
+ $update[] = "$key = c$c";
+ }
+ if (isset($primary[$name])) {
+ $where[] = "$key = c$c";
+ }
+ }
$values = array();
foreach ($rows as $set) {
- $update = array();
- $where = array();
- $columns = "c" . implode(", c", range(1, count($set)));
- $c = 0;
- foreach ($set as $key => $val) {
- $c++;
- $name = idf_unescape($key);
- if (!$fields[$name]["auto_increment"]) {
- $update[] = "$key = c$c";
- }
- if (isset($primary[$name])) {
- $where[] = "$key = c$c";
- }
- }
$values[] = "(" . implode(", ", $set) . ")";
}
queries("SET IDENTITY_INSERT " . table($table) . " ON");
$return = queries("MERGE " . table($table) . " USING (VALUES\n\t" . implode(",\n\t", $values) . "\n) AS source ($columns) ON " . implode(" AND ", $where) //! source, c1 - possible conflict
- . "\nWHEN MATCHED THEN UPDATE SET " . implode(", ", $update)
+ . ($update ? "\nWHEN MATCHED THEN UPDATE SET " . implode(", ", $update) : "")
. "\nWHEN NOT MATCHED THEN INSERT (" . implode(", ", array_keys($set)) . ") VALUES ($columns);" // ; is mandatory
);
queries("SET IDENTITY_INSERT " . table($table) . " OFF");