Skip to content

Commit

Permalink
Make lastInsertRowid consistent with other SQLite wrappers
Browse files Browse the repository at this point in the history
closes #532
  • Loading branch information
jberkel committed Nov 15, 2016
1 parent 6b78409 commit 75394da
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 9 deletions.
5 changes: 2 additions & 3 deletions SQLite/Core/Connection.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion SQLite/Typed/Query.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}

Expand Down
22 changes: 17 additions & 5 deletions SQLiteTests/ConnectionTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down

0 comments on commit 75394da

Please sign in to comment.