Skip to content

Commit ce1188f

Browse files
committed
Added new method getLastInsertID()
1 parent 4ee575e commit ce1188f

1 file changed

Lines changed: 17 additions & 0 deletions

File tree

Sources/SQLiteAdapter/SQLiteAdapter.swift

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ public protocol SQLiteType {
6464
func getRow(sql: String, valuesToBind: SQLValues?, valuesToGet: SQLValues) throws -> [SQLValues]
6565
func getAllRows(in tableName: String, valuesToGet: SQLValues) throws -> [SQLValues]
6666
func getByID(in tableName: String, id: Int, valuesToGet: SQLValues) throws -> SQLValues
67+
func getLastInsertID() throws -> Int
6768
func vacuum() throws
6869
func resetAutoincrement(in tableName: String) throws
6970
func query(sql: String, valuesToBind: SQLValues?) throws
@@ -417,6 +418,22 @@ open class SQLite: SQLiteType {
417418
}
418419
}
419420

421+
public func getLastInsertID() throws -> Int {
422+
let sqlStatement = try prepareStatement(sql: "SELECT last_insert_rowid();")
423+
defer {
424+
sqlite3_finalize(sqlStatement)
425+
}
426+
427+
try bindPlaceholders(sqlStatement: sqlStatement, valuesToBind: nil)
428+
429+
guard sqlite3_step(sqlStatement) == SQLITE_ROW else {
430+
throw SQLiteError.Step(getErrorMessage(dbPointer: dbPointer))
431+
}
432+
let id = sqlite3_column_int(sqlStatement, 0)
433+
log("successfully got last_insert_id: \(id)")
434+
return Int(id)
435+
}
436+
420437
/// Repack the DB to take advantage of deleted data
421438
public func vacuum() throws {
422439
let sql = "VACUUM;"

0 commit comments

Comments
 (0)