#147: Database.tableExists(_:) and Database.indexes(on:) can now throw database errors

This commit is contained in:
Gwendal Roué committed 2016-11-26 08:28:32 +01:00
1 parent b0db219aeb
commit b31356aada
12 files changed
+60 -58

No files matched your search

+5 -3
View File
@@ -5,7 +5,7 @@ Release Notes
**New**
- `DatabaseCursor` allows processing errors when reading from the database. Compare:
- `DatabaseCursor` allows processing errors that happen when reading from the database. Compare:
```swift
// May crash in case of I/O error, for example:
@@ -15,14 +15,16 @@ Release Notes
// Cursor expose all database errors:
let cursor = try Person.fetchCursor(db)
while person = try cursor.step() {
while person = try cursor.next() {
...
}
```
**Breaking Change**
- the throwing `step()` method of DatabaseIterator has been removed. Use cursors instead.
- The throwing `step()` method of DatabaseIterator has been removed. Use DatabaseCursor instead.
- `Database.tableExists(_:)` can now throw database errors.
- `Database.indexes(on:)` can now throw database errors.
## 0.90.1
+10 -10
View File
@@ -936,13 +936,13 @@ extension Database {
}
/// Returns whether a table exists.
public func tableExists(_ tableName: String) -> Bool {
public func tableExists(_ tableName: String) throws -> Bool {
SchedulingWatchdog.preconditionValidQueue(self)
// SQlite identifiers are case-insensitive, case-preserving (http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html)
return Row.fetchOne(self,
"SELECT * FROM (SELECT sql, type, name FROM sqlite_master UNION SELECT sql, type, name FROM sqlite_temp_master) WHERE type = 'table' AND LOWER(name) = ?",
arguments: [tableName.lowercased()]) != nil
return try Row
.fetchCursor(self, "SELECT 1 FROM (SELECT sql, type, name FROM sqlite_master UNION SELECT sql, type, name FROM sqlite_temp_master) WHERE type = 'table' AND LOWER(name) = ?", arguments: [tableName.lowercased()])
.next() != nil
}
/// The primary key for table named `tableName`; nil if table has no
@@ -1064,11 +1064,11 @@ extension Database {
if #available(iOS 8.2, OSX 10.10, *) { } else {
// Work around a bug in SQLite where PRAGMA table_info would
// return a result even after the table was deleted.
if !tableExists(tableName) {
if try !tableExists(tableName) {
throw DatabaseError(message: "no such table: \(tableName)")
}
}
let columns = ColumnInfo.fetchAll(self, "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))")
let columns = try ColumnInfo.fetchCursor(self, "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))").map { $0 }
guard columns.count > 0 else {
throw DatabaseError(message: "no such table: \(tableName)")
}
@@ -1085,15 +1085,15 @@ extension Database {
///
/// If you want to know if a set of columns uniquely identify a row, prefer
/// table(_:hasUniqueKey:) instead.
public func indexes(on tableName: String) -> [IndexInfo] {
public func indexes(on tableName: String) throws -> [IndexInfo] {
if let indexes = schemaCache.indexes(on: tableName) {
return indexes
}
let indexes = Row.fetch(self, "PRAGMA index_list(\(tableName.quotedDatabaseIdentifier))").map { row -> IndexInfo in
let indexes = try Row.fetchCursor(self, "PRAGMA index_list(\(tableName.quotedDatabaseIdentifier))").map { row -> IndexInfo in
let indexName: String = row.value(atIndex: 1)
let unique: Bool = row.value(atIndex: 2)
let columns = Row.fetch(self, "PRAGMA index_info(\(indexName.quotedDatabaseIdentifier))")
let columns = try Row.fetchCursor(self, "PRAGMA index_info(\(indexName.quotedDatabaseIdentifier))")
.map { ($0.value(atIndex: 0) as Int, $0.value(atIndex: 2) as String) }
.sorted { $0.0 < $1.0 }
.map { $0.1 }
@@ -1109,7 +1109,7 @@ extension Database {
public func table<T: Sequence>(_ tableName: String, hasUniqueKey columns: T) throws -> Bool where T.Iterator.Element == String {
let primaryKey = try self.primaryKey(tableName) // first, so that we fail early and consistently should the table not exist
let columns = Set(columns.map { $0.lowercased() })
if indexes(on: tableName).contains(where: { index in index.isUnique && Set(index.columns.map { $0.lowercased() }) == columns }) {
if try indexes(on: tableName).contains(where: { index in index.isUnique && Set(index.columns.map { $0.lowercased() }) == columns }) {
// There is an explicit unique index on the columns
return true
}
+3 -3
View File
@@ -1376,10 +1376,10 @@ for row in Row.fetch(db, "PRAGMA table_info('persons')") {
GRDB provides four high-level methods as well:
```swift
db.tableExists("persons") // Bool, true if the table exists
db.indexes(on: "persons") // [IndexInfo], the indexes defined on the table
try db.tableExists("persons") // Bool, true if the table exists
try db.indexes(on: "persons") // [IndexInfo], the indexes defined on the table
try db.table("persons", hasUniqueKey: ["email"]) // Bool, true if column(s) is a unique key
try db.primaryKey("persons") // PrimaryKeyInfo?
try db.primaryKey("persons") // PrimaryKeyInfo?
```
Primary key is nil when table has no primary key:
@@ -45,7 +45,7 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase {
XCTAssertEqual(columns[2].name, "foo")
XCTAssertEqual(columns[3].name, "bar")
let indexes = db.indexes(on: "items")
let indexes = try db.indexes(on: "items")
XCTAssertEqual(indexes.count, 2)
for index in indexes {
switch index.name {
@@ -13,13 +13,13 @@ class DatabaseTests : GRDBTestCase {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
XCTAssertFalse(db.tableExists("persons"))
XCTAssertFalse(try db.tableExists("persons"))
try db.execute(
"CREATE TABLE persons (" +
"id INTEGER PRIMARY KEY, " +
"name TEXT, " +
"age INT)")
XCTAssertTrue(db.tableExists("persons"))
XCTAssertTrue(try db.tableExists("persons"))
}
}
}
@@ -28,13 +28,13 @@ class DatabaseTests : GRDBTestCase {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
XCTAssertFalse(db.tableExists("persons"))
XCTAssertFalse(try db.tableExists("persons"))
try db.execute(
"CREATE TEMPORARY TABLE persons (" +
"id INTEGER PRIMARY KEY, " +
"name TEXT, " +
"age INT)")
XCTAssertTrue(db.tableExists("persons"))
XCTAssertTrue(try db.tableExists("persons"))
}
}
}
@@ -43,13 +43,13 @@ class DatabaseTests : GRDBTestCase {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
XCTAssertFalse(db.tableExists("persons"))
XCTAssertFalse(db.tableExists("pets"))
XCTAssertFalse(try db.tableExists("persons"))
XCTAssertFalse(try db.tableExists("pets"))
try db.execute(
"CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT, age INT);" +
"CREATE TABLE pets (id INTEGER PRIMARY KEY, name TEXT, age INT);")
XCTAssertTrue(db.tableExists("persons"))
XCTAssertTrue(db.tableExists("pets"))
XCTAssertTrue(try db.tableExists("persons"))
XCTAssertTrue(try db.tableExists("pets"))
}
}
}
@@ -15,7 +15,7 @@ class IndexInfoTests: GRDBTestCase {
try dbQueue.inDatabase { db in
do {
try db.execute("CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT, email TEXT UNIQUE)")
let indexes = db.indexes(on: "persons")
let indexes = try db.indexes(on: "persons")
XCTAssertEqual(indexes.count, 1)
XCTAssertEqual(indexes[0].name, "sqlite_autoindex_persons_1")
@@ -26,7 +26,7 @@ class IndexInfoTests: GRDBTestCase {
do {
try db.execute("CREATE TABLE citizenships (year INTEGER, personId INTEGER NOT NULL, countryIsoCode TEXT NOT NULL, PRIMARY KEY (personId, countryIsoCode))")
try db.execute("CREATE INDEX citizenshipsOnYear ON citizenships(year)")
let indexes = db.indexes(on: "citizenships")
let indexes = try db.indexes(on: "citizenships")
XCTAssertEqual(indexes.count, 2)
if let i = indexes.index(where: { $0.columns == ["year"] }) {
@@ -32,8 +32,8 @@ class DatabasePoolBackupTests: GRDBTestCase {
try source.backup(to: destination)
destination.read { db in
XCTAssertFalse(db.tableExists("items"))
try destination.read { db in
XCTAssertFalse(try db.tableExists("items"))
}
}
}
@@ -32,8 +32,8 @@ class DatabaseQueueBackupTests: GRDBTestCase {
try source.backup(to: destination)
destination.inDatabase { db in
XCTAssertFalse(db.tableExists("items"))
try destination.inDatabase { db in
XCTAssertFalse(try db.tableExists("items"))
}
}
}
@@ -174,8 +174,8 @@ class UpdateStatementTests : GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE wines (name TEXT, color INT); CREATE TABLE books (name TEXT, age INT)")
XCTAssertTrue(db.tableExists("wines"))
XCTAssertTrue(db.tableExists("books"))
XCTAssertTrue(try db.tableExists("wines"))
XCTAssertTrue(try db.tableExists("books"))
}
}
}
@@ -185,8 +185,8 @@ class UpdateStatementTests : GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE wines (name TEXT, color INT); CREATE TABLE books (name TEXT, age INT)\n \t")
XCTAssertTrue(db.tableExists("wines"))
XCTAssertTrue(db.tableExists("books"))
XCTAssertTrue(try db.tableExists("wines"))
XCTAssertTrue(try db.tableExists("books"))
}
}
}
@@ -196,8 +196,8 @@ class UpdateStatementTests : GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE wines (name TEXT, color INT); CREATE TABLE books (name TEXT, age INT);\n \t")
XCTAssertTrue(db.tableExists("wines"))
XCTAssertTrue(db.tableExists("books"))
XCTAssertTrue(try db.tableExists("wines"))
XCTAssertTrue(try db.tableExists("books"))
}
}
}
@@ -33,9 +33,9 @@ class DatabaseMigratorTests : GRDBTestCase {
}
try migrator.migrate(dbQueue)
dbQueue.inDatabase { db in
XCTAssertTrue(db.tableExists("persons"))
XCTAssertTrue(db.tableExists("pets"))
try dbQueue.inDatabase { db in
XCTAssertTrue(try db.tableExists("persons"))
XCTAssertTrue(try db.tableExists("pets"))
}
migrator.registerMigration("destroyPersons") { db in
@@ -43,9 +43,9 @@ class DatabaseMigratorTests : GRDBTestCase {
}
try migrator.migrate(dbQueue)
dbQueue.inDatabase { db in
XCTAssertTrue(db.tableExists("persons"))
XCTAssertFalse(db.tableExists("pets"))
try dbQueue.inDatabase { db in
XCTAssertTrue(try db.tableExists("persons"))
XCTAssertFalse(try db.tableExists("pets"))
}
}
}
@@ -74,9 +74,9 @@ class DatabaseMigratorTests : GRDBTestCase {
}
try migrator.migrate(dbPool)
dbPool.read { db in
XCTAssertTrue(db.tableExists("persons"))
XCTAssertTrue(db.tableExists("pets"))
try dbPool.read { db in
XCTAssertTrue(try db.tableExists("persons"))
XCTAssertTrue(try db.tableExists("pets"))
}
migrator.registerMigration("destroyPersons") { db in
@@ -84,9 +84,9 @@ class DatabaseMigratorTests : GRDBTestCase {
}
try migrator.migrate(dbPool)
dbPool.read { db in
XCTAssertTrue(db.tableExists("persons"))
XCTAssertFalse(db.tableExists("pets"))
try dbPool.read { db in
XCTAssertTrue(try db.tableExists("persons"))
XCTAssertFalse(try db.tableExists("pets"))
}
}
}
@@ -423,12 +423,12 @@ class SQLTableBuilderTests: GRDBTestCase {
try db.create(table: "test") { t in
t.column("a", .text)
}
XCTAssertTrue(db.tableExists("test"))
XCTAssertTrue(try db.tableExists("test"))
try db.rename(table: "test", to: "foo")
XCTAssertEqual(self.lastSQLQuery, "ALTER TABLE \"test\" RENAME TO \"foo\"")
XCTAssertFalse(db.tableExists("test"))
XCTAssertTrue(db.tableExists("foo"))
XCTAssertFalse(try db.tableExists("test"))
XCTAssertTrue(try db.tableExists("foo"))
}
}
}
@@ -461,11 +461,11 @@ class SQLTableBuilderTests: GRDBTestCase {
t.column("id", .integer).primaryKey()
t.column("name", .text)
}
XCTAssertTrue(db.tableExists("test"))
XCTAssertTrue(try db.tableExists("test"))
try db.drop(table: "test")
XCTAssertEqual(self.lastSQLQuery, "DROP TABLE \"test\"")
XCTAssertFalse(db.tableExists("test"))
XCTAssertFalse(try db.tableExists("test"))
}
}
}
@@ -487,7 +487,7 @@ class SQLTableBuilderTests: GRDBTestCase {
XCTAssertEqual(self.lastSQLQuery, "CREATE UNIQUE INDEX IF NOT EXISTS \"test_on_a_b\" ON \"test\"(\"a\", \"b\") WHERE (\"a\" = 1)")
// Sanity check
XCTAssertEqual(Set(db.indexes(on: "test").map { $0.name }), ["test_on_a", "test_on_a_b"])
XCTAssertEqual(try Set(db.indexes(on: "test").map { $0.name }), ["test_on_a", "test_on_a_b"])
}
}
}
@@ -506,7 +506,7 @@ class SQLTableBuilderTests: GRDBTestCase {
XCTAssertEqual(self.lastSQLQuery, "DROP INDEX \"test_on_name\"")
// Sanity check
XCTAssertTrue(db.indexes(on: "test").isEmpty)
XCTAssertTrue(try db.indexes(on: "test").isEmpty)
}
}
}
@@ -58,7 +58,7 @@ class VirtualTableModuleTests: GRDBTestCase {
t.tokenizer = "simple"
}
assertDidExecute(sql: "CREATE VIRTUAL TABLE \"test\" USING fts3tokenize(simple)")
XCTAssertTrue(db.tableExists("test"))
XCTAssertTrue(try db.tableExists("test"))
}
}
}
@@ -76,7 +76,7 @@ class VirtualTableModuleTests: GRDBTestCase {
XCTAssertEqual(error.code, 123)
}
assertDidExecute(sql: "CREATE VIRTUAL TABLE \"test\" USING fts3tokenize(simple)")
XCTAssertFalse(db.tableExists("test"))
XCTAssertFalse(try db.tableExists("test"))
}
}
}