From 7001b60cf7daa3c0ab89f445de6e70920f3476de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 12 Dec 2021 16:43:40 +0100 Subject: [PATCH] More support for association existence check New: support for associated tables WITHOUT ROWID with a compound primary key New: support for associated views Checking for the existence of associated CTEs is still not implemented (it fails with "table does not exist" error). --- CHANGELOG.md | 3 +- GRDB/Core/Database+Schema.swift | 25 +++- GRDB/QueryInterface/SQL/SQLExpression.swift | 52 +++++++- .../SQLGeneration/SQLGenerationContext.swift | 3 +- .../AssociationBelongsToSQLTests.swift | 122 +++++++++++++++--- 5 files changed, 182 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8629d3231..b6366d29d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -88,7 +88,8 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **New**: `DatabaseRegion(table: tableName)` is deprecated. Use `Table(tableName)` instead. - **New**: The `ABS` and `LENGTH` SQL functions are now available on association aggregates, through `abs(aggregate)` and `length(aggregate)`. - **New**: Support for the [`TOTAL` aggregate function](https://www.sqlite.org/lang_aggfunc.html#sumunc). You can use `total` in Swift, at all places `sum` is available. -- **New**: `ValueObservation.removeDuplicates(by:)` +- **New**: `ValueObservation.removeDuplicates(by:)` with a closure argument. +- **New**: Testing for the existence of an associated record with `TableAlias.exists` now supports associated views, and associated tables WITHOUT ROWID that have a compound primary key. ## 5.16.0 diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 96a8b0b91..31b546ed9 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -530,7 +530,7 @@ extension Database { extension Database { - /// The columns in the table named `tableName`. + /// The columns in the table, or view, named `tableName`. /// /// - throws: A DatabaseError if table does not exist. public func columns(in tableName: String) throws -> [ColumnInfo] { @@ -661,6 +661,29 @@ extension Database { } return nil } + + /// Returns the columns to check for NULL in order to check if the row exist. + /// + /// 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 + let primaryKey = try self.primaryKey(tableName) + if let rowIDColumn = primaryKey.rowIDColumn { + // Prefer the user-provided name of the rowid + return [rowIDColumn] + } else if primaryKey.tableHasRowID { + // Prefer the rowid + return [Column.rowID.name] + } else { + // WITHOUT ROWID table: use primary key columns + return primaryKey.columns + } + } else { + // View: check all columns for existence + return try columns(in: tableName).map(\.name) + } + } } /// A column of a database table. diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index 99d0632b2..e460aab80 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -136,6 +136,14 @@ public struct SQLExpression { /// document.rowid /// country.code case qualifiedFastPrimaryKey(TableAlias) + + /// An expression that is true iff the row exists: + /// + /// - For tables with a rowid, it is true iff the rowid is not null. + /// - For tables WITHOUT ROWID, it is true iff any primary key column is not null. + /// - For views, it is true iff any column is not null. + /// - For CTEs, it is not implemented yet. + case qualifiedExists(TableAlias, isNegated: Bool) } /// `BooleanTest` supports truthiness tests. @@ -669,24 +677,37 @@ extension SQLExpression { // MARK: Deferred + // TODO: replace with something that can work for WITHOUT ROWID table with a multi-columns primary key. /// An expression that picks the fastest available primary key. /// /// It crashes for WITHOUT ROWID table with a multi-columns primary key. - /// Future versions of GRDB may use [row values](https://www.sqlite.org/rowvalue.html). /// /// id /// rowid /// code static let fastPrimaryKey = SQLExpression(impl: .fastPrimaryKey) + // TODO: replace with something that can work for WITHOUT ROWID table with a multi-columns primary key. /// A qualified "fast primary key" (see `SQLExpression.fastPrimaryKey`). /// + /// It crashes for WITHOUT ROWID table with a multi-columns primary key. + /// /// player.id /// document.rowid /// country.code static func qualifiedFastPrimaryKey(_ alias: TableAlias) -> Self { self.init(impl: .qualifiedFastPrimaryKey(alias)) } + + /// An expression that is true iff the row exists: + /// + /// - For tables with a rowid, it is true iff the rowid is not null. + /// - For tables WITHOUT ROWID, it is true iff any primary key column is not null. + /// - For views, it is true iff any column is not null. + /// - For CTEs, it is not implemented yet. + static func qualifiedExists(_ alias: TableAlias) -> Self { + self.init(impl: .qualifiedExists(alias, isNegated: false)) + } } extension SQLExpression { @@ -993,6 +1014,22 @@ extension SQLExpression { return try SQLExpression .qualifiedColumn(column, alias) .sql(context, wrappedInParenthesis: wrappedInParenthesis) + + case let .qualifiedExists(alias, isNegated: isNegated): + // Works with tables and views. + // TODO: add support for CTEs eventually. + let existenceCheckColumns = try context.db.existenceCheckColumns(in: alias.tableName) + if isNegated { + return try existenceCheckColumns + .map { SQLExpression.qualifiedColumn($0, alias) == nil } + .joined(operator: .and) + .sql(context, wrappedInParenthesis: wrappedInParenthesis) + } else { + return try existenceCheckColumns + .map { SQLExpression.qualifiedColumn($0, alias) != nil } + .joined(operator: .or) + .sql(context, wrappedInParenthesis: wrappedInParenthesis) + } } } @@ -1335,6 +1372,18 @@ extension SQLExpression { return .isEmpty(expression, isNegated: !isNegated) } + case let .qualifiedExists(alias, isNegated: isNegated): + switch test { + case .true: + return .compare(.equal, self, true.sqlExpression) + + case .false: + return .compare(.equal, self, false.sqlExpression) + + case .falsey: + return SQLExpression(impl: .qualifiedExists(alias, isNegated: !isNegated)) + } + default: switch test { case .true: @@ -1421,6 +1470,7 @@ extension SQLExpression { case .databaseValue, .qualifiedColumn, .qualifiedFastPrimaryKey, + .qualifiedExists, .subquery, .exists: return self diff --git a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift index f336278e5..1f491e133 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift @@ -437,8 +437,7 @@ public class TableAlias: Hashable { /// return try request.fetchAll(db) /// } public var exists: SQLExpression { - // TODO: this fails with SQL views. Can we do something? - SQLExpression.qualifiedFastPrimaryKey(self) != nil + SQLExpression.qualifiedExists(self) } /// :nodoc: diff --git a/Tests/GRDBTests/AssociationBelongsToSQLTests.swift b/Tests/GRDBTests/AssociationBelongsToSQLTests.swift index ed21f4c95..152c6aa68 100644 --- a/Tests/GRDBTests/AssociationBelongsToSQLTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToSQLTests.swift @@ -2000,28 +2000,114 @@ class AssociationBelongsToSQLTests: GRDBTestCase { static let author = belongsTo(Author.self) } - struct Author: TableRecord { + struct Author: TableRecord { } + + do { + // Primary key is the rowid: + // Existence check is performed on the primary key. + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "author") { t in + t.autoIncrementedPrimaryKey("id") + } + try db.create(table: "book") { t in + t.autoIncrementedPrimaryKey("id") + t.column("authorID", .integer).references("author") + } + + let authorAlias = TableAlias() + let request = Book + .joining(optional: Book.author.aliased(authorAlias)) + .filter(!authorAlias.exists) + try assertEqualSQL(db, request, """ + SELECT "book".* FROM "book" \ + LEFT JOIN "author" ON "author"."id" = "book"."authorID" \ + WHERE "author"."id" IS NULL + """) + } } - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { db in - try db.create(table: "author") { t in - t.autoIncrementedPrimaryKey("id") + do { + // Primary key is not the rowid: + // Existence check is performed on the rowid. + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "author") { t in + t.column("id", .text).primaryKey() + } + try db.create(table: "book") { t in + t.autoIncrementedPrimaryKey("id") + t.column("authorID", .text).references("author") + } + + let authorAlias = TableAlias() + let request = Book + .joining(optional: Book.author.aliased(authorAlias)) + .filter(!authorAlias.exists) + try assertEqualSQL(db, request, """ + SELECT "book".* FROM "book" \ + LEFT JOIN "author" ON "author"."id" = "book"."authorID" \ + WHERE "author"."rowid" IS NULL + """) } - try db.create(table: "book") { t in - t.autoIncrementedPrimaryKey("id") - t.column("authorID", .integer).references("author") + } + + do { + // Compound primary key, WITHOUT ROWID optimization: + // Existence check is performed on the primary key. + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "author", withoutRowID: true) { t in + t.column("a", .text).notNull() + t.column("b", .text).notNull() + t.primaryKey(["a", "b"]) + } + try db.create(table: "book") { t in + t.autoIncrementedPrimaryKey("id") + t.column("authorA", .text) + t.column("authorB", .text) + t.foreignKey(["authorA", "authorB"], references: "author") + } + + let authorAlias = TableAlias() + let request = Book + .joining(optional: Book.author.aliased(authorAlias)) + .filter(!authorAlias.exists) + try assertEqualSQL(db, request, """ + SELECT "book".* FROM "book" \ + LEFT JOIN "author" ON ("author"."a" = "book"."authorA") AND ("author"."b" = "book"."authorB") \ + WHERE ("author"."a" IS NULL) AND ("author"."b" IS NULL) + """) + } + } + + do { + // View: existence check is performed on all columns. + 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) AND ("authorView"."name" IS NULL) + """) } - - let authorAlias = TableAlias() - let request = Book - .joining(optional: Book.author.aliased(authorAlias)) - .filter(!authorAlias.exists) - try assertEqualSQL(db, request, """ - SELECT "book".* FROM "book" \ - LEFT JOIN "author" ON "author"."id" = "book"."authorID" \ - WHERE "author"."id" IS NULL - """) } } }