diff --git a/SQLite/Core/Connection.swift b/SQLite/Core/Connection.swift index 5d6ebcdc..e96a84b5 100644 --- a/SQLite/Core/Connection.swift +++ b/SQLite/Core/Connection.swift @@ -132,9 +132,8 @@ public final class Connection { public var readonly: Bool { return sqlite3_db_readonly(handle, nil) == 1 } /// The last rowid inserted into the database via this connection. - public var lastInsertRowid: Int64? { - let rowid = sqlite3_last_insert_rowid(handle) - return rowid != 0 ? rowid : nil + public var lastInsertRowid: Int64 { + return sqlite3_last_insert_rowid(handle) } /// The last number of changes (inserts, updates, or deletes) made to the diff --git a/SQLite/Typed/Query.swift b/SQLite/Typed/Query.swift index 375c1d0a..288768c1 100644 --- a/SQLite/Typed/Query.swift +++ b/SQLite/Typed/Query.swift @@ -972,7 +972,7 @@ extension Connection { let expression = query.expression return try sync { try self.run(expression.template, expression.bindings) - return self.lastInsertRowid! + return self.lastInsertRowid } } diff --git a/SQLiteTests/ConnectionTests.swift b/SQLiteTests/ConnectionTests.swift index 99b9d8a1..ab0e957c 100644 --- a/SQLiteTests/ConnectionTests.swift +++ b/SQLiteTests/ConnectionTests.swift @@ -43,17 +43,29 @@ class ConnectionTests : SQLiteTestCase { XCTAssertTrue(db.readonly) } - func test_lastInsertRowid_returnsNilOnNewConnections() { - XCTAssert(db.lastInsertRowid == nil) + func test_changes_returnsZeroOnNewConnections() { + XCTAssertEqual(0, db.changes) } func test_lastInsertRowid_returnsLastIdAfterInserts() { try! InsertUser("alice") - XCTAssertEqual(1, db.lastInsertRowid!) + XCTAssertEqual(1, db.lastInsertRowid) } - func test_changes_returnsZeroOnNewConnections() { - XCTAssertEqual(0, db.changes) + func test_lastInsertRowid_doesNotResetAfterError() { + XCTAssert(db.lastInsertRowid == 0) + try! InsertUser("alice") + XCTAssertEqual(1, db.lastInsertRowid) + XCTAssertThrowsError( + try db.run("INSERT INTO \"users\" (email, age, admin) values ('invalid@example.com', 12, 'invalid')") + ) { error in + if case SQLite.Result.error(_, let code, _) = error { + XCTAssertEqual(SQLITE_CONSTRAINT, code) + } else { + XCTFail("expected error") + } + } + XCTAssertEqual(1, db.lastInsertRowid) } func test_changes_returnsNumberOfChanges() {