Skip to content

Commit 8760ca3

Browse files
committed
Added settable primaryKey property
1 parent a262080 commit 8760ca3

1 file changed

Lines changed: 5 additions & 3 deletions

File tree

Sources/SQLiteAdapter/SQLiteAdapter.swift

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,8 @@ open class SQLite: SQLiteType {
7878
private let SQLITE_STATIC = unsafeBitCast(0, to: sqlite3_destructor_type.self)
7979
private let SQLITE_TRANSIENT = unsafeBitCast(-1, to: sqlite3_destructor_type.self)
8080

81+
public var primaryKey = "id"
82+
8183
public init(path: String, recreateDB: Bool = false) throws {
8284
if recreateDB {
8385
try deleteDB(path: path)
@@ -311,7 +313,7 @@ open class SQLite: SQLiteType {
311313
}
312314

313315
public func deleteByID(in tableName: String, id: Int) throws {
314-
let sql = "DELETE FROM \(tableName) WHERE id = ?;"
316+
let sql = "DELETE FROM \(tableName) WHERE \(primaryKey) = ?;"
315317
let valuesToBind = SQLValues([(.INT, id)])
316318
try operation(sql: sql, valuesToBind: valuesToBind)
317319
log("successfully deleted a row by id \(id) in \(tableName)")
@@ -413,7 +415,7 @@ open class SQLite: SQLiteType {
413415
}
414416

415417
public func getByID(in tableName: String, id: Int, valuesToGet: SQLValues) throws -> SQLValues {
416-
let sql = "SELECT * FROM \(tableName) WHERE id = ? LIMIT 1;"
418+
let sql = "SELECT * FROM \(tableName) WHERE \(primaryKey) = ? LIMIT 1;"
417419
let valueToBind = SQLValues([(.INT, id)])
418420
let result = try getRow(sql: sql, valuesToBind: valueToBind, valuesToGet: valuesToGet)
419421
if result.count == 1 {
@@ -425,7 +427,7 @@ open class SQLite: SQLiteType {
425427
}
426428

427429
public func getLastRow(in tableName: String, valuesToGet: SQLValues) throws -> SQLValues {
428-
let sql = "SELECT * FROM \(tableName) WHERE id = (SELECT MAX(id) FROM \(tableName));"
430+
let sql = "SELECT * FROM \(tableName) WHERE \(primaryKey) = (SELECT MAX(\(primaryKey)) FROM \(tableName));"
429431
let result = try getRow(sql: sql, valuesToBind: nil, valuesToGet: valuesToGet)
430432
if result.count == 1 {
431433
log("successfully read last row in \(tableName)")

0 commit comments

Comments
 (0)