From 0098369e293edb63df0e008f05886cb61a49b678 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 27 Jun 2021 11:26:41 +0200 Subject: [PATCH] Simplify Refinable --- .../Request/Association/Association.swift | 139 +++++++++++++----- .../Association/AssociationAggregate.swift | 9 +- .../Association/BelongsToAssociation.swift | 5 - .../Association/HasManyAssociation.swift | 5 - .../HasManyThroughAssociation.swift | 5 - .../Association/HasOneAssociation.swift | 5 - .../HasOneThroughAssociation.swift | 5 - .../Request/Association/JoinAssociation.swift | 5 - .../Request/QueryInterfaceRequest.swift | 90 +++++++++--- GRDB/QueryInterface/SQL/SQLAssociation.swift | 8 +- GRDB/QueryInterface/SQL/SQLRelation.swift | 114 ++++++++------ GRDB/QueryInterface/SQL/Table.swift | 4 +- .../SQLGeneration/SQLQueryGenerator.swift | 29 ++-- .../TableRecord+Association.swift | 10 +- GRDB/Utils/Refinable.swift | 54 +------ GRDB/ValueObservation/ValueObservation.swift | 19 ++- 16 files changed, 292 insertions(+), 214 deletions(-) diff --git a/GRDB/QueryInterface/Request/Association/Association.swift b/GRDB/QueryInterface/Request/Association/Association.swift index 569f6429c..c6714f9c9 100644 --- a/GRDB/QueryInterface/Request/Association/Association.swift +++ b/GRDB/QueryInterface/Request/Association/Association.swift @@ -4,8 +4,7 @@ import Foundation /// /// :nodoc: public protocol _Association { - init(sqlAssociation: _SQLAssociation) - var _sqlAssociation: _SQLAssociation { get } + var _sqlAssociation: _SQLAssociation { get set } } /// The base protocol for all associations that define a connection between two @@ -45,35 +44,57 @@ public protocol Association: _Association, DerivableRequest { } extension Association { - /// :nodoc: - public func _including(all association: _SQLAssociation) -> Self { - mapDestinationRelation { $0._including(all: association) } + /// Returns self modified with the *update* function. + @inline(__always) + func with(_ update: (inout Self) throws -> Void) rethrows -> Self { + var result = self + try update(&result) + return result } - /// :nodoc: - public func _including(optional association: _SQLAssociation) -> Self { - mapDestinationRelation { $0._including(optional: association) } - } - - /// :nodoc: - public func _including(required association: _SQLAssociation) -> Self { - mapDestinationRelation { $0._including(required: association) } - } - - /// :nodoc: - public func _joining(optional association: _SQLAssociation) -> Self { - mapDestinationRelation { $0._joining(optional: association) } - } - - /// :nodoc: - public func _joining(required association: _SQLAssociation) -> Self { - mapDestinationRelation { $0._joining(required: association) } + /// Returns self with destination relation modified with the *update* function. + @inline(__always) + fileprivate func withDestinationRelation(_ update: (inout SQLRelation) throws -> Void) rethrows -> Self { + var result = self + try update(&result._sqlAssociation.destination.relation) + return result } } extension Association { - fileprivate func mapDestinationRelation(_ transform: (SQLRelation) -> SQLRelation) -> Self { - .init(sqlAssociation: _sqlAssociation.map(\.destination.relation, transform)) + /// :nodoc: + public func _including(all association: _SQLAssociation) -> Self { + withDestinationRelation { relation in + relation = relation._including(all: association) + } + } + + /// :nodoc: + public func _including(optional association: _SQLAssociation) -> Self { + withDestinationRelation { relation in + relation = relation._including(optional: association) + } + } + + /// :nodoc: + public func _including(required association: _SQLAssociation) -> Self { + withDestinationRelation { relation in + relation = relation._including(required: association) + } + } + + /// :nodoc: + public func _joining(optional association: _SQLAssociation) -> Self { + withDestinationRelation { relation in + relation = relation._joining(optional: association) + } + } + + /// :nodoc: + public func _joining(required association: _SQLAssociation) -> Self { + withDestinationRelation { relation in + relation = relation._joining(required: association) + } } } @@ -159,7 +180,9 @@ extension Association { /// .including(required: Player.team.aliased(teamAlias)) /// .filter(sql: "custom.color = ?", arguments: ["red"]) public func aliased(_ alias: TableAlias) -> Self { - mapDestinationRelation { $0.aliased(alias) } + withDestinationRelation { relation in + relation = relation.aliased(alias) + } } } @@ -188,7 +211,11 @@ extension Association { /// .select { db in [Column("color") } /// var request = Player.including(required: association) public func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> Self { - mapDestinationRelation { $0.select { try selection($0).map(\.sqlSelection) } } + withDestinationRelation { relation in + relation = relation.select { db in + try selection(db).map(\.sqlSelection) + } + } } /// Creates an association which appends *selection*. @@ -205,7 +232,11 @@ extension Association { /// .annotated(with: { db in [Column("name")] }) /// var request = Player.including(required: association) public func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> Self { - mapDestinationRelation { $0.annotated { try selection($0).map(\.sqlSelection) } } + withDestinationRelation { relation in + relation = relation.annotated { db in + try selection(db).map(\.sqlSelection) + } + } } } @@ -224,7 +255,11 @@ extension Association { /// let association = Player.team.filter { db in true } /// var request = Player.including(required: association) public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self { - mapDestinationRelation { $0.filter { try predicate($0).sqlExpression } } + withDestinationRelation { relation in + relation = relation.filter { db in + try predicate(db).sqlExpression + } + } } } @@ -255,7 +290,11 @@ extension Association { /// .order{ _ in [Column("name")] } /// var request = Player.including(required: association) public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> Self { - mapDestinationRelation { $0.order { try orderings($0).map(\.sqlOrdering) } } + withDestinationRelation { relation in + relation = relation.order { db in + try orderings(db).map(\.sqlOrdering) + } + } } /// Creates an association that reverses applied orderings. @@ -279,7 +318,9 @@ extension Association { /// let association = Player.team.reversed() /// var request = Player.including(required: association) public func reversed() -> Self { - mapDestinationRelation { $0.reversed() } + withDestinationRelation { relation in + relation = relation.reversed() + } } /// Creates an association without any ordering. @@ -294,7 +335,9 @@ extension Association { /// let association = Player.team.order(Column("name")).unordered() /// var request = Player.including(required: association) public func unordered() -> Self { - mapDestinationRelation { $0.unordered() } + withDestinationRelation { relation in + relation = relation.unordered() + } } } @@ -309,13 +352,21 @@ extension Association { extension Association { /// Creates an association grouped according to *expressions promise*. public func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> Self { - mapDestinationRelation { $0.group { try expressions($0).map(\.sqlExpression) } } + withDestinationRelation { relation in + relation = relation.group { db in + try expressions(db).map(\.sqlExpression) + } + } } /// Creates an association with the provided *predicate promise* added to /// the eventual set of already applied predicates. public func having(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self { - mapDestinationRelation { $0.having { try predicate($0).sqlExpression } } + withDestinationRelation { relation in + relation = relation.having { db in + try predicate(db).sqlExpression + } + } } } @@ -323,7 +374,9 @@ extension Association { extension Association { /// Creates an association for returns distinct rows. public func distinct() -> Self { - mapDestinationRelation { $0.with(\.isDistinct, true) } + withDestinationRelation { relation in + relation.isDistinct = true + } } /// Creates an association that fetches *limit* rows, starting at *offset*. @@ -335,14 +388,18 @@ extension Association { /// /// :nodoc: public func limit(_ limit: Int, offset: Int? = nil) -> Self { - mapDestinationRelation { $0.with(\.limit, SQLLimit(limit: limit, offset: offset)) } + withDestinationRelation { relation in + relation.limit = SQLLimit(limit: limit, offset: offset) + } } /// Returns an association that embeds the common table expression. /// /// See `QueryInterfaceRequest.with(_:)` for more information. public func with(_ cte: CommonTableExpression) -> Self { - mapDestinationRelation { $0.with(\.ctes[cte.tableName], cte.cte) } + withDestinationRelation { relation in + relation.ctes[cte.tableName] = cte.cte + } } } @@ -354,7 +411,9 @@ public protocol AssociationToOne: Association { } extension AssociationToOne { public func forKey(_ key: String) -> Self { let associationKey = SQLAssociationKey.fixedSingular(key) - return .init(sqlAssociation: _sqlAssociation.forDestinationKey(associationKey)) + return with { + $0._sqlAssociation = $0._sqlAssociation.forDestinationKey(associationKey) + } } } @@ -366,6 +425,8 @@ public protocol AssociationToMany: Association { } extension AssociationToMany { public func forKey(_ key: String) -> Self { let associationKey = SQLAssociationKey.fixedPlural(key) - return .init(sqlAssociation: _sqlAssociation.forDestinationKey(associationKey)) + return with { + $0._sqlAssociation = $0._sqlAssociation.forDestinationKey(associationKey) + } } } diff --git a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift index 4d46a616d..1813bb570 100644 --- a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift +++ b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift @@ -344,7 +344,9 @@ extension AssociationAggregate: Refinable { /// let numberOfBooks: Int = row["numberOfBooks"] /// } public func forKey(_ key: String) -> Self { - with(\.key, key) + with { + $0.key = key + } } /// Returns an aggregate that is selected in a column named like the given @@ -1088,8 +1090,9 @@ public func ?? ( rhs: SQLExpressible) -> AssociationAggregate { - // Preserve key - lhs.map { $0 ?? rhs }.with(\.key, lhs.key) + lhs + .map { $0 ?? rhs } + .with { $0.key = lhs.key } // Preserve key } // TODO: add support for ABS(aggregate) diff --git a/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift b/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift index 435d76725..56d6d8938 100644 --- a/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift @@ -68,11 +68,6 @@ public struct BelongsToAssociation: AssociationToOne { /// :nodoc: public var _sqlAssociation: _SQLAssociation - /// :nodoc: - public init(sqlAssociation: _SQLAssociation) { - self._sqlAssociation = sqlAssociation - } - init( to destinationRelation: SQLRelation, key: String?, diff --git a/GRDB/QueryInterface/Request/Association/HasManyAssociation.swift b/GRDB/QueryInterface/Request/Association/HasManyAssociation.swift index ad74dfbda..4d200177d 100644 --- a/GRDB/QueryInterface/Request/Association/HasManyAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/HasManyAssociation.swift @@ -68,11 +68,6 @@ public struct HasManyAssociation: AssociationToMany { /// :nodoc: public var _sqlAssociation: _SQLAssociation - /// :nodoc: - public init(sqlAssociation: _SQLAssociation) { - self._sqlAssociation = sqlAssociation - } - init( to destinationRelation: SQLRelation, key: String?, diff --git a/GRDB/QueryInterface/Request/Association/HasManyThroughAssociation.swift b/GRDB/QueryInterface/Request/Association/HasManyThroughAssociation.swift index e2d3eeb91..51eda18de 100644 --- a/GRDB/QueryInterface/Request/Association/HasManyThroughAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/HasManyThroughAssociation.swift @@ -50,9 +50,4 @@ public struct HasManyThroughAssociation: AssociationToMany /// :nodoc: public var _sqlAssociation: _SQLAssociation - - /// :nodoc: - public init(sqlAssociation: _SQLAssociation) { - self._sqlAssociation = sqlAssociation - } } diff --git a/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift b/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift index 020b34b9f..0150ee6cd 100644 --- a/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift @@ -70,11 +70,6 @@ public struct HasOneAssociation: AssociationToOne { /// :nodoc: public var _sqlAssociation: _SQLAssociation - /// :nodoc: - public init(sqlAssociation: _SQLAssociation) { - self._sqlAssociation = sqlAssociation - } - init( to destinationRelation: SQLRelation, key: String?, diff --git a/GRDB/QueryInterface/Request/Association/HasOneThroughAssociation.swift b/GRDB/QueryInterface/Request/Association/HasOneThroughAssociation.swift index 7d7027496..b77569198 100644 --- a/GRDB/QueryInterface/Request/Association/HasOneThroughAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/HasOneThroughAssociation.swift @@ -30,9 +30,4 @@ public struct HasOneThroughAssociation: AssociationToOne { /// :nodoc: public var _sqlAssociation: _SQLAssociation - - /// :nodoc: - public init(sqlAssociation: _SQLAssociation) { - self._sqlAssociation = sqlAssociation - } } diff --git a/GRDB/QueryInterface/Request/Association/JoinAssociation.swift b/GRDB/QueryInterface/Request/Association/JoinAssociation.swift index 8578d2705..3e142448b 100644 --- a/GRDB/QueryInterface/Request/Association/JoinAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/JoinAssociation.swift @@ -10,11 +10,6 @@ public struct JoinAssociation: AssociationToOne { /// :nodoc: public var _sqlAssociation: _SQLAssociation - /// :nodoc: - public init(sqlAssociation: _SQLAssociation) { - self._sqlAssociation = sqlAssociation - } - /// Creates a `JoinAssociation` whose key is the table name of the relation. init( to relation: SQLRelation, diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index 861751180..b4ccfb679 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -77,7 +77,11 @@ extension QueryInterfaceRequest: SelectionRequest { /// .select { db in [Column("id")] } /// .select { db in [Column("email")] } public func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> QueryInterfaceRequest { - map(\.relation) { $0.select { try selection($0).map(\.sqlSelection) } } + with { + $0.relation = $0.relation.select { db in + try selection(db).map(\.sqlSelection) + } + } } /// Creates a request which selects *selection*, and fetches values of @@ -153,7 +157,11 @@ extension QueryInterfaceRequest: SelectionRequest { /// .select([Column("id"), Column("email")]) /// .annotated(with: { db in [Column("name")] }) public func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> QueryInterfaceRequest { - map(\.relation) { $0.annotated { try selection($0).map(\.sqlSelection) } } + with { + $0.relation = $0.relation.annotated { db in + try selection(db).map(\.sqlSelection) + } + } } } @@ -206,7 +214,11 @@ extension QueryInterfaceRequest: FilteredRequest { /// var request = Player.all() /// request = request.filter { db in true } public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest { - map(\.relation) { $0.filter { try predicate($0).sqlExpression } } + with { + $0.relation = $0.relation.filter { db in + try predicate(db).sqlExpression + } + } } } @@ -225,7 +237,11 @@ extension QueryInterfaceRequest: OrderedRequest { /// .reversed() /// .order{ _ in [Column("name")] } public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> QueryInterfaceRequest { - map(\.relation) { $0.order { try orderings($0).map(\.sqlOrdering) } } + with { + $0.relation = $0.relation.order { db in + try orderings(db).map(\.sqlOrdering) + } + } } /// Creates a request that reverses applied orderings. @@ -240,7 +256,9 @@ extension QueryInterfaceRequest: OrderedRequest { /// var request = Player.all() /// request = request.reversed() public func reversed() -> QueryInterfaceRequest { - map(\.relation) { $0.reversed() } + with { + $0.relation = $0.relation.reversed() + } } /// Creates a request without any ordering. @@ -249,20 +267,30 @@ extension QueryInterfaceRequest: OrderedRequest { /// var request = Player.all().order(Column("name")) /// request = request.unordered() public func unordered() -> QueryInterfaceRequest { - map(\.relation) { $0.unordered() } + with { + $0.relation = $0.relation.unordered() + } } } extension QueryInterfaceRequest: AggregatingRequest { /// Creates a request grouped according to *expressions promise*. public func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> QueryInterfaceRequest { - map(\.relation) { $0.group { try expressions($0).map(\.sqlExpression) } } + with { + $0.relation = $0.relation.group { db in + try expressions(db).map(\.sqlExpression) + } + } } /// Creates a request with the provided *predicate promise* added to the /// eventual set of already applied predicates. public func having(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest { - map(\.relation) { $0.having { try predicate($0).sqlExpression } } + with { + $0.relation = $0.relation.having { db in + try predicate(db).sqlExpression + } + } } } @@ -270,27 +298,37 @@ extension QueryInterfaceRequest: AggregatingRequest { extension QueryInterfaceRequest: _JoinableRequest { /// :nodoc: public func _including(all association: _SQLAssociation) -> QueryInterfaceRequest { - map(\.relation) { $0._including(all: association) } + with { + $0.relation = $0.relation._including(all: association) + } } /// :nodoc: public func _including(optional association: _SQLAssociation) -> QueryInterfaceRequest { - map(\.relation) { $0._including(optional: association) } + with { + $0.relation = $0.relation._including(optional: association) + } } /// :nodoc: public func _including(required association: _SQLAssociation) -> QueryInterfaceRequest { - map(\.relation) { $0._including(required: association) } + with { + $0.relation = $0.relation._including(required: association) + } } /// :nodoc: public func _joining(optional association: _SQLAssociation) -> QueryInterfaceRequest { - map(\.relation) { $0._joining(optional: association) } + with { + $0.relation = $0.relation._joining(optional: association) + } } /// :nodoc: public func _joining(required association: _SQLAssociation) -> QueryInterfaceRequest { - map(\.relation) { $0._joining(required: association) } + with { + $0.relation = $0.relation._joining(required: association) + } } } @@ -320,13 +358,17 @@ extension QueryInterfaceRequest: TableRequest { /// .aliased(playerAlias) /// .including(required: Player.team.filter(Column("avgScore") < playerAlias[Column("score")]) public func aliased(_ alias: TableAlias) -> QueryInterfaceRequest { - map(\.relation) { $0.aliased(alias) } + with { + $0.relation = $0.relation.aliased(alias) + } } } extension QueryInterfaceRequest: DerivableRequest { public func distinct() -> QueryInterfaceRequest { - with(\.relation.isDistinct, true) + with { + $0.relation.isDistinct = true + } } /// Creates a request which fetches *limit* rows, starting at *offset*. @@ -337,11 +379,15 @@ extension QueryInterfaceRequest: DerivableRequest { /// /// Any previous limit is replaced. public func limit(_ limit: Int, offset: Int?) -> QueryInterfaceRequest { - with(\.relation.limit, SQLLimit(limit: limit, offset: offset)) + with { + $0.relation.limit = SQLLimit(limit: limit, offset: offset) + } } public func with(_ cte: CommonTableExpression) -> Self { - with(\.relation.ctes[cte.tableName], cte.cte) + with { + $0.relation.ctes[cte.tableName] = cte.cte + } } } @@ -711,7 +757,11 @@ func makePrefetchRequest( let pivotAlias = TableAlias() let prefetchRelation = association - .map(\.pivot.relation, { $0.aliased(pivotAlias).filter(pivotFilter) }) + .with { + $0.pivot.relation = $0.pivot.relation + .aliased(pivotAlias) + .filter(pivotFilter) + } .destinationRelation() .annotated(with: pivotColumns.map { pivotAlias[$0].forKey("grdb_\($0)") }) @@ -756,7 +806,9 @@ throws -> DatabaseRegion let pivotFilter = pivotMapping.joinExpression(leftRows: [DummyRow()]) let prefetchRelation = association - .map(\.pivot.relation) { $0.filter(pivotFilter) } + .with { + $0.pivot.relation = $0.pivot.relation.filter(pivotFilter) + } .destinationRelation() return try SQLQueryGenerator(relation: prefetchRelation) diff --git a/GRDB/QueryInterface/SQL/SQLAssociation.swift b/GRDB/QueryInterface/SQL/SQLAssociation.swift index 3e6585cf1..f756bc22d 100644 --- a/GRDB/QueryInterface/SQL/SQLAssociation.swift +++ b/GRDB/QueryInterface/SQL/SQLAssociation.swift @@ -87,7 +87,9 @@ public struct _SQLAssociation { /// Changes the destination key func forDestinationKey(_ key: SQLAssociationKey) -> Self { - with(\.destination.key, key) + with { + $0.destination.key = key + } } /// Returns a new association @@ -126,7 +128,9 @@ public struct _SQLAssociation { .removingChildrenForPrefetchedAssociations() // Don't interfere with user-defined keys that could be added later - let key = step.key.map(\.baseName) { "grdb_\($0)" } + let key = step.key.with { + $0.baseName = "grdb_\($0.baseName)" + } return SQLAssociationStep( key: key, diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index dd4759c52..310c3a152 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -190,7 +190,9 @@ extension SQLRelation { extension SQLRelation: Refinable { func select(_ selection: @escaping (Database) throws -> [SQLSelection]) -> Self { - with(\.selectionPromise, DatabasePromise(selection)) + with { + $0.selectionPromise = DatabasePromise(selection) + } } // Convenience @@ -208,18 +210,21 @@ extension SQLRelation: Refinable { func selectOnly(_ selection: [SQLSelection]) -> Self { self .select(selection) - .with(\.isDistinct, false) - .map(\.children) { children in - children.mapValues { child in - child.map(\.relation) { $0.selectOnly([]) } + .with { + $0.isDistinct = false + $0.children = children.mapValues { child in + child.with { + $0.relation = $0.relation.selectOnly([]) + } } } } func annotated(with selection: @escaping (Database) throws -> [SQLSelection]) -> Self { - map(\.selectionPromise) { selectionPromise in - DatabasePromise { db in - try selectionPromise.resolve(db) + selection(db) + with { + let old = $0.selectionPromise + $0.selectionPromise = DatabasePromise { db in + try old.resolve(db) + selection(db) } } } @@ -230,13 +235,13 @@ extension SQLRelation: Refinable { } func filter(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self { - map(\.filterPromise) { promise in - DatabasePromise { db in - if let filter = try promise?.resolve(db) { - return try filter && predicate(db) - } else { - return try predicate(db) + with { + if let old = $0.filterPromise { + $0.filterPromise = DatabasePromise { db in + try old.resolve(db) && predicate(db) } + } else { + $0.filterPromise = DatabasePromise(predicate) } } } @@ -247,41 +252,50 @@ extension SQLRelation: Refinable { } func order(_ orderings: @escaping (Database) throws -> [SQLOrdering]) -> Self { - with(\.ordering, SQLRelation.Ordering(orderings: orderings)) + with { + $0.ordering = SQLRelation.Ordering(orderings: orderings) + } } func reversed() -> Self { - map(\.ordering, \.reversed) + with { + $0.ordering = $0.ordering.reversed + } } func unordered() -> Self { - self - .with(\.ordering, SQLRelation.Ordering()) - .map(\.children) { children in - children.mapValues { child in - child.map(\.relation) { $0.unordered() } - } - } - } - - func group(_ expressions: @escaping (Database) throws -> [SQLExpression]) -> Self { - with(\.groupPromise, DatabasePromise(expressions)) - } - - func having(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self { - map(\.havingExpressionPromise) { promise in - DatabasePromise { db in - if let filter = try promise?.resolve(db) { - return try filter && predicate(db) - } else { - return try predicate(db) + with { + $0.ordering = SQLRelation.Ordering() + $0.children = children.mapValues { child in + child.with { + $0.relation = $0.relation.unordered() } } } } + func group(_ expressions: @escaping (Database) throws -> [SQLExpression]) -> Self { + with { + $0.groupPromise = DatabasePromise(expressions) + } + } + + func having(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self { + with { + if let old = $0.havingExpressionPromise { + $0.havingExpressionPromise = DatabasePromise { db in + try old.resolve(db) && predicate(db) + } + } else { + $0.havingExpressionPromise = DatabasePromise(predicate) + } + } + } + func aliased(_ alias: TableAlias) -> Self { - map(\.source) { $0.aliased(alias) } + with { + $0.source = $0.source.aliased(alias) + } } } @@ -296,9 +310,9 @@ extension SQLRelation { return child.relation.prefetchedAssociations.map { association in // Remove redundant pivot child let pivotKey = association.pivot.keyName - let child = child.map(\.relation) { relation in - assert(relation.children[pivotKey] != nil) - return relation.removingChild(forKey: pivotKey) + let child = child.with { + assert($0.relation.children[pivotKey] != nil) + $0.relation = $0.relation.removingChild(forKey: pivotKey) } return association.through(child.makeAssociationForKey(key)) } @@ -488,11 +502,15 @@ extension SQLRelation { } func removingChild(forKey key: String) -> Self { - mapInto(\.children) { $0.removeValue(forKey: key) } + with { + $0.children.removeValue(forKey: key) + } } func filteringChildren(_ included: (Child) throws -> Bool) rethrows -> Self { - try map(\.children) { try $0.filter { try included($1) } } + try with { + $0.children = try $0.children.filter { (_, child) in try included(child) } + } } func removingChildrenForPrefetchedAssociations() -> Self { @@ -519,11 +537,19 @@ extension SQLRelation { } func _joining(optional association: _SQLAssociation) -> Self { - appendingChild(for: association.map(\.destination.relation, { $0.select([]) }), kind: .oneOptional) + // Remove association selection + let associationWithEmptySelection = association.with { + $0.destination.relation = $0.destination.relation.select([]) + } + return appendingChild(for: associationWithEmptySelection, kind: .oneOptional) } func _joining(required association: _SQLAssociation) -> Self { - appendingChild(for: association.map(\.destination.relation, { $0.select([]) }), kind: .oneRequired) + // Remove association selection + let associationWithEmptySelection = association.with { + $0.destination.relation = $0.destination.relation.select([]) + } + return appendingChild(for: associationWithEmptySelection, kind: .oneRequired) } } diff --git a/GRDB/QueryInterface/SQL/Table.swift b/GRDB/QueryInterface/SQL/Table.swift index 0fef926a7..2a6481328 100644 --- a/GRDB/QueryInterface/SQL/Table.swift +++ b/GRDB/QueryInterface/SQL/Table.swift @@ -1087,7 +1087,7 @@ extension Table { Pivot.RowDecoder == Target.OriginRowDecoder { let association = HasManyThroughAssociation( - sqlAssociation: target._sqlAssociation.through(pivot._sqlAssociation)) + _sqlAssociation: target._sqlAssociation.through(pivot._sqlAssociation)) if let key = key { return association.forKey(key) @@ -1120,7 +1120,7 @@ extension Table { Pivot.RowDecoder == Target.OriginRowDecoder { let association = HasOneThroughAssociation( - sqlAssociation: target._sqlAssociation.through(pivot._sqlAssociation)) + _sqlAssociation: target._sqlAssociation.through(pivot._sqlAssociation)) if let key = key { return association.forKey(key) diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 00a1f4f43..b61ebd9ce 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -245,11 +245,14 @@ struct SQLQueryGenerator: Refinable { let context = SQLGenerationContext(db, aliases: [alias]) let subqueryContext = context.subqueryContext(aliases: relation.allAliases, ctes: relation.ctes) let primaryKey = SQLExpression.fastPrimaryKey + let selectPrimaryKey = self.with { + $0.relation = $0.relation.selectOnly([.expression(primaryKey)]) + } var sql = "DELETE FROM \(tableName.quotedDatabaseIdentifier) WHERE " sql += try alias[primaryKey].sql(context) sql += " IN (" - sql += try map(\.relation, { $0.selectOnly([.expression(primaryKey)]) }).requestSQL(subqueryContext) + sql += try selectPrimaryKey.requestSQL(subqueryContext) sql += ")" let statement = try db.makeUpdateStatement(sql: sql) @@ -343,6 +346,9 @@ struct SQLQueryGenerator: Refinable { let context = SQLGenerationContext(db, aliases: [alias]) let subqueryContext = context.subqueryContext(aliases: relation.allAliases, ctes: relation.ctes) let primaryKey = SQLExpression.fastPrimaryKey + let selectPrimaryKey = self.with { + $0.relation = $0.relation.selectOnly([.expression(primaryKey)]) + } // UPDATE table... var sql = "UPDATE " @@ -361,7 +367,7 @@ struct SQLQueryGenerator: Refinable { sql += " WHERE " sql += try alias[primaryKey].sql(context) sql += " IN (" - sql += try map(\.relation, { $0.selectOnly([.expression(primaryKey)]) }).requestSQL(subqueryContext) + sql += try selectPrimaryKey.requestSQL(subqueryContext) sql += ")" let statement = try db.makeUpdateStatement(sql: sql) @@ -654,17 +660,18 @@ private struct SQLQualifiedRelation { /// Sets the selection, removes all selections from joins, and clears the /// `isDistinct` flag. func selectOnly(_ selection: [SQLSelection]) -> Self { - let sourceSelectionPromise = DatabasePromise(value: selection.map { + let qualifiedSelection = selection.map { $0.qualified(with: source.alias) - }) - return self - .with(\.sourceSelectionPromise, sourceSelectionPromise) - .with(\.isDistinct, false) - .map(\.joins, { joins in - joins.mapValues { join in - join.map(\.relation) { $0.selectOnly([]) } + } + return with { + $0.sourceSelectionPromise = DatabasePromise(value: qualifiedSelection) + $0.isDistinct = false + $0.joins = $0.joins.mapValues { join in + join.with { + $0.relation = $0.relation.selectOnly([]) } - }) + } + } } } diff --git a/GRDB/QueryInterface/TableRecord+Association.swift b/GRDB/QueryInterface/TableRecord+Association.swift index 12fa6d111..7c2fdaee6 100644 --- a/GRDB/QueryInterface/TableRecord+Association.swift +++ b/GRDB/QueryInterface/TableRecord+Association.swift @@ -436,7 +436,7 @@ extension TableRecord { Pivot.RowDecoder == Target.OriginRowDecoder { let association = HasManyThroughAssociation( - sqlAssociation: target._sqlAssociation.through(pivot._sqlAssociation)) + _sqlAssociation: target._sqlAssociation.through(pivot._sqlAssociation)) if let key = key { return association.forKey(key) @@ -518,7 +518,7 @@ extension TableRecord { Pivot.RowDecoder == Target.OriginRowDecoder { let association = HasOneThroughAssociation( - sqlAssociation: target._sqlAssociation.through(pivot._sqlAssociation)) + _sqlAssociation: target._sqlAssociation.through(pivot._sqlAssociation)) if let key = key { return association.forKey(key) @@ -556,14 +556,14 @@ extension TableRecord where Self: EncodableRecord { case let .foreignKey(foreignKey): let destinationRelation = association ._sqlAssociation - .map(\.pivot.relation, { pivotRelation in - pivotRelation.filter { db in + .with { + $0.pivot.relation = $0.pivot.relation.filter { db in // Filter the pivot on self try foreignKey .joinMapping(db, from: Self.databaseTableName) .joinExpression(leftRows: [PersistenceContainer(db, self)]) } - }) + } .destinationRelation() return QueryInterfaceRequest(relation: destinationRelation) } diff --git a/GRDB/Utils/Refinable.swift b/GRDB/Utils/Refinable.swift index ea4b1a065..253cbf8d4 100644 --- a/GRDB/Utils/Refinable.swift +++ b/GRDB/Utils/Refinable.swift @@ -10,13 +10,14 @@ /// extension Player: Refinable { } /// /// let player = Player(name: "Arthur", score: 1000) -/// player.with { $0.score = 100 } // Player(name: "Arthur", score: 100) -/// player.with(\.score, 100) // Player(name: "Arthur", score: 100) -/// player.map(\.score) { $0 + 100 } // Player(name: "Arthur", score: 1100) +/// +/// // Player(name: "Arthur", score: 100) +/// let newPlayer = player.with { +/// $0.score = 100 +/// } protocol Refinable { } extension Refinable { - /// Returns self modified with the *update* function. /// /// For example: @@ -33,49 +34,4 @@ extension Refinable { try update(&result) return result } - - /// Returns self with the given value set on the given key path. - /// - /// For example: - /// - /// let player = Player(name: "Arthur", score: 1000) - /// let newPlayer = player.with(\.score, 1100) - /// newPlayer.name // "Arthur" - /// newPlayer.score // 1100 - @inline(__always) - func with(_ keyPath: WritableKeyPath, _ value: T) -> Self { - with { $0[keyPath: keyPath] = value } - } - - /// Returns self with the given transform function applied to the given key path. - /// - /// For example: - /// - /// let player = Player(name: "Arthur", score: 1000) - /// let newPlayer = player.map(\.score) { $0 + 100 } - /// newPlayer.name // "Arthur" - /// newPlayer.score // 1100 - @inline(__always) - func map(_ keyPath: WritableKeyPath, _ transform: (T) throws -> T) rethrows -> Self { - try with { - $0[keyPath: keyPath] = try transform($0[keyPath: keyPath]) - } - } - - /// Returns self with the given update function applied to the given key path. - /// - /// For example: - /// - /// let player = Player(name: "Arthur", scores: [100, 10]) - /// let newPlayer = player.mapInto(\.scores) { $0.append(1000) } - /// newPlayer.name // "Arthur" - /// newPlayer.scores // [100, 10, 1000] - @inline(__always) - func mapInto(_ keyPath: WritableKeyPath, _ update: (inout T) throws -> Void) rethrows -> Self { - try with { - try update(&$0[keyPath: keyPath]) - } - } } - -extension Array: Refinable where Element: Refinable { } diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index a7950f933..0be571ac3 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -103,8 +103,8 @@ extension ValueObservation: Refinable { onError: @escaping (Error) -> Void, onChange: @escaping (Reducer.Value) -> Void) -> DatabaseCancellable { - let observation = map(\.events) { events in - events.map(\.didFail) { concat($0, onError) } + let observation = self.with { + $0.events.didFail = concat($0.events.didFail, onError) } observation.events.willStart?() return reader._add( @@ -157,14 +157,13 @@ extension ValueObservation: Refinable { // the type of the value may change with the `map` operator. didReceiveValue: didReceiveValue ?? { _ in }) }) - .map(\.events, { events in - events - .map(\.willStart) { concat($0, willStart) } - .map(\.willTrackRegion) { concat($0, willTrackRegion) } - .map(\.databaseDidChange) { concat($0, databaseDidChange) } - .map(\.didFail) { concat($0, didFail) } - .map(\.didCancel) { concat($0, didCancel) } - }) + .with { + $0.events.willStart = concat($0.events.willStart, willStart) + $0.events.willTrackRegion = concat($0.events.willTrackRegion, willTrackRegion) + $0.events.databaseDidChange = concat($0.events.databaseDidChange, databaseDidChange) + $0.events.didFail = concat($0.events.didFail, didFail) + $0.events.didCancel = concat($0.events.didCancel, didCancel) + } } /// Prints log messages for all ValueObservation events.