diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 3309bf656..2fcce080c 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -580,7 +580,6 @@ extension Database { /// Returns whether the column identifies the rowid column func columnIsRowID(_ column: String, of tableName: String) throws -> Bool { - #warning("TODO: test with database views") let pk = try primaryKey(tableName) return pk.rowIDColumn == column || (pk.tableHasRowID && column.uppercased() == "ROWID") } @@ -1153,8 +1152,8 @@ extension Database { /// /// The returned array is never empty. func existenceCheckColumns(in tableName: String) throws -> [String] { - if try tableExists(tableName) { - // Table: only check the primary key columns for existence + do { + // Check the primary key columns for existence let primaryKey = try self.primaryKey(tableName) if let rowIDColumn = primaryKey.rowIDColumn { // Prefer the user-provided name of the rowid @@ -1175,10 +1174,15 @@ extension Database { // try db.existenceCheckColumns(in: "player") // ["uuid"] return primaryKey.columns } - } else { - #warning("TODO: use the primary key if available") - // View: check all columns for existence - return try columns(in: tableName).map(\.name) + } catch let error as DatabaseError { + if case .SQLITE_ERROR = error.resultCode, + (try? viewExists(tableName)) == true + { + // View without primary key: check all columns for existence + return try columns(in: tableName).map(\.name) + } else { + throw error + } } } } diff --git a/Tests/GRDBTests/AssociationBelongsToSQLTests.swift b/Tests/GRDBTests/AssociationBelongsToSQLTests.swift index 3e4c2fd43..b7d737d18 100644 --- a/Tests/GRDBTests/AssociationBelongsToSQLTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToSQLTests.swift @@ -2359,5 +2359,41 @@ class AssociationBelongsToSQLTests: GRDBTestCase { """) } } + + do { + // View with custom primary key. + // Existence check is performed on the primary key. + struct SchemaSource: DatabaseSchemaSource { + func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? { + ["id"] + } + } + dbConfiguration.schemaSource = SchemaSource() + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "author") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name", .text) + } + try db.create(table: "book") { t in + t.autoIncrementedPrimaryKey("id") + t.column("authorID", .integer) + } + try db.execute(sql: """ + CREATE VIEW authorView AS SELECT * FROM author + """) + + let association = Book.belongsTo(Table("authorView"), using: ForeignKey(["authorId"], to: ["id"])) + let authorAlias = TableAlias() + let request = Book + .joining(optional: association.aliased(authorAlias)) + .filter(!authorAlias.exists) + try assertEqualSQL(db, request, """ + SELECT "book".* FROM "book" \ + LEFT JOIN "authorView" ON "authorView"."id" = "book"."authorId" \ + WHERE "authorView"."id" IS NULL + """) + } + } } }