-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathInsert.swift
More file actions
89 lines (72 loc) · 2.4 KB
/
Insert.swift
File metadata and controls
89 lines (72 loc) · 2.4 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
//
// Insert.swift
// PostgresStORM
//
// Created by Jonathan Guthrie on 2016-09-24.
//
//
import StORM
import PerfectLogger
/// Performs insert functions as an extension to the main class.
extension MySQLStORM {
/// Insert function where the suppled data is in [(String, Any)] format.
@discardableResult
public func insert(_ data: [(String, Any)]) throws -> Any {
var keys = [String]()
var vals = [String]()
for i in data {
keys.append(i.0)
vals.append(String(describing: i.1))
}
do {
return try insert(cols: keys, params: vals)
} catch {
LogFile.error("Error msg: \(error)", logFile: StORMDebug.location)
throw StORMError.error("\(error)")
}
}
/// Insert function where the suppled data is in [String: Any] format.
public func insert(_ data: [String: Any]) throws -> Any {
var keys = [String]()
var vals = [String]()
for (key, value) in data {
keys.append(key)
vals.append(String(describing: value))
}
do {
return try insert(cols: keys, params: vals)
} catch {
LogFile.error("Error msg: \(error)", logFile: StORMDebug.location)
throw StORMError.error("\(error)")
}
}
/// Insert function where the suppled data is in matching arrays of columns and parameter values.
public func insert(cols: [String], params: [Any]) throws -> Any {
let (idname, _) = firstAsKey()
do {
return try insert(cols: cols, params: params, idcolumn: idname)
} catch {
LogFile.error("Error msg: \(error)", logFile: StORMDebug.location)
throw StORMError.error("\(error)")
}
}
/// Insert function where the suppled data is in matching arrays of columns and parameter values, as well as specifying the name of the id column.
public func insert(cols: [String], params: [Any], idcolumn: String) throws -> Any {
var paramString = [String]()
var substString = [String]()
for i in 0..<params.count {
paramString.append(String(describing: params[i]))
substString.append("?")
}
let str = "INSERT INTO \(self.table()) (\(cols.joined(separator: ","))) VALUES(\(substString.joined(separator: ",")))"
if StORMDebug.active { LogFile.info("insert statement: \(str), params: \(paramString)", logFile: StORMDebug.location) }
do {
_ = try exec(str, params: paramString, isInsert: true)
return results.insertedID
} catch {
LogFile.error("Error msg: \(error)", logFile: StORMDebug.location)
self.error = StORMError.error("\(error)")
throw error
}
}
}