Support primary key when testing the existence of an association to a view

This commit is contained in:
Gwendal Roué authored and Gwendal Roué committed 2025-09-23 17:12:27 +02:00
1 parent f4991273c2
commit 99ecf76a77
2 files changed
+47 -7

No files matched your search

+11 -7
View File
@@ -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
}
}
}
}
@@ -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
""")
}
}
}
}