Skip to content

Commit c96be8e

Browse files
author
Kyle Jessup
committed
Added func lastInsertId
1 parent 24adff0 commit c96be8e

File tree

3 files changed

+38
-4
lines changed

3 files changed

+38
-4
lines changed

Package.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ let package = Package(
3131
.library(name: "PerfectMySQL", targets: ["PerfectMySQL"])
3232
],
3333
dependencies: [
34-
.package(url: "https://github.com/PerfectlySoft/Perfect-CRUD.git", from: "1.0.0"),
34+
.package(url: "https://github.com/PerfectlySoft/Perfect-CRUD.git", from: "1.2.0"),
3535
.package(url: "https://github.com/PerfectlySoft/\(clientPackage).git", from: "2.0.0"),
3636
],
3737
targets: [

Sources/PerfectMySQL/MySQLCRUD.swift

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -532,5 +532,13 @@ extension Date {
532532
}
533533
}
534534

535-
536-
535+
public extension Insert {
536+
func lastInsertId() throws -> UInt64? {
537+
let exeDelegate = try databaseConfiguration.sqlExeDelegate(forSQL: "SELECT LAST_INSERT_ID()")
538+
guard try exeDelegate.hasNext(), let next: KeyedDecodingContainer<ColumnKey> = try exeDelegate.next() else {
539+
throw CRUDSQLGenError("Did not get return value from statement \"SELECT LAST_INSERT_ID()\".")
540+
}
541+
let value = try next.decode(UInt64.self, forKey: ColumnKey(stringValue: "LAST_INSERT_ID()")!)
542+
return value
543+
}
544+
}

Tests/PerfectMySQLTests/PerfectMySQLTests.swift

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1714,6 +1714,31 @@ class PerfectMySQLTests: XCTestCase {
17141714
}
17151715
}
17161716

1717+
func testLastInsertId() {
1718+
do {
1719+
let db = try getTestDB()
1720+
struct ReturningItem: Codable, Equatable {
1721+
let id: UInt64?
1722+
var def: Int?
1723+
init(id: UInt64, def: Int? = nil) {
1724+
self.id = id
1725+
self.def = def
1726+
}
1727+
}
1728+
try db.sql("DROP TABLE IF EXISTS \(ReturningItem.CRUDTableName)")
1729+
try db.sql("CREATE TABLE \(ReturningItem.CRUDTableName) (id INT PRIMARY KEY AUTO_INCREMENT, def INT DEFAULT 42)")
1730+
let table = db.table(ReturningItem.self)
1731+
let id = try table
1732+
.insert(ReturningItem(id: 0, def: 0),
1733+
ignoreKeys: \ReturningItem.id)//, \ReturningItem.def)
1734+
.lastInsertId()
1735+
XCTAssertEqual(id, 1)
1736+
1737+
} catch {
1738+
XCTFail("\(error)")
1739+
}
1740+
}
1741+
17171742
static var allTests = [
17181743
("testConnect", testConnect),
17191744
("testListDbs1", testListDbs1),
@@ -1762,7 +1787,8 @@ class PerfectMySQLTests: XCTestCase {
17621787
("testAllPrimTypes1", testAllPrimTypes1),
17631788
("testAllPrimTypes2", testAllPrimTypes2),
17641789
("testBespokeSQL", testBespokeSQL),
1765-
("testURL", testURL)
1790+
("testURL", testURL),
1791+
("testLastInsertId", testLastInsertId)
17661792
]
17671793
}
17681794

0 commit comments

Comments
 (0)