diff --git a/GRDB/Core/SQL.swift b/GRDB/Core/SQL.swift index a6d2c439f..056ad8abf 100644 --- a/GRDB/Core/SQL.swift +++ b/GRDB/Core/SQL.swift @@ -118,7 +118,7 @@ public struct SQL: Sendable { } } - fileprivate func qualified(with alias: TableAlias) -> Element { + fileprivate func qualified(with alias: TableAliasBase) -> Element { switch self { case .sql: // A raw SQL string can't be qualified with a table alias, @@ -192,7 +192,7 @@ public struct SQL: Sendable { try elements.map { try $0.sql(context) }.joined() } - func qualified(with alias: TableAlias) -> SQL { + func qualified(with alias: TableAliasBase) -> SQL { SQL(elements: elements.map { $0.qualified(with: alias) }) } } diff --git a/GRDB/QueryInterface/FTS3+QueryInterface.swift b/GRDB/QueryInterface/FTS3+QueryInterface.swift index 49fbc559c..a2335d4b8 100644 --- a/GRDB/QueryInterface/FTS3+QueryInterface.swift +++ b/GRDB/QueryInterface/FTS3+QueryInterface.swift @@ -21,7 +21,7 @@ extension TableRequest where Self: FilteredRequest { } let alias = TableAlias() let matchExpression = SQLExpression.tableMatch(alias, pattern.sqlExpression) - return self.aliased(alias).filter(matchExpression) + return self._aliased(alias).filter(matchExpression) } } diff --git a/GRDB/QueryInterface/FTS5+QueryInterface.swift b/GRDB/QueryInterface/FTS5+QueryInterface.swift index b49f10514..4d97fd00f 100644 --- a/GRDB/QueryInterface/FTS5+QueryInterface.swift +++ b/GRDB/QueryInterface/FTS5+QueryInterface.swift @@ -22,7 +22,7 @@ extension TableRequest where Self: FilteredRequest { } let alias = TableAlias() let matchExpression = SQLExpression.tableMatch(alias, pattern.sqlExpression) - return self.aliased(alias).filter(matchExpression) + return self._aliased(alias).filter(matchExpression) } } diff --git a/GRDB/QueryInterface/Request/Association/Association.swift b/GRDB/QueryInterface/Request/Association/Association.swift index 28a94532c..734b04ffd 100644 --- a/GRDB/QueryInterface/Request/Association/Association.swift +++ b/GRDB/QueryInterface/Request/Association/Association.swift @@ -164,7 +164,7 @@ extension Association { // TableRequest conformance extension Association { - public func aliased(_ alias: TableAlias) -> Self { + public func _aliased(_ alias: TableAliasBase) -> Self { withDestinationRelation { relation in relation = relation.aliased(alias) } diff --git a/GRDB/QueryInterface/Request/CommonTableExpression.swift b/GRDB/QueryInterface/Request/CommonTableExpression.swift index 9cbd4d2bb..ceef01931 100644 --- a/GRDB/QueryInterface/Request/CommonTableExpression.swift +++ b/GRDB/QueryInterface/Request/CommonTableExpression.swift @@ -385,12 +385,18 @@ extension CommonTableExpression { /// - returns: An association to the common table expression. public func association( to cte: CommonTableExpression, - on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible) + on condition: @escaping @Sendable ( + _ left: TableAlias, + _ right: TableAlias + ) -> any SQLExpressible + ) -> JoinAssociation { JoinAssociation( to: cte.relationForAll, - condition: .expression { condition($0, $1).sqlExpression }) + condition: .expression { left, right in + condition(TableAlias(root: left), TableAlias(root: right)).sqlExpression + }) } /// Creates an association to a common table expression that you can join @@ -421,13 +427,18 @@ extension CommonTableExpression { /// - returns: An association to the common table expression. public func association( to destination: Destination.Type, - on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible) + on condition: @escaping @Sendable ( + _ left: TableAlias, + _ right: TableAlias + ) -> any SQLExpressible) -> JoinAssociation where Destination: TableRecord { JoinAssociation( to: Destination.relationForAll, - condition: .expression { condition($0, $1).sqlExpression }) + condition: .expression { left, right in + condition(TableAlias(root: left), TableAlias(root: right)).sqlExpression + }) } /// Creates an association to a table record that you can join @@ -458,12 +469,17 @@ extension CommonTableExpression { /// - returns: An association to the common table expression. public func association( to destination: Table, - on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible) + on condition: @escaping @Sendable ( + _ left: TableAlias, + _ right: TableAlias + ) -> any SQLExpressible) -> JoinAssociation { JoinAssociation( to: destination.relationForAll, - condition: .expression { condition($0, $1).sqlExpression }) + condition: .expression { left, right in + condition(TableAlias(root: left), TableAlias(root: right)).sqlExpression + }) } /// Creates an association to a table that you can join diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index f6e40d3d0..d93793e8e 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -493,7 +493,7 @@ extension QueryInterfaceRequest: TableRequest { relation.source.tableName } - public func aliased(_ alias: TableAlias) -> Self { + public func _aliased(_ alias: TableAliasBase) -> Self { with { $0.relation = $0.relation.aliased(alias) } diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index bd3656794..cb08039e4 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -557,7 +557,19 @@ public protocol TableRequest { /// .filter(sql: "b.publishDate >= a.deathDate") /// .fetchAll(db) /// ``` - func aliased(_ alias: TableAlias) -> Self + func _aliased(_ alias: TableAliasBase) -> Self +} + +extension TableRequest where Self: TypedRequest { + // TODO: DocC + public func aliased(_ alias: TableAlias) -> Self { + self._aliased(alias) + } + + // TODO: DocC + public func aliased(_ alias: TableAlias) -> Self { + self._aliased(alias) + } } extension TableRequest where Self: FilteredRequest, Self: TypedRequest { @@ -1607,9 +1619,17 @@ extension JoinableRequest where Self: SelectionRequest { /// For example: /// /// ```swift + /// struct Player: TableRecord { } + /// + /// struct Team: TableRecord { + /// enum Columns { + /// static let color = Column("color") + /// } + /// } + /// /// // SELECT player.*, team.color /// // FROM player JOIN team ... - /// let teamColor = Player.team.select(Column("color")) + /// let teamColor = Player.team.select { $0.color } /// let request = Player.all().annotated(withRequired: teamColor) /// ``` /// @@ -1635,9 +1655,9 @@ extension JoinableRequest where Self: SelectionRequest { /// ``JoinableRequest/joining(required:)``: /// /// ```swift - /// let teamAlias = TableAlias() + /// let teamAlias = TableAlias() /// let request = Player.all() - /// .annotated(with: teamAlias[Column("color")]) + /// .annotated(with: teamAlias.color]) /// .joining(required: Player.team.aliased(teamAlias)) /// ``` public func annotated(withRequired association: A) -> Self where A.OriginRowDecoder == RowDecoder { diff --git a/GRDB/QueryInterface/SQL/SQLCollection.swift b/GRDB/QueryInterface/SQL/SQLCollection.swift index 98435bc02..a3bf6fabb 100644 --- a/GRDB/QueryInterface/SQL/SQLCollection.swift +++ b/GRDB/QueryInterface/SQL/SQLCollection.swift @@ -39,7 +39,7 @@ struct SQLCollection { extension SQLCollection { /// Returns a qualified collection. - func qualified(with alias: TableAlias) -> SQLCollection { + func qualified(with alias: TableAliasBase) -> SQLCollection { switch impl { case .subquery, .table: diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index 7ea83a19a..356323fd6 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -68,7 +68,7 @@ public struct SQLExpression: Sendable { /// /// player.id /// player.name - case qualifiedColumn(String, TableAlias) + case qualifiedColumn(String, TableAliasBase) /// A database value. /// @@ -151,7 +151,7 @@ public struct SQLExpression: Sendable { /// A table full-text match. /// /// MATCH - indirect case tableMatch(TableAlias, SQLExpression) + indirect case tableMatch(TableAliasBase, SQLExpression) /// A logical `NOT` operator. /// @@ -199,7 +199,7 @@ public struct SQLExpression: Sendable { /// player.id /// document.rowid /// country.code - case qualifiedFastPrimaryKey(TableAlias) + case qualifiedFastPrimaryKey(TableAliasBase) /// An expression that is true iff the row exists: /// @@ -207,10 +207,10 @@ public struct SQLExpression: Sendable { /// - 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) + case qualifiedExists(TableAliasBase, isNegated: Bool) /// Returns a qualified expression - func qualified(with alias: TableAlias) -> Impl { + func qualified(with alias: TableAliasBase) -> Impl { switch self { case .databaseValue, .qualifiedColumn, @@ -642,7 +642,7 @@ extension SQLExpression { /// /// player.id /// player.name - static func qualifiedColumn(_ name: String, _ alias: TableAlias) -> Self { + static func qualifiedColumn(_ name: String, _ alias: TableAliasBase) -> Self { self.init(impl: .qualifiedColumn(name, alias)) } @@ -865,7 +865,7 @@ extension SQLExpression { /// A table full-text match. /// ///
MATCH - static func tableMatch(_ alias: TableAlias, _ expression: SQLExpression) -> Self { + static func tableMatch(_ alias: TableAliasBase, _ expression: SQLExpression) -> Self { self.init(impl: .tableMatch(alias, expression)) } @@ -1153,7 +1153,7 @@ extension SQLExpression { /// player.id /// document.rowid /// country.code - static func qualifiedFastPrimaryKey(_ alias: TableAlias) -> Self { + static func qualifiedFastPrimaryKey(_ alias: TableAliasBase) -> Self { self.init(impl: .qualifiedFastPrimaryKey(alias)) } @@ -1163,7 +1163,7 @@ extension SQLExpression { /// - 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 { + static func qualifiedExists(_ alias: TableAliasBase) -> Self { self.init(impl: .qualifiedExists(alias, isNegated: false)) } } @@ -1172,7 +1172,7 @@ extension SQLExpression { extension SQLExpression { /// Returns a qualified expression - func qualified(with alias: TableAlias) -> Self { + func qualified(with alias: TableAliasBase) -> Self { .init(impl: impl.qualified(with: alias), preferredJSONInterpretation: preferredJSONInterpretation) } @@ -1217,7 +1217,7 @@ extension SQLExpression { /// - parameter acceptsBijection: If true, expressions that define a /// bijection on a column return this column. For example: `-score` /// returns `score`. - func column(_ db: Database, for alias: TableAlias, acceptsBijection: Bool = false) throws -> String? { + func column(_ db: Database, for alias: TableAliasBase, acceptsBijection: Bool = false) throws -> String? { switch impl { case let .qualifiedColumn(name, a): if alias == a { @@ -1504,7 +1504,7 @@ extension SQLExpression { /// /// // SELECT * FROM "player" WHERE "name" = 'Arthur' LIMIT 1 /// try Player.filter(Column("name") == "Arthur").fetchOne(db) - func identifyingColums(_ db: Database, for alias: TableAlias) throws -> Set { + func identifyingColums(_ db: Database, for alias: TableAliasBase) throws -> Set { switch impl { case let .rowValue(expressions): assert(!expressions.isEmpty) @@ -1572,7 +1572,7 @@ extension SQLExpression { /// let request = Player.filter(keys: [1, 2, 3]) /// let regionObservation = DatabaseRegionObservation(tracking: request) /// let valueObservation = ValueObservation.tracking(request.fetchAll) - func identifyingRowIDs(_ db: Database, for alias: TableAlias) throws -> Set? { + func identifyingRowIDs(_ db: Database, for alias: TableAliasBase) throws -> Set? { switch impl { case let .databaseValue(dbValue): if dbValue.isNull || dbValue == false.databaseValue { @@ -1979,7 +1979,7 @@ struct SQLSimpleFunctionInvocation { isPure && arguments.allSatisfy(\.isConstantInRequest) } - func qualified(with alias: TableAlias) -> Self { + func qualified(with alias: TableAliasBase) -> Self { SQLSimpleFunctionInvocation( name: name, arguments: arguments.map { $0.qualified(with: alias) }, @@ -1987,7 +1987,7 @@ struct SQLSimpleFunctionInvocation { isJSONValue: isJSONValue) } - func column(_ db: Database, for alias: TableAlias) throws -> String? { + func column(_ db: Database, for alias: TableAliasBase) throws -> String? { let name = name.uppercased() if ["HEX", "QUOTE"].contains(name) && arguments.count == 1 { return try arguments[0].column(db, for: alias, acceptsBijection: true) @@ -2023,7 +2023,7 @@ struct SQLAggregateFunctionInvocation { /// A false value does not provide any information. var isJSONValue: Bool - func qualified(with alias: TableAlias) -> Self { + func qualified(with alias: TableAliasBase) -> Self { SQLAggregateFunctionInvocation( name: name, arguments: arguments.map { $0.qualified(with: alias) }, diff --git a/GRDB/QueryInterface/SQL/SQLOrdering.swift b/GRDB/QueryInterface/SQL/SQLOrdering.swift index 0badbcca2..b3b536309 100644 --- a/GRDB/QueryInterface/SQL/SQLOrdering.swift +++ b/GRDB/QueryInterface/SQL/SQLOrdering.swift @@ -86,7 +86,7 @@ extension SQLOrdering { } extension SQLOrdering { - func qualified(with alias: TableAlias) -> SQLOrdering { + func qualified(with alias: TableAliasBase) -> SQLOrdering { switch impl { case .expression(let expression): return .expression(expression.qualified(with: alias)) diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index 691889cb3..fcbb7b884 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -331,7 +331,7 @@ extension SQLRelation: Refinable { } } - func aliased(_ alias: TableAlias) -> Self { + func aliased(_ alias: TableAliasBase) -> Self { with { $0.source = $0.source.aliased(alias) } @@ -674,9 +674,9 @@ struct SQLLimit { struct SQLSource: Sendable { var tableName: String - var alias: TableAlias? + var alias: TableAliasBase? - func aliased(_ alias: TableAlias) -> SQLSource { + func aliased(_ alias: TableAliasBase) -> SQLSource { if let sourceAlias = self.alias { alias.becomeProxy(of: sourceAlias) return self @@ -705,7 +705,7 @@ extension SQLRelation { } } - func qualified(with alias: TableAlias) -> Element { + func qualified(with alias: TableAliasBase) -> Element { switch self { case .terms(let terms): return .terms(terms.map { $0.map { $0.qualified(with: alias) } }) @@ -752,7 +752,7 @@ extension SQLRelation { isReversed: !isReversed) } - func qualified(with alias: TableAlias) -> Ordering { + func qualified(with alias: TableAliasBase) -> Ordering { Ordering( elements: elements.map { $0.qualified(with: alias) }, isReversed: isReversed) @@ -814,7 +814,7 @@ enum SQLAssociationCondition: Sendable { /// player[Column("id")] == bonus[Column("playerID")] /// }) /// Player.with(bonus).joining(required: association) - case expression(@Sendable (_ left: TableAlias, _ right: TableAlias) -> SQLExpression?) + case expression(@Sendable (_ left: TableAliasBase, _ right: TableAliasBase) -> SQLExpression?) /// The condition that does not constrain the two associated tables /// in any way. @@ -831,8 +831,8 @@ enum SQLAssociationCondition: Sendable { func joinExpression( _ db: Database, - leftAlias: TableAlias, - rightAlias: TableAlias) + leftAlias: TableAliasBase, + rightAlias: TableAliasBase) throws -> SQLExpression? { switch self { @@ -999,7 +999,7 @@ extension JoinMapping { /// JOIN operator. /// - parameter rightAlias: A TableAlias for the table on the right of the /// JOIN operator. - func joinExpression(leftAlias: TableAlias, rightAlias: TableAlias) -> SQLExpression { + func joinExpression(leftAlias: TableAliasBase, rightAlias: TableAliasBase) -> SQLExpression { map { rightAlias[$0.right] == leftAlias[$0.left] }.joined(operator: .and) } } diff --git a/GRDB/QueryInterface/SQL/SQLSelection.swift b/GRDB/QueryInterface/SQL/SQLSelection.swift index 2d0f6cc82..4a414109d 100644 --- a/GRDB/QueryInterface/SQL/SQLSelection.swift +++ b/GRDB/QueryInterface/SQL/SQLSelection.swift @@ -24,13 +24,13 @@ public struct SQLSelection: Sendable { case allColumns /// All columns, qualified: `player.*` - case qualifiedAllColumns(TableAlias) + case qualifiedAllColumns(TableAliasBase) /// All columns but the specified ones case allColumnsExcluding(Set) /// All columns but the specified ones, qualified. - case qualifiedAllColumnsExcluding(TableAlias, Set) + case qualifiedAllColumnsExcluding(TableAliasBase, Set) /// An expression case expression(SQLExpression) @@ -53,13 +53,13 @@ public struct SQLSelection: Sendable { } /// All columns, qualified: `player.*` - static func qualifiedAllColumns(_ alias: TableAlias) -> Self { + static func qualifiedAllColumns(_ alias: TableAliasBase) -> Self { self.init(impl: .qualifiedAllColumns(alias)) } /// All columns but the specified ones, qualified. static func qualifiedAllColumnsExcluding( - _ alias: TableAlias, + _ alias: TableAliasBase, _ excludedColumns: Set ) -> Self { self.init(impl: .qualifiedAllColumnsExcluding(alias, excludedColumns)) @@ -261,7 +261,7 @@ extension SQLSelection { } /// Returns a qualified selection - func qualified(with alias: TableAlias) -> SQLSelection { + func qualified(with alias: TableAliasBase) -> SQLSelection { switch impl { case .qualifiedAllColumns, .qualifiedAllColumnsExcluding: return self diff --git a/GRDB/QueryInterface/SQL/Table.swift b/GRDB/QueryInterface/SQL/Table.swift index 95b3e07db..179800ea0 100644 --- a/GRDB/QueryInterface/SQL/Table.swift +++ b/GRDB/QueryInterface/SQL/Table.swift @@ -745,7 +745,15 @@ extension Table { /// /// `table.aliased(alias)` is equivalent to `table.all().aliased(alias)`. /// See ``TableRequest/aliased(_:)`` for more information. - public func aliased(_ alias: TableAlias) -> QueryInterfaceRequest { + public func aliased(_ alias: TableAlias) -> QueryInterfaceRequest { + all().aliased(alias) + } + + /// Returns a request that can be referred to with the provided alias. + /// + /// `table.aliased(alias)` is equivalent to `table.all().aliased(alias)`. + /// See ``TableRequest/aliased(_:)`` for more information. + public func aliased(_ alias: TableAlias) -> QueryInterfaceRequest { all().aliased(alias) } @@ -1331,12 +1339,17 @@ extension Table { /// - returns: An association to the common table expression. public func association( to cte: CommonTableExpression, - on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible) + on condition: @escaping @Sendable ( + _ left: TableAlias, + _ right: TableAlias + ) -> any SQLExpressible) -> JoinAssociation { JoinAssociation( to: cte.relationForAll, - condition: .expression { condition($0, $1).sqlExpression }) + condition: .expression { left, right in + condition(TableAlias(root: left), TableAlias(root: right)).sqlExpression + }) } /// Creates an association to a common table expression. diff --git a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift index 3a27b5cd8..d4fac3f8d 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift @@ -37,8 +37,8 @@ final class SQLGenerationContext { } } - private let resolvedNames: [TableAlias: String] - private let ownAliases: Set + private let resolvedNames: [TableAliasBase: String] + private let ownAliases: Set private let ownCTEs: [String: SQLCTE] /// Creates a generation context. @@ -50,7 +50,7 @@ final class SQLGenerationContext { init( _ db: Database, argumentsSink: StatementArgumentsSink = StatementArgumentsSink(), - aliases: [TableAlias] = [], + aliases: [TableAliasBase] = [], ctes: OrderedDictionary = [:]) { self.parent = .none(db: db, argumentsSink: argumentsSink) @@ -66,7 +66,7 @@ final class SQLGenerationContext { /// - parameter ctes: An dictionary of available CTEs. private init( parent: SQLGenerationContext, - aliases: [TableAlias], + aliases: [TableAliasBase], ctes: OrderedDictionary) { self.parent = .context(parent) @@ -77,7 +77,7 @@ final class SQLGenerationContext { /// Returns a generation context suitable for subqueries. func subqueryContext( - aliases: [TableAlias] = [], + aliases: [TableAliasBase] = [], ctes: OrderedDictionary = [:]) -> SQLGenerationContext { SQLGenerationContext(parent: self, aliases: aliases, ctes: ctes) @@ -118,7 +118,7 @@ final class SQLGenerationContext { /// /// WHERE column == 1 /// SELECT * - func qualifier(for alias: TableAlias) -> String? { + func qualifier(for alias: TableAliasBase) -> String? { if alias.hasUserName { return alias.identityName } @@ -132,7 +132,7 @@ final class SQLGenerationContext { } /// WHERE MATCH pattern - func resolvedName(for alias: TableAlias) -> String { + func resolvedName(for alias: TableAliasBase) -> String { if let name = resolvedNames[alias] { return name } @@ -145,7 +145,7 @@ final class SQLGenerationContext { } /// FROM tableName - func aliasName(for alias: TableAlias) -> String? { + func aliasName(for alias: TableAliasBase) -> String? { let resolvedName = self.resolvedName(for: alias) if resolvedName != alias.tableName { return resolvedName @@ -244,9 +244,9 @@ class StatementArgumentsSink { } } -extension [TableAlias] { +extension [TableAliasBase] { /// Resolve ambiguities in aliases' names. - fileprivate var resolvedNames: [TableAlias: String] { + fileprivate var resolvedNames: [TableAliasBase: String] { // It is a programmer error to reuse the same TableAlias for // multiple tables. // @@ -262,7 +262,7 @@ extension [TableAlias] { } var uniqueLowercaseNames: Set = [] - var ambiguousGroups: [[TableAlias]] = [] + var ambiguousGroups: [[TableAliasBase]] = [] for (lowercaseName, group) in groups { if group.count > 1 { @@ -276,7 +276,7 @@ extension [TableAlias] { } } - var resolvedNames: [TableAlias: String] = [:] + var resolvedNames: [TableAliasBase: String] = [:] for group in ambiguousGroups { var index = 1 for alias in group { diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index e18a46c32..f4b8fdccf 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -573,7 +573,7 @@ struct SQLQueryGenerator: Refinable { /// LIMIT ... -- limit private struct SQLQualifiedRelation: Sendable { /// All aliases, including aliases of joined relations - var allAliases: [TableAlias] { + var allAliases: [TableAliasBase] { joins.reduce(into: [source.alias].compactMap { $0 }) { $0.append(contentsOf: $1.value.relation.allAliases) } @@ -739,7 +739,7 @@ extension SQLQualifiedRelation: Refinable { } /// A "qualified" source, where all tables are identified with a table alias. private struct SQLQualifiedSource { var tableName: String - var alias: TableAlias + var alias: TableAliasBase init(_ source: SQLSource) { self.tableName = source.tableName @@ -788,13 +788,13 @@ private struct SQLQualifiedJoin: Refinable { self.relation = SQLQualifiedRelation(child.relation) } - func sql(_ context: SQLGenerationContext, leftAlias: TableAlias) throws -> String { + func sql(_ context: SQLGenerationContext, leftAlias: TableAliasBase) throws -> String { try sql(context, leftAlias: leftAlias, allowingInnerJoin: true) } private func sql( _ context: SQLGenerationContext, - leftAlias: TableAlias, + leftAlias: TableAliasBase, allowingInnerJoin allowsInnerJoin: Bool) throws -> String { diff --git a/GRDB/QueryInterface/SQLGeneration/TableAlias.swift b/GRDB/QueryInterface/SQLGeneration/TableAlias.swift index eef2b49d9..0f979255f 100644 --- a/GRDB/QueryInterface/SQLGeneration/TableAlias.swift +++ b/GRDB/QueryInterface/SQLGeneration/TableAlias.swift @@ -3,7 +3,7 @@ /// See ``TableRequest/aliased(_:)`` for more information and examples. /// /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) -public class TableAlias: @unchecked Sendable { +public class TableAliasBase: @unchecked Sendable { // This Sendable conformance is transient. TableAlias IS NOT really Sendable. // TODO: Make TableAlias really Sendable private enum Impl { @@ -50,13 +50,13 @@ public class TableAlias: @unchecked Sendable { /// .including(required: Player.team) /// .filter(sql: "custom.name = 'Arthur'") /// .aliased(customAlias) - case proxy(TableAlias) + case proxy(TableAliasBase) } private var impl: Impl /// Resolve all proxies - private var root: TableAlias { + private var root: TableAliasBase { if case .proxy(let base) = impl { return base.root } else { @@ -107,7 +107,7 @@ public class TableAlias: @unchecked Sendable { /// let alias = TableAlias(name: "p") /// let request = Player.all().aliased(alias) /// ``` - public init(name: String? = nil) { + init(name: String? = nil) { self.impl = .undefined(userName: name) } @@ -115,7 +115,7 @@ public class TableAlias: @unchecked Sendable { self.impl = .table(tableName: tableName, userName: userName) } - func becomeProxy(of base: TableAlias) { + func becomeProxy(of base: TableAliasBase) { if self === base { return } @@ -142,7 +142,7 @@ public class TableAlias: @unchecked Sendable { } /// Returns nil if aliases can't be merged (conflict in tables, aliases...) - func merged(with other: TableAlias) -> TableAlias? { + func merged(with other: TableAliasBase) -> TableAliasBase? { if self === other { return self } @@ -198,7 +198,21 @@ public class TableAlias: @unchecked Sendable { base.setTableName(tableName) } } - +} + +extension TableAliasBase: Equatable { + public static func == (lhs: TableAliasBase, rhs: TableAliasBase) -> Bool { + ObjectIdentifier(lhs.root) == ObjectIdentifier(rhs.root) + } +} + +extension TableAliasBase: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(ObjectIdentifier(root)) + } +} + +extension TableAliasBase { /// Returns a result column that refers to the aliased table. public subscript(_ selectable: some SQLSelectable) -> SQLSelection { // TODO: test @@ -210,14 +224,28 @@ public class TableAlias: @unchecked Sendable { /// For example, let's sort books by author name first, and then by title: /// /// ```swift + /// struct Author: TableRecord { + /// enum Columns { + /// static let name = Column("name") + /// } + /// } + /// + /// struct Book: TableRecord { + /// static let author = belongsTo(Author.self) + /// + /// enum Columns { + /// static let title = Column("title") + /// } + /// } + /// /// // SELECT book.* /// // FROM book /// // JOIN author ON author.id = book.authorId /// // ORDER BY author.name, book.title - /// let authorAlias = TableAlias() + /// let authorAlias = TableAlias() /// let request = Book /// .joining(required: Book.author.aliased(authorAlias)) - /// .order(authorAlias[Column("name")], Column("title")) + /// .order { [authorAlias.name, $0.title] } /// ``` public subscript(_ expression: some SQLSpecificExpressible & SQLSelectable & SQLOrderingTerm) -> SQLExpression { expression.sqlExpression.qualified(with: self) @@ -232,20 +260,6 @@ public class TableAlias: @unchecked Sendable { AnySQLJSONExpressible(sqlExpression: expression.sqlExpression.qualified(with: self)) } - /// Returns an SQL ordering term that refers to the aliased table. - /// - /// For example, let's sort books by author name first, and then by title: - /// - /// ```swift - /// // SELECT book.* - /// // FROM book - /// // JOIN author ON author.id = book.authorId - /// // ORDER BY author.name ASC, book.title ASC - /// let authorAlias = TableAlias() - /// let request = Book - /// .joining(required: Book.author.aliased(authorAlias)) - /// .order(authorAlias[Column("name").asc], Column("title").asc) - /// ``` public subscript(_ ordering: some SQLOrderingTerm) -> SQLOrdering { ordering.sqlOrdering.qualified(with: self) } @@ -267,7 +281,58 @@ public class TableAlias: @unchecked Sendable { public subscript(_ column: String) -> SQLExpression { .qualifiedColumn(column, self) } +} + +// MARK: - TableAlias + +@dynamicMemberLookup +public final class TableAlias: TableAliasBase, @unchecked Sendable { + init(tableName: String, userName: String? = nil) + where RowDecoder == Void + { + super.init(tableName: tableName, userName: userName) + } + init(root: TableAliasBase) { + super.init() + becomeProxy(of: root) + } + + /// Creates a TableAlias. + /// + /// When the alias is given a name, this name is guaranteed to be used as + /// the table alias in the SQL query: + /// + /// ```swift + /// // SELECT p.* FROM player p + /// let alias = TableAlias(name: "p") + /// let request = Player.all().aliased(alias) + /// ``` + public init(name: String? = nil) + where RowDecoder == Void + { + super.init(name: name) + } + + /// Creates a TableAlias for the specified record type. + /// + /// When the alias is given a name, this name is guaranteed to be used as + /// the table alias in the SQL query: + /// + /// ```swift + /// // SELECT p.* FROM player p + /// let alias = TableAlias(name: "p") + /// let request = Player.all().aliased(alias) + /// ``` + public init( + name: String? = nil, + for record: RowDecoder.Type = RowDecoder.self + ) { + super.init(name: name) + } +} + +extension TableAlias { /// A boolean SQL expression indicating whether this alias refers to some /// rows, or not. /// @@ -281,7 +346,7 @@ public class TableAlias: @unchecked Sendable { /// } /// /// try dbQueue.read { db in - /// let authorAlias = TableAlias() + /// let authorAlias = TableAlias() /// let request = Book /// .joining(optional: Book.author.aliased(authorAlias)) /// .filter(!authorAlias.exists) @@ -293,14 +358,69 @@ public class TableAlias: @unchecked Sendable { } } -extension TableAlias: Equatable { - public static func == (lhs: TableAlias, rhs: TableAlias) -> Bool { - ObjectIdentifier(lhs.root) == ObjectIdentifier(rhs.root) - } -} - -extension TableAlias: Hashable { - public func hash(into hasher: inout Hasher) { - hasher.combine(ObjectIdentifier(root)) +extension TableAlias where RowDecoder: TableRecord { + /// Returns a result column that refers to the aliased table. + public subscript( + dynamicMember keyPath: KeyPath + ) -> SQLSelection + where T: SQLSelectable + { + self[RowDecoder.columns[keyPath: keyPath]] + } + + /// Returns an SQL expression that refers to the aliased table. + /// + /// For example, let's sort books by author name first, and then by title: + /// + /// ```swift + /// struct Author: TableRecord { + /// enum Columns { + /// static let name = Column("name") + /// } + /// } + /// + /// struct Book: TableRecord { + /// static let author = belongsTo(Author.self) + /// + /// enum Columns { + /// static let title = Column("title") + /// } + /// } + /// + /// // SELECT book.* + /// // FROM book + /// // JOIN author ON author.id = book.authorId + /// // ORDER BY author.name, book.title + /// let authorAlias = TableAlias() + /// let request = Book + /// .joining(required: Book.author.aliased(authorAlias)) + /// .order { [authorAlias.name, $0.title] } + /// ``` + public subscript( + dynamicMember keyPath: KeyPath + ) -> SQLExpression + where T: SQLSpecificExpressible & + SQLSelectable & + SQLOrderingTerm + { + self[RowDecoder.columns[keyPath: keyPath]] + } + + public subscript( + dynamicMember keyPath: KeyPath + ) -> AnySQLJSONExpressible + where T: SQLJSONExpressible & + SQLSpecificExpressible & + SQLSelectable & + SQLOrderingTerm + { + self[RowDecoder.columns[keyPath: keyPath]] + } + + public subscript( + dynamicMember keyPath: KeyPath + ) -> SQLOrdering + where T: SQLOrderingTerm { + self[RowDecoder.columns[keyPath: keyPath]] } } diff --git a/GRDB/QueryInterface/TableRecord+Association.swift b/GRDB/QueryInterface/TableRecord+Association.swift index e59a634a3..4a3e5620d 100644 --- a/GRDB/QueryInterface/TableRecord+Association.swift +++ b/GRDB/QueryInterface/TableRecord+Association.swift @@ -339,12 +339,17 @@ extension TableRecord { /// - returns: An association to the common table expression. public static func association( to cte: CommonTableExpression, - on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible) + on condition: @escaping @Sendable ( + _ left: TableAlias, + _ right: TableAlias + ) -> any SQLExpressible) -> JoinAssociation { JoinAssociation( to: cte.relationForAll, - condition: .expression { condition($0, $1).sqlExpression }) + condition: .expression { left, right in + condition(TableAlias(root: left), TableAlias(root: right)).sqlExpression + }) } /// Creates an association to a common table expression. diff --git a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift index 530d88d73..ed8761379 100644 --- a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift @@ -749,7 +749,44 @@ extension TableRecord { /// ``` /// /// See ``TableRequest/aliased(_:)`` for more information. - public static func aliased(_ alias: TableAlias) -> QueryInterfaceRequest { + public static func aliased(_ alias: TableAlias) -> QueryInterfaceRequest { + all().aliased(alias) + } + + /// Returns a request that can be referred to with the provided alias. + /// + /// Use this method when you need to refer to this table from + /// another request. + /// + /// For example, the request below fetches posthumous books: + /// + /// ```swift + /// struct Author: TableRecord { + /// enum Columns { + /// static let deathDate = Column("deathDate") + /// } + /// } + /// + /// struct Book: TableRecord { + /// static let author = belongsTo(Author.self) + /// + /// enum Columns { + /// static let publishDate = Column("publishDate") + /// } + /// } + /// + /// // SELECT book.* + /// // FROM book + /// // JOIN author ON author.id = book.authorId + /// // AND author.deathDate <= book.publishDate + /// let bookAlias = TableAlias() + /// let request = Book + /// .aliased(bookAlias) + /// .joining(required: Book.author.filter { $0.deathDate <= bookAlias.publishDate }) + /// ``` + /// + /// See ``TableRequest/aliased(_:)`` for more information. + public static func aliased(_ alias: TableAlias) -> QueryInterfaceRequest { all().aliased(alias) } diff --git a/GRDB/Record/MutablePersistableRecord+DAO.swift b/GRDB/Record/MutablePersistableRecord+DAO.swift index 82d8b199d..de15f6e87 100644 --- a/GRDB/Record/MutablePersistableRecord+DAO.swift +++ b/GRDB/Record/MutablePersistableRecord+DAO.swift @@ -42,8 +42,11 @@ final class DAO { func upsertStatement( _ db: Database, onConflict conflictTargetColumns: [String], - doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])?, - updateCondition: ((_ existing: TableAlias, _ excluded: TableAlias) -> any SQLExpressible)? = nil, + doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])?, + updateCondition: (( + _ existing: TableAlias, + _ excluded: TableAlias + ) -> any SQLExpressible)? = nil, returning selection: [any SQLSelectable]) throws -> Statement { @@ -73,7 +76,7 @@ final class DAO { // that no information stored in the record is lost, unless explicitly // requested by the user. sql += " DO UPDATE SET " - let excluded = TableAlias(name: "excluded") + let excluded = TableAlias(name: "excluded") var assignments = assignments?(excluded) ?? [] let lowercaseExcludedColumns = Set(primaryKey.columns.map { $0.lowercased() }) .union(conflictTargetColumns.map { $0.lowercased() }) @@ -119,7 +122,7 @@ final class DAO { } // WHERE - let existing = TableAlias(name: databaseTableName) + let existing = TableAlias(name: databaseTableName) if let condition = updateCondition?(existing, excluded) { let context = SQLGenerationContext(db) sql += try " WHERE " + condition.sqlExpression.sql(context) @@ -253,7 +256,7 @@ final class DAO { // Make sure the selection is qualified with a table alias, so // that selectables such as `.allColumns(excluding:)` can query // the database about the database table. - let alias = TableAlias(tableName: databaseTableName) + let alias = TableAliasBase(tableName: databaseTableName) let context = SQLGenerationContext(db, aliases: [alias]) var sql = sql var arguments = arguments diff --git a/GRDB/Record/MutablePersistableRecord+Upsert.swift b/GRDB/Record/MutablePersistableRecord+Upsert.swift index 567feee50..60699968a 100644 --- a/GRDB/Record/MutablePersistableRecord+Upsert.swift +++ b/GRDB/Record/MutablePersistableRecord+Upsert.swift @@ -128,7 +128,7 @@ extension MutablePersistableRecord { public mutating func upsertAndFetch( _ db: Database, onConflict conflictTarget: [String] = [], - doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) + doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) throws -> Self where Self: FetchableRecord { @@ -156,7 +156,7 @@ extension MutablePersistableRecord { _ db: Database, as returnedType: T.Type, onConflict conflictTarget: [String] = [], - doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) + doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) throws -> T { try willSave(db) @@ -306,7 +306,7 @@ extension MutablePersistableRecord { public mutating func upsertAndFetch( _ db: Database, onConflict conflictTarget: [String] = [], - doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) + doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) throws -> Self where Self: FetchableRecord { @@ -335,7 +335,7 @@ extension MutablePersistableRecord { _ db: Database, as returnedType: T.Type, onConflict conflictTarget: [String] = [], - doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) + doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) throws -> T { try willSave(db) @@ -378,7 +378,7 @@ extension MutablePersistableRecord { mutating func upsertAndFetchWithCallbacks( _ db: Database, onConflict conflictTarget: [String], - doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])?, + doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])?, selection: [any SQLSelectable], decode: (Row) throws -> T) throws -> (InsertionSuccess, T) @@ -408,7 +408,7 @@ extension MutablePersistableRecord { func upsertAndFetchWithoutCallbacks( _ db: Database, onConflict conflictTarget: [String], - doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])?, + doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])?, selection: [any SQLSelectable], decode: (Row) throws -> T) throws -> (InsertionSuccess, T) diff --git a/GRDB/Record/PersistableRecord+Upsert.swift b/GRDB/Record/PersistableRecord+Upsert.swift index af1a68807..eea951e39 100644 --- a/GRDB/Record/PersistableRecord+Upsert.swift +++ b/GRDB/Record/PersistableRecord+Upsert.swift @@ -128,7 +128,7 @@ extension PersistableRecord { public func upsertAndFetch( _ db: Database, onConflict conflictTarget: [String] = [], - doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) + doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) throws -> Self where Self: FetchableRecord { @@ -156,7 +156,7 @@ extension PersistableRecord { _ db: Database, as returnedType: T.Type, onConflict conflictTarget: [String] = [], - doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) + doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) throws -> T { try willSave(db) @@ -306,7 +306,7 @@ extension PersistableRecord { public func upsertAndFetch( _ db: Database, onConflict conflictTarget: [String] = [], - doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) + doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) throws -> Self where Self: FetchableRecord { @@ -335,7 +335,7 @@ extension PersistableRecord { _ db: Database, as returnedType: T.Type, onConflict conflictTarget: [String] = [], - doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) + doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) throws -> T { try willSave(db) @@ -378,7 +378,7 @@ extension PersistableRecord { func upsertAndFetchWithCallbacks( _ db: Database, onConflict conflictTarget: [String], - doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])?, + doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])?, selection: [any SQLSelectable], decode: (Row) throws -> T) throws -> (InsertionSuccess, T)