-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathUpsert.swift
More file actions
53 lines (39 loc) · 1.5 KB
/
Upsert.swift
File metadata and controls
53 lines (39 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//
// Upsert.swift
// PostgresStORM
//
// Created by Jonathan Guthrie on 2016-09-24.
//
//
import StORM
import PerfectLogger
/// An extention ot the main class that provides MySQL-specific "ON CONFLICT UPDATE" functionality.
extension MySQLStORM {
/// Inserts the row with the specified data, on conflict (conflickkeys columns) it will perform an update.
/// Specify matching arrays of columns and parameters, and an array of conflict key columns.
public func upsert(cols: [String], params: [Any], conflictkeys: [String]) throws {
var paramsString = [String]()
var upsertParamsString = [String]()
var substString = [String]()
var upsertString = [String]()
for i in 0..<params.count {
paramsString.append(String(describing: params[i]))
substString.append("?")
if i >= conflictkeys.count {
upsertString.append("\(String(describing: cols[i])) = ?")
}
if !conflictkeys.contains(cols[i]) {
upsertParamsString.append(String(describing: params[i]))
}
}
paramsString.append(contentsOf: upsertParamsString)
let str = "INSERT INTO \(self.table()) (\(cols.joined(separator: ","))) VALUES(\(substString.joined(separator: ","))) ON DUPLICATE KEY UPDATE \(upsertString.joined(separator: ","))"
do {
try exec(str, params: paramsString)
} catch {
LogFile.error("Error msg: \(error)", logFile: StORMDebug.location)
self.error = StORMError.error("\(error)")
throw error
}
}
}