diff --git a/GRDB/QueryInterface/Request/Association/Association.swift b/GRDB/QueryInterface/Request/Association/Association.swift index 26dbd9418..22abce855 100644 --- a/GRDB/QueryInterface/Request/Association/Association.swift +++ b/GRDB/QueryInterface/Request/Association/Association.swift @@ -321,164 +321,3 @@ extension AssociationToMany { return .init(sqlAssociation: sqlAssociation.forDestinationKey(associationKey)) } } - -extension AssociationToMany { - private func makeAggregate(_ expression: SQLExpression) -> AssociationAggregate { - AssociationAggregate { request in - let tableAlias = TableAlias() - let request = request - .joining(optional: self.aliased(tableAlias)) - .groupByPrimaryKey() - let expression = tableAlias[expression] - return (request: request, expression: expression) - } - } - - /// The number of associated records. - /// - /// It has a default name, which is "[key]Count", where key is the key of - /// the association. For example: - /// - /// For example: - /// - /// struct TeamInfo: FetchableRecord, Decodable { - /// var team: Team - /// var playerCount: Int - /// } - /// let request = Team.annotated(with: Team.players.count()) - /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) - /// - /// let teams: [Team] = try Team.having(Team.players.count() > 10).fetchAll(db) - public var count: AssociationAggregate { - makeAggregate(SQLExpressionCountDistinct(Column.rowID)) - .forKey("\(key.singularizedName)Count") - } - - /// Creates an aggregate that is true if there exists no associated records. - /// - /// It has a default name, which is "hasNo[Key]", where key is the key of - /// the association. For example: - /// - /// struct TeamInfo: FetchableRecord, Decodable { - /// var team: Team - /// var hasNoPlayer: Bool - /// } - /// let request = Team.annotated(with: Team.players.isEmpty()) - /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) - /// - /// let teams: [Team] = try Team.having(Team.players.isEmpty()).fetchAll(db) - /// let teams: [Team] = try Team.having(!Team.players.isEmpty()) - /// let teams: [Team] = try Team.having(Team.players.isEmpty() == false) - public var isEmpty: AssociationAggregate { - makeAggregate(SQLExpressionIsEmpty(SQLExpressionCountDistinct(Column.rowID))) - .forKey("hasNo\(key.singularizedName.uppercasingFirstCharacter)") - } - - /// Creates an aggregate which evaluate to the average value of the given - /// expression in associated records. - /// - /// When the averaged expression is a column, the aggregate has a default - /// name which is "average[Key][Column]", where key is the key of the - /// association. For example: - /// - /// For example: - /// - /// struct TeamInfo: FetchableRecord, Decodable { - /// var team: Team - /// var averagePlayerScore: Double - /// } - /// let request = Team.annotated(with: Team.players.average(Column("score"))) - /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) - /// - /// let teams: [Team] = try Team.having(Team.players.average(Column("score")) > 100).fetchAll(db) - public func average(_ expression: SQLExpressible) -> AssociationAggregate { - let aggregate = makeAggregate(SQLExpressionFunction(.avg, arguments: expression)) - if let column = expression as? ColumnExpression { - let name = key.singularizedName - return aggregate.forKey("average\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") - } else { - return aggregate - } - } - - /// Creates an aggregate which evaluate to the maximum value of the given - /// expression in associated records. - /// - /// When the maximized expression is a column, the aggregate has a default - /// name which is "maximum[Key][Column]", where key is the key of the - /// association. For example: - /// - /// For example: - /// - /// struct TeamInfo: FetchableRecord, Decodable { - /// var team: Team - /// var maxPlayerScore: Double - /// } - /// let request = Team.annotated(with: Team.players.max(Column("score"))) - /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) - /// - /// let teams: [Team] = try Team.having(Team.players.max(Column("score")) < 100).fetchAll(db) - public func max(_ expression: SQLExpressible) -> AssociationAggregate { - let aggregate = makeAggregate(SQLExpressionFunction(.max, arguments: expression)) - if let column = expression as? ColumnExpression { - let name = key.singularizedName - return aggregate.forKey("max\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") - } else { - return aggregate - } - } - - /// Creates an aggregate which evaluate to the minimum value of the given - /// expression in associated records. - /// - /// When the minimized expression is a column, the aggregate has a default - /// name which is "minimum[Key][Column]", where key is the key of the - /// association. For example: - /// - /// For example: - /// - /// struct TeamInfo: FetchableRecord, Decodable { - /// var team: Team - /// var minPlayerScore: Double - /// } - /// let request = Team.annotated(with: Team.players.min(Column("score"))) - /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) - /// - /// let teams: [Team] = try Team.having(Team.players.min(Column("score")) > 100).fetchAll(db) - public func min(_ expression: SQLExpressible) -> AssociationAggregate { - let aggregate = makeAggregate(SQLExpressionFunction(.min, arguments: expression)) - if let column = expression as? ColumnExpression { - let name = key.singularizedName - return aggregate.forKey("min\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") - } else { - return aggregate - } - } - - /// Creates an aggregate which evaluate to the sum of the given expression - /// in associated records. - /// - /// When the summed expression is a column, the aggregate has a default - /// name which is "[key][Column]Sum", where key is the key of the - /// association. For example: - /// - /// For example: - /// - /// struct TeamInfo: FetchableRecord, Decodable { - /// var team: Team - /// var playerScoreSum: Double - /// } - /// let request = Team.annotated(with: Team.players.sum(Column("score"))) - /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) - /// - /// let teams: [Team] = try Team.having(Team.players.sum(Column("score")) > 100).fetchAll(db) - public func sum(_ expression: SQLExpressible) -> AssociationAggregate { - let aggregate = makeAggregate(SQLExpressionFunction(.sum, arguments: expression)) - if let column = expression as? ColumnExpression { - let name = key.singularizedName - return aggregate.forKey("\(name)\(column.name.uppercasingFirstCharacter)Sum") - } else { - return aggregate - } - } -} diff --git a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift index aafa8de13..a2e7cbe26 100644 --- a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift +++ b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift @@ -4,6 +4,169 @@ typealias AssociationAggregatePreparation = (QueryInterfaceRequest) -> (request: QueryInterfaceRequest, expression: SQLExpression) +extension AssociationToMany { + private func makeAggregate(_ expression: SQLExpression) -> AssociationAggregate { + AssociationAggregate { request in + let tableAlias = TableAlias() + let request = request + .joining(optional: self.aliased(tableAlias)) + .groupByPrimaryKey() + let expression = tableAlias[expression] + return (request: request, expression: expression) + } + } + + /// The number of associated records. + /// + /// It has a default name, which is "[key]Count", where key is the key of + /// the association. For example: + /// + /// For example: + /// + /// struct TeamInfo: FetchableRecord, Decodable { + /// var team: Team + /// var playerCount: Int + /// } + /// let request = Team.annotated(with: Team.players.count()) + /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) + /// + /// let teams: [Team] = try Team.having(Team.players.count() > 10).fetchAll(db) + public var count: AssociationAggregate { + // TODO: try to replace rowid with actual primary key + makeAggregate(SQLExpressionCountDistinct(Column.rowID)) + .forKey("\(key.singularizedName)Count") + } + + /// Creates an aggregate that is true if there exists no associated records. + /// + /// It has a default name, which is "hasNo[Key]", where key is the key of + /// the association. For example: + /// + /// struct TeamInfo: FetchableRecord, Decodable { + /// var team: Team + /// var hasNoPlayer: Bool + /// } + /// let request = Team.annotated(with: Team.players.isEmpty()) + /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) + /// + /// let teams: [Team] = try Team.having(Team.players.isEmpty()).fetchAll(db) + /// let teams: [Team] = try Team.having(!Team.players.isEmpty()) + /// let teams: [Team] = try Team.having(Team.players.isEmpty() == false) + public var isEmpty: AssociationAggregate { + // TODO: try to replace rowid with actual primary key + makeAggregate(SQLExpressionIsEmpty(SQLExpressionCountDistinct(Column.rowID))) + .forKey("hasNo\(key.singularizedName.uppercasingFirstCharacter)") + } + + /// Creates an aggregate which evaluate to the average value of the given + /// expression in associated records. + /// + /// When the averaged expression is a column, the aggregate has a default + /// name which is "average[Key][Column]", where key is the key of the + /// association. For example: + /// + /// For example: + /// + /// struct TeamInfo: FetchableRecord, Decodable { + /// var team: Team + /// var averagePlayerScore: Double + /// } + /// let request = Team.annotated(with: Team.players.average(Column("score"))) + /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) + /// + /// let teams: [Team] = try Team.having(Team.players.average(Column("score")) > 100).fetchAll(db) + public func average(_ expression: SQLExpressible) -> AssociationAggregate { + let aggregate = makeAggregate(SQLExpressionFunction(.avg, arguments: expression)) + if let column = expression as? ColumnExpression { + let name = key.singularizedName + return aggregate.forKey("average\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") + } else { + return aggregate + } + } + + /// Creates an aggregate which evaluate to the maximum value of the given + /// expression in associated records. + /// + /// When the maximized expression is a column, the aggregate has a default + /// name which is "maximum[Key][Column]", where key is the key of the + /// association. For example: + /// + /// For example: + /// + /// struct TeamInfo: FetchableRecord, Decodable { + /// var team: Team + /// var maxPlayerScore: Double + /// } + /// let request = Team.annotated(with: Team.players.max(Column("score"))) + /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) + /// + /// let teams: [Team] = try Team.having(Team.players.max(Column("score")) < 100).fetchAll(db) + public func max(_ expression: SQLExpressible) -> AssociationAggregate { + let aggregate = makeAggregate(SQLExpressionFunction(.max, arguments: expression)) + if let column = expression as? ColumnExpression { + let name = key.singularizedName + return aggregate.forKey("max\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") + } else { + return aggregate + } + } + + /// Creates an aggregate which evaluate to the minimum value of the given + /// expression in associated records. + /// + /// When the minimized expression is a column, the aggregate has a default + /// name which is "minimum[Key][Column]", where key is the key of the + /// association. For example: + /// + /// For example: + /// + /// struct TeamInfo: FetchableRecord, Decodable { + /// var team: Team + /// var minPlayerScore: Double + /// } + /// let request = Team.annotated(with: Team.players.min(Column("score"))) + /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) + /// + /// let teams: [Team] = try Team.having(Team.players.min(Column("score")) > 100).fetchAll(db) + public func min(_ expression: SQLExpressible) -> AssociationAggregate { + let aggregate = makeAggregate(SQLExpressionFunction(.min, arguments: expression)) + if let column = expression as? ColumnExpression { + let name = key.singularizedName + return aggregate.forKey("min\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") + } else { + return aggregate + } + } + + /// Creates an aggregate which evaluate to the sum of the given expression + /// in associated records. + /// + /// When the summed expression is a column, the aggregate has a default + /// name which is "[key][Column]Sum", where key is the key of the + /// association. For example: + /// + /// For example: + /// + /// struct TeamInfo: FetchableRecord, Decodable { + /// var team: Team + /// var playerScoreSum: Double + /// } + /// let request = Team.annotated(with: Team.players.sum(Column("score"))) + /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) + /// + /// let teams: [Team] = try Team.having(Team.players.sum(Column("score")) > 100).fetchAll(db) + public func sum(_ expression: SQLExpressible) -> AssociationAggregate { + let aggregate = makeAggregate(SQLExpressionFunction(.sum, arguments: expression)) + if let column = expression as? ColumnExpression { + let name = key.singularizedName + return aggregate.forKey("\(name)\(column.name.uppercasingFirstCharacter)Sum") + } else { + return aggregate + } + } +} + /// An AssociationAggregate is able to compute aggregated values from a /// population of associated records. /// @@ -27,6 +190,7 @@ typealias AssociationAggregatePreparation = /// // Won't compile because Fruit is not Author. /// let request = Fruit.annotated(with: bookCount) public struct AssociationAggregate { + // TODO: replace rowid with actual primary key in the doc when implemented /// Given a request, returns a tuple made of a request extended with the /// associated records used to compute the aggregate, and an expression /// whose value is the aggregated value. diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest+Association.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest+Association.swift index dd33bd864..4c7743a40 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest+Association.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest+Association.swift @@ -11,6 +11,7 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord { } } + // TODO: replace rowid with actual primary key in the doc when implemented /// Creates a request which appends *aggregates* to the current selection. /// /// // SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount @@ -21,6 +22,7 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord { annotated(with: aggregates) } + // TODO: replace rowid with actual primary key in the doc when implemented /// Creates a request which appends *aggregates* to the current selection. /// /// // SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount @@ -33,6 +35,7 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord { } } + // TODO: replace rowid with actual primary key in the doc when implemented /// Creates a request which appends the provided aggregate *predicate* to /// the eventual set of already applied predicates. /// diff --git a/GRDB/QueryInterface/SQL/SQLAssociation.swift b/GRDB/QueryInterface/SQL/SQLAssociation.swift index 8a84642db..39c044270 100644 --- a/GRDB/QueryInterface/SQL/SQLAssociation.swift +++ b/GRDB/QueryInterface/SQL/SQLAssociation.swift @@ -136,15 +136,11 @@ public /* TODO: internal */ struct SQLAssociation { /// as HasManyThrough, which have any number of pivot relations between the /// origin and the destination. func destinationRelation(fromOriginRows originRows: @escaping (Database) throws -> [Row]) -> SQLRelation { - // Filter the pivot + // Filter the pivot: `pivot.originId = 123` or `pivot.originId IN (1, 2, 3)` let pivot = self.pivot - let pivotAlias = TableAlias() - let filteredPivotRelation = pivot.relation - .qualified(with: pivotAlias) - .filter({ db in - // `pivot.originId = 123` or `pivot.originId IN (1, 2, 3)` - try pivot.condition.filteringExpression(db, leftRows: originRows(db), rightAlias: pivotAlias) - }) + let filteredPivotRelation = pivot.relation.filter { db in + try pivot.condition.filteringExpression(db, leftRows: originRows(db)) + } if steps.count == 1 { // This is a direct join from origin to destination, without @@ -178,7 +174,12 @@ public /* TODO: internal */ struct SQLAssociation { // children are useless: let relation = step.relation .selectOnly([]) - .filteringChildren { $0.kind.cardinality == .toOne } + .filteringChildren({ + switch $0.kind { + case .allPrefetched, .allNotPrefetched: return false + case .oneRequired, .oneOptional: return true + } + }) // Don't interfere with user-defined keys that could be added later let key = step.key.map(\.baseName) { "grdb_\($0)" } @@ -203,7 +204,16 @@ struct SQLAssociationStep: Refinable { var relation: SQLRelation var cardinality: SQLAssociationCardinality - var keyName: String { key.name(for: cardinality) } + var isSingular: Bool { + switch cardinality { + case .toOne: + return true + case .toMany: + return false + } + } + + var keyName: String { key.name(singular: isSingular) } } enum SQLAssociationCardinality { @@ -319,11 +329,10 @@ enum SQLAssociationKey: Refinable { } } - func name(for cardinality: SQLAssociationCardinality) -> String { - switch cardinality { - case .toOne: + func name(singular: Bool) -> String { + if singular { return singularizedName - case .toMany: + } else { return pluralizedName } } diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index 19cabbc40..7361d6eb9 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -141,3 +141,22 @@ struct SQLExpressionNot: SQLExpression { SQLExpressionNot(expression.qualifiedExpression(with: alias)) } } + +// MARK: - + +extension Database { + /// Returns an expression for the primary key of this table. + /// + /// When the table as a primary key made of several columns, we return + /// the rowid column. Eventually we'll support + /// [row values](https://www.sqlite.org/rowvalue.html) and be able to deal + /// with WITHOUT ROWID tables. + func primaryKeyExpression(_ tableName: String) throws -> SQLExpression { + let columns = try primaryKey(tableName).columns + if columns.count == 1 { + return Column(columns[0]) + } else { + return Column.rowID + } + } +} diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index 7a70bf8b6..3d0d154f1 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -111,12 +111,12 @@ struct SQLRelation { // Record.including(all: associationThroughPivot) case allNotPrefetched - var cardinality: SQLAssociationCardinality { + var isSingular: Bool { switch self { case .oneOptional, .oneRequired: - return .toOne + return true case .allPrefetched, .allNotPrefetched: - return .toMany + return false } } } @@ -140,11 +140,20 @@ struct SQLRelation { fileprivate func makeAssociationForKey(_ key: String) -> SQLAssociation { let key = SQLAssociationKey.fixed(key) + + let cardinality: SQLAssociationCardinality + switch kind { + case .oneOptional, .oneRequired: + cardinality = .toOne + case .allPrefetched, .allNotPrefetched: + cardinality = .toMany + } + return SQLAssociation( key: key, condition: condition, relation: relation, - cardinality: kind.cardinality) + cardinality: cardinality) } } @@ -175,6 +184,18 @@ struct SQLRelation { } } } + + /// Returns nil if there is no way to express the primary key of the + /// relation as an expression. + func primaryKeyExpression(_ db: Database) throws -> SQLExpression? { + switch source { + case .query: + // No primary key for sub query + return nil + case let .table(tableName: tableName, alias: _): + return try db.primaryKeyExpression(tableName) + } + } } extension SQLRelation: Refinable { @@ -254,10 +275,10 @@ extension SQLRelation { func appendingChild(for association: SQLAssociation, kind: SQLRelation.Child.Kind) -> Self { // Preserve association cardinality in intermediate steps of // including(all:), and force desired cardinality otherwize - let childCardinality = (kind == .allNotPrefetched) - ? association.destination.cardinality - : kind.cardinality - let childKey = association.destination.key.name(for: childCardinality) + let isSingular = (kind == .allNotPrefetched) + ? association.destination.isSingular + : kind.isSingular + let childKey = association.destination.key.name(singular: isSingular) let child = SQLRelation.Child( kind: kind, condition: association.destination.condition, @@ -549,13 +570,11 @@ struct SQLAssociationCondition: Equatable { /// - parameter db: A database connection. /// - parameter leftAlias: A TableAlias for the table on the left of the /// JOIN operator. - /// - parameter rightAlias: A TableAlias for the table on the right of the - /// JOIN operator. /// - Returns: An array of SQL expression that should be joined with - /// the AND operator. - func expressions(_ db: Database, leftAlias: TableAlias, rightAlias: TableAlias) throws -> [SQLExpression] { + /// the AND operator and qualified with the right table. + func expressions(_ db: Database, leftAlias: TableAlias) throws -> [SQLExpression] { try columnMappings(db).map { - QualifiedColumn($0.right, alias: rightAlias) == QualifiedColumn($0.left, alias: leftAlias) + Column($0.right) == QualifiedColumn($0.left, alias: leftAlias) } } @@ -564,7 +583,7 @@ struct SQLAssociationCondition: Equatable { /// /// Given `right.a = left.b`, returns `right.a = 1` or /// `right.a IN (1, 2, 3)`. - func filteringExpression(_ db: Database, leftRows: [Row], rightAlias: TableAlias) throws -> SQLExpression { + func filteringExpression(_ db: Database, leftRows: [Row]) throws -> SQLExpression { if leftRows.isEmpty { // Degenerate case: there is no row to attach return false.sqlExpression @@ -578,7 +597,7 @@ struct SQLAssociationCondition: Equatable { if columnMappings.count == 1 { // Join on a single right column. - let rightColumn = QualifiedColumn(columnMapping.right, alias: rightAlias) + let rightColumn = Column(columnMapping.right) // Unique database values and filter out NULL: var dbValues = Set(leftRows.map { $0[columnMapping.left] as DatabaseValue }) @@ -600,7 +619,7 @@ struct SQLAssociationCondition: Equatable { // (table.a = 1) AND (table.b = 2) columnMappings .map({ columns -> SQLExpression in - let rightColumn = QualifiedColumn(columns.right, alias: rightAlias) + let rightColumn = Column(columns.right) let leftValue = leftRow[columns.left] as DatabaseValue return rightColumn == leftValue }) diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 06e6a09d4..c6a34bbd2 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -1,5 +1,5 @@ /// SQLQueryGenerator is able to generate an SQL SELECT query. -struct SQLQueryGenerator { +struct SQLQueryGenerator: Refinable { fileprivate private(set) var relation: SQLQualifiedRelation private let isDistinct: Bool private let groupPromise: DatabasePromise<[SQLExpression]>? @@ -168,7 +168,7 @@ struct SQLQueryGenerator { } } - /// DELETE FROM table WHERE rowid IN (SELECT rowid FROM table ...) + /// DELETE FROM table WHERE id IN (SELECT id FROM table ...) private func makeTrivialDeleteStatement(_ db: Database) throws -> UpdateStatement { guard case let .table(tableName: tableName, alias: _) = relation.source else { // Programmer error @@ -176,14 +176,13 @@ struct SQLQueryGenerator { } var context = SQLGenerationContext.queryContext(aliases: relation.allAliases) + let primaryKey = try db.primaryKeyExpression(tableName) - // SELECT rowid FROM table ... - var generator = self - generator.relation = generator.relation.selectOnly([Column.rowID]) - let selectSQL = try generator.sql(db, &context) - - // DELETE FROM table WHERE rowid IN (SELECT rowid FROM table ...) - let sql = "DELETE FROM \(tableName.quotedDatabaseIdentifier) WHERE rowid IN (\(selectSQL))" + var sql = "DELETE FROM \(tableName.quotedDatabaseIdentifier) WHERE " + sql += primaryKey.expressionSQL(&context, wrappedInParenthesis: false) + sql += " IN (" + sql += try map(\.relation, { $0.selectOnly([primaryKey]) }).sql(db, &context) + sql += ")" let statement = try db.makeUpdateStatement(sql: sql) statement.arguments = context.arguments @@ -258,7 +257,7 @@ struct SQLQueryGenerator { } } - /// UPDATE table SET ... WHERE rowid IN (SELECT rowid FROM table ...) + /// UPDATE table SET ... WHERE id IN (SELECT id FROM table ...) /// Returns nil if assignments is empty private func makeTrivialUpdateStatement( _ db: Database, @@ -278,6 +277,7 @@ struct SQLQueryGenerator { } var context = SQLGenerationContext.queryContext(aliases: relation.allAliases) + let primaryKey = try db.primaryKeyExpression(tableName) // UPDATE table... var sql = "UPDATE " @@ -292,10 +292,12 @@ struct SQLQueryGenerator { .joined(separator: ", ") sql += " SET " + assignmentsSQL - // WHERE rowid IN (SELECT rowid FROM ...) - var generator = self - generator.relation = generator.relation.selectOnly([Column.rowID]) - sql += try " WHERE rowid IN (\(generator.sql(db, &context)))" + // WHERE id IN (SELECT rowid FROM ...) + sql += " WHERE " + sql += primaryKey.expressionSQL(&context, wrappedInParenthesis: false) + sql += " IN (" + sql += try map(\.relation, { $0.selectOnly([primaryKey]) }).sql(db, &context) + sql += ")" let statement = try db.makeUpdateStatement(sql: sql) statement.arguments = context.arguments @@ -481,23 +483,7 @@ private struct SQLQualifiedRelation { // Qualify all joins, selection, filter, and ordering, so that all // identifiers can be correctly disambiguated and qualified. - joins = relation.children.compactMapValues { child -> SQLQualifiedJoin? in - let kind: SQLQualifiedJoin.Kind - switch child.kind { - case .oneRequired: - kind = .innerJoin - case .oneOptional: - kind = .leftJoin - case .allPrefetched, .allNotPrefetched: - // This relation child is not fetched with an SQL join. - return nil - } - - return SQLQualifiedJoin( - kind: kind, - condition: child.condition, - relation: SQLQualifiedRelation(child.relation)) - } + joins = relation.children.compactMapValues { SQLQualifiedJoin($0) } sourceSelection = relation.selection.map { $0.qualifiedSelectable(with: sourceAlias) } filtersPromise = relation.filtersPromise.map { $0.map { $0.qualifiedExpression(with: sourceAlias) } } sourceOrdering = relation.ordering.qualified(with: sourceAlias) @@ -620,15 +606,36 @@ private enum SQLQualifiedSource { } /// A "qualified" join, where all tables are identified with a table alias. -private struct SQLQualifiedJoin { +private struct SQLQualifiedJoin: Refinable { enum Kind: String { case leftJoin = "LEFT JOIN" case innerJoin = "JOIN" + + init?(_ kind: SQLRelation.Child.Kind) { + switch kind { + case .oneRequired: + self = .innerJoin + case .oneOptional: + self = .leftJoin + case .allPrefetched, .allNotPrefetched: + // Eager loading of to-many associations is not implemented with joins + return nil + } + } } - let kind: Kind - let condition: SQLAssociationCondition - let relation: SQLQualifiedRelation + var kind: Kind + var condition: SQLAssociationCondition + var relation: SQLQualifiedRelation + + init?(_ child: SQLRelation.Child) { + guard let kind = Kind(child.kind) else { + return nil + } + self.kind = kind + self.condition = child.condition + self.relation = SQLQualifiedRelation(child.relation) + } func sql(_ db: Database, _ context: inout SQLGenerationContext, leftAlias: TableAlias) throws -> String { try sql(db, &context, leftAlias: leftAlias, allowingInnerJoin: true) @@ -636,10 +643,7 @@ private struct SQLQualifiedJoin { /// Removes all selections from joins func selectOnly(_ selection: [SQLSelectable]) -> SQLQualifiedJoin { - SQLQualifiedJoin( - kind: kind, - condition: condition, - relation: relation.selectOnly(selection)) + map(\.relation) { $0.selectOnly(selection) } } private func sql( @@ -650,7 +654,6 @@ private struct SQLQualifiedJoin { throws -> String { var allowsInnerJoin = allowsInnerJoin - var sql = "" switch self.kind { case .innerJoin: @@ -665,16 +668,24 @@ private struct SQLQualifiedJoin { case .leftJoin: allowsInnerJoin = false } - sql += try "\(kind.rawValue) \(relation.source.sql(db, &context))" + // JOIN table... + var sql = try "\(kind.rawValue) \(relation.source.sql(db, &context))" let rightAlias = relation.sourceAlias - let filters = try condition.expressions(db, leftAlias: leftAlias, rightAlias: rightAlias) - + relation.filtersPromise.resolve(db) + + // ... ON AND + var filters = try condition.expressions(db, leftAlias: leftAlias) + filters += try relation.filtersPromise.resolve(db) if filters.isEmpty == false { - sql += " ON \(filters.joined(operator: .and).expressionSQL(&context, wrappedInParenthesis: false))" + let filterSQL = filters + .joined(operator: .and) + .qualifiedExpression(with: rightAlias) + .expressionSQL(&context, wrappedInParenthesis: false) + sql += " ON \(filterSQL)" } for (_, join) in relation.joins { + // Right becomes left as we dig further sql += try " \(join.sql(db, &context, leftAlias: rightAlias, allowingInnerJoin: allowsInnerJoin))" } diff --git a/GRDB/QueryInterface/TableRecord+Association.swift b/GRDB/QueryInterface/TableRecord+Association.swift index 2b83533b5..7afa6e10c 100644 --- a/GRDB/QueryInterface/TableRecord+Association.swift +++ b/GRDB/QueryInterface/TableRecord+Association.swift @@ -547,6 +547,7 @@ extension TableRecord { // MARK: - Association Aggregates + // TODO: replace rowid with actual primary key in the doc when implemented /// Creates a request with *aggregates* appended to the selection. /// /// // SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount @@ -556,6 +557,7 @@ extension TableRecord { all().annotated(with: aggregates) } + // TODO: replace rowid with actual primary key in the doc when implemented /// Creates a request with *aggregates* appended to the selection. /// /// // SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount @@ -565,6 +567,7 @@ extension TableRecord { all().annotated(with: aggregates) } + // TODO: replace rowid with actual primary key in the doc when implemented /// Creates a request with the provided aggregate *predicate*. /// /// // SELECT player.* diff --git a/Tests/GRDBTests/AssociationHasManySQLTests.swift b/Tests/GRDBTests/AssociationHasManySQLTests.swift index 61c418e30..71ab378b0 100644 --- a/Tests/GRDBTests/AssociationHasManySQLTests.swift +++ b/Tests/GRDBTests/AssociationHasManySQLTests.swift @@ -780,6 +780,7 @@ class AssociationHasManySQLTests: GRDBTestCase { t.autoIncrementedPrimaryKey("id") } try db.create(table: "child") { t in + t.autoIncrementedPrimaryKey("id") t.column("parentId", .integer).references("parent") } try db.create(table: "toy") { t in @@ -793,17 +794,17 @@ class AssociationHasManySQLTests: GRDBTestCase { try assertEqualSQL(db, Parent.all().including(required: association), """ SELECT "parent".*, "child".* \ FROM "parent" JOIN "child" ON "child"."parentId" = "parent"."id" \ - JOIN "toy" ON "toy"."childId" = "child"."rowid" + JOIN "toy" ON "toy"."childId" = "child"."id" """) try assertEqualSQL(db, Parent.all().joining(required: association), """ SELECT "parent".* FROM "parent" \ JOIN "child" ON "child"."parentId" = "parent"."id" \ - JOIN "toy" ON "toy"."childId" = "child"."rowid" + JOIN "toy" ON "toy"."childId" = "child"."id" """) try assertEqualSQL(db, Parent().request(for: association), """ SELECT "child".* \ FROM "child" \ - JOIN "toy" ON "toy"."childId" = "child"."rowid" \ + JOIN "toy" ON "toy"."childId" = "child"."id" \ WHERE "child"."parentId" = 1 """) } diff --git a/Tests/GRDBTests/AssociationHasManyThroughSQLTests.swift b/Tests/GRDBTests/AssociationHasManyThroughSQLTests.swift index 3d6d7c5c9..499319438 100644 --- a/Tests/GRDBTests/AssociationHasManyThroughSQLTests.swift +++ b/Tests/GRDBTests/AssociationHasManyThroughSQLTests.swift @@ -332,6 +332,7 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase { t.autoIncrementedPrimaryKey("id") } try db.create(table: "child") { t in + t.autoIncrementedPrimaryKey("id") t.column("parentId", .integer).references("parent") } try db.create(table: "toy") { t in @@ -352,21 +353,21 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase { SELECT "parent".*, "pet".* \ FROM "parent" \ JOIN "child" ON "child"."parentId" = "parent"."id" \ - JOIN "toy" ON "toy"."childId" = "child"."rowid" \ - JOIN "pet" ON "pet"."childId" = "child"."rowid" + JOIN "toy" ON "toy"."childId" = "child"."id" \ + JOIN "pet" ON "pet"."childId" = "child"."id" """) try assertEqualSQL(db, Parent.all().joining(required: association), """ SELECT "parent".* \ FROM "parent" \ JOIN "child" ON "child"."parentId" = "parent"."id" \ - JOIN "toy" ON "toy"."childId" = "child"."rowid" \ - JOIN "pet" ON "pet"."childId" = "child"."rowid" + JOIN "toy" ON "toy"."childId" = "child"."id" \ + JOIN "pet" ON "pet"."childId" = "child"."id" """) try assertEqualSQL(db, Parent().request(for: association), """ SELECT "pet".* \ FROM "pet" \ - JOIN "child" ON ("child"."rowid" = "pet"."childId") AND ("child"."parentId" = 1) \ - JOIN "toy" ON "toy"."childId" = "child"."rowid" + JOIN "child" ON ("child"."id" = "pet"."childId") AND ("child"."parentId" = 1) \ + JOIN "toy" ON "toy"."childId" = "child"."id" """) } do { @@ -378,24 +379,24 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase { SELECT "parent".*, "pet".* \ FROM "parent" \ JOIN "child" "child1" ON ("child1"."parentId" = "parent"."id") AND (1 + 1) \ - JOIN "pet" ON "pet"."childId" = "child1"."rowid" \ - JOIN "child" "child2" ON ("child2"."rowid" = "pet"."childId") AND (1) \ - JOIN "toy" ON "toy"."childId" = "child2"."rowid" + JOIN "pet" ON "pet"."childId" = "child1"."id" \ + JOIN "child" "child2" ON ("child2"."id" = "pet"."childId") AND (1) \ + JOIN "toy" ON "toy"."childId" = "child2"."id" """) try assertEqualSQL(db, Parent.all().joining(required: association), """ SELECT "parent".* \ FROM "parent" \ JOIN "child" "child1" ON ("child1"."parentId" = "parent"."id") AND (1 + 1) \ - JOIN "pet" ON "pet"."childId" = "child1"."rowid" \ - JOIN "child" "child2" ON ("child2"."rowid" = "pet"."childId") AND (1) \ - JOIN "toy" ON "toy"."childId" = "child2"."rowid" + JOIN "pet" ON "pet"."childId" = "child1"."id" \ + JOIN "child" "child2" ON ("child2"."id" = "pet"."childId") AND (1) \ + JOIN "toy" ON "toy"."childId" = "child2"."id" """) try assertEqualSQL(db, Parent().request(for: association), """ SELECT "pet".* \ FROM "pet" \ - JOIN "child" "child1" ON ("child1"."rowid" = "pet"."childId") AND (1) \ - JOIN "toy" ON "toy"."childId" = "child1"."rowid" \ - JOIN "child" "child2" ON ("child2"."rowid" = "pet"."childId") AND (1 + 1) AND ("child2"."parentId" = 1) + JOIN "child" "child1" ON ("child1"."id" = "pet"."childId") AND (1) \ + JOIN "toy" ON "toy"."childId" = "child1"."id" \ + JOIN "child" "child2" ON ("child2"."id" = "pet"."childId") AND (1 + 1) AND ("child2"."parentId" = 1) """) } do { @@ -408,24 +409,24 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase { SELECT "parent".*, "pet".* \ FROM "parent" \ JOIN "child" "child1" ON ("child1"."parentId" = "parent"."id") AND (1 + 1) \ - JOIN "pet" ON "pet"."childId" = "child1"."rowid" \ - JOIN "child" "child2" ON ("child2"."rowid" = "pet"."childId") AND (1) \ - JOIN "toy" ON "toy"."childId" = "child2"."rowid" + JOIN "pet" ON "pet"."childId" = "child1"."id" \ + JOIN "child" "child2" ON ("child2"."id" = "pet"."childId") AND (1) \ + JOIN "toy" ON "toy"."childId" = "child2"."id" """) try assertEqualSQL(db, Parent.all().joining(required: association), """ SELECT "parent".* \ FROM "parent" \ JOIN "child" "child1" ON ("child1"."parentId" = "parent"."id") AND (1 + 1) \ - JOIN "pet" ON "pet"."childId" = "child1"."rowid" \ - JOIN "child" "child2" ON ("child2"."rowid" = "pet"."childId") AND (1) \ - JOIN "toy" ON "toy"."childId" = "child2"."rowid" + JOIN "pet" ON "pet"."childId" = "child1"."id" \ + JOIN "child" "child2" ON ("child2"."id" = "pet"."childId") AND (1) \ + JOIN "toy" ON "toy"."childId" = "child2"."id" """) try assertEqualSQL(db, Parent().request(for: association), """ SELECT "pet".* \ FROM "pet" \ - JOIN "child" "child1" ON ("child1"."rowid" = "pet"."childId") AND (1) \ - JOIN "toy" ON "toy"."childId" = "child1"."rowid" \ - JOIN "child" "child2" ON ("child2"."rowid" = "pet"."childId") AND (1 + 1) AND ("child2"."parentId" = 1) + JOIN "child" "child1" ON ("child1"."id" = "pet"."childId") AND (1) \ + JOIN "toy" ON "toy"."childId" = "child1"."id" \ + JOIN "child" "child2" ON ("child2"."id" = "pet"."childId") AND (1 + 1) AND ("child2"."parentId" = 1) """) } } diff --git a/Tests/GRDBTests/MutablePersistableRecordDeleteTests.swift b/Tests/GRDBTests/MutablePersistableRecordDeleteTests.swift index d2af2f8db..a22d34815 100644 --- a/Tests/GRDBTests/MutablePersistableRecordDeleteTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordDeleteTests.swift @@ -205,8 +205,8 @@ class MutablePersistableRecordDeleteTests: GRDBTestCase { do { try Player.including(required: Player.team).deleteAll(db) XCTAssertEqual(self.lastSQLQuery, """ - DELETE FROM "player" WHERE rowid IN (\ - SELECT "player"."rowid" \ + DELETE FROM "player" WHERE "id" IN (\ + SELECT "player"."id" \ FROM "player" \ JOIN "team" ON "team"."id" = "player"."teamId") """) @@ -215,8 +215,8 @@ class MutablePersistableRecordDeleteTests: GRDBTestCase { let alias = TableAlias(name: "p") try Player.aliased(alias).including(required: Player.team).deleteAll(db) XCTAssertEqual(self.lastSQLQuery, """ - DELETE FROM "player" WHERE rowid IN (\ - SELECT "p"."rowid" \ + DELETE FROM "player" WHERE "id" IN (\ + SELECT "p"."id" \ FROM "player" "p" \ JOIN "team" ON "team"."id" = "p"."teamId") """) @@ -224,8 +224,8 @@ class MutablePersistableRecordDeleteTests: GRDBTestCase { do { try Team.having(Team.players.isEmpty).deleteAll(db) XCTAssertEqual(self.lastSQLQuery, """ - DELETE FROM "team" WHERE rowid IN (\ - SELECT "team"."rowid" \ + DELETE FROM "team" WHERE "id" IN (\ + SELECT "team"."id" \ FROM "team" \ LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ GROUP BY "team"."id" \ @@ -261,8 +261,8 @@ class MutablePersistableRecordDeleteTests: GRDBTestCase { do { try Player.all().groupByPrimaryKey().deleteAll(db) XCTAssertEqual(self.lastSQLQuery, """ - DELETE FROM "player" WHERE rowid IN (\ - SELECT "rowid" \ + DELETE FROM "player" WHERE "id" IN (\ + SELECT "id" \ FROM "player" \ GROUP BY "id") """) @@ -270,8 +270,8 @@ class MutablePersistableRecordDeleteTests: GRDBTestCase { do { try Player.all().group(Column.rowID).deleteAll(db) XCTAssertEqual(self.lastSQLQuery, """ - DELETE FROM "player" WHERE rowid IN (\ - SELECT "rowid" \ + DELETE FROM "player" WHERE "id" IN (\ + SELECT "id" \ FROM "player" \ GROUP BY "rowid") """) @@ -279,7 +279,7 @@ class MutablePersistableRecordDeleteTests: GRDBTestCase { do { try Passport.all().groupByPrimaryKey().deleteAll(db) XCTAssertEqual(self.lastSQLQuery, """ - DELETE FROM "passport" WHERE rowid IN (\ + DELETE FROM "passport" WHERE "rowid" IN (\ SELECT "rowid" \ FROM "passport" \ GROUP BY "countryCode", "citizenId") @@ -288,7 +288,7 @@ class MutablePersistableRecordDeleteTests: GRDBTestCase { do { try Passport.all().group(Column.rowID).deleteAll(db) XCTAssertEqual(self.lastSQLQuery, """ - DELETE FROM "passport" WHERE rowid IN (\ + DELETE FROM "passport" WHERE "rowid" IN (\ SELECT "rowid" \ FROM "passport" \ GROUP BY "rowid") diff --git a/Tests/GRDBTests/MutablePersistableRecordUpdateTests.swift b/Tests/GRDBTests/MutablePersistableRecordUpdateTests.swift index cc43f4fef..dc22d59d0 100644 --- a/Tests/GRDBTests/MutablePersistableRecordUpdateTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordUpdateTests.swift @@ -422,8 +422,8 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase { do { try Player.including(required: Player.team).updateAll(db, Column("score").set(to: 0)) XCTAssertEqual(self.lastSQLQuery, """ - UPDATE "player" SET "score" = 0 WHERE rowid IN (\ - SELECT "player"."rowid" \ + UPDATE "player" SET "score" = 0 WHERE "id" IN (\ + SELECT "player"."id" \ FROM "player" \ JOIN "team" ON "team"."id" = "player"."teamId") """) @@ -432,8 +432,8 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase { // Regression test for https://github.com/groue/GRDB.swift/issues/758 try Player.including(required: Player.team.filter(Column("active") == 1)).updateAll(db, Column("score").set(to: 0)) XCTAssertEqual(self.lastSQLQuery, """ - UPDATE "player" SET "score" = 0 WHERE rowid IN (\ - SELECT "player"."rowid" \ + UPDATE "player" SET "score" = 0 WHERE "id" IN (\ + SELECT "player"."id" \ FROM "player" \ JOIN "team" ON ("team"."id" = "player"."teamId") AND ("team"."active" = 1)) """) @@ -442,8 +442,8 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase { let alias = TableAlias(name: "p") try Player.aliased(alias).including(required: Player.team).updateAll(db, Column("score").set(to: 0)) XCTAssertEqual(self.lastSQLQuery, """ - UPDATE "player" SET "score" = 0 WHERE rowid IN (\ - SELECT "p"."rowid" \ + UPDATE "player" SET "score" = 0 WHERE "id" IN (\ + SELECT "p"."id" \ FROM "player" "p" \ JOIN "team" ON "team"."id" = "p"."teamId") """) @@ -451,8 +451,8 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase { do { try Team.having(Team.players.isEmpty).updateAll(db, Column("active").set(to: false)) XCTAssertEqual(self.lastSQLQuery, """ - UPDATE "team" SET "active" = 0 WHERE rowid IN (\ - SELECT "team"."rowid" \ + UPDATE "team" SET "active" = 0 WHERE "id" IN (\ + SELECT "team"."id" \ FROM "team" \ LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ GROUP BY "team"."id" \ @@ -489,8 +489,8 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase { do { try Player.all().groupByPrimaryKey().updateAll(db, Column("score").set(to: 0)) XCTAssertEqual(self.lastSQLQuery, """ - UPDATE "player" SET "score" = 0 WHERE rowid IN (\ - SELECT "rowid" \ + UPDATE "player" SET "score" = 0 WHERE "id" IN (\ + SELECT "id" \ FROM "player" \ GROUP BY "id") """) @@ -498,8 +498,8 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase { do { try Player.all().group(Column.rowID).updateAll(db, Column("score").set(to: 0)) XCTAssertEqual(self.lastSQLQuery, """ - UPDATE "player" SET "score" = 0 WHERE rowid IN (\ - SELECT "rowid" \ + UPDATE "player" SET "score" = 0 WHERE "id" IN (\ + SELECT "id" \ FROM "player" \ GROUP BY "rowid") """) @@ -507,7 +507,7 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase { do { try Passport.all().groupByPrimaryKey().updateAll(db, Column("active").set(to: true)) XCTAssertEqual(self.lastSQLQuery, """ - UPDATE "passport" SET "active" = 1 WHERE rowid IN (\ + UPDATE "passport" SET "active" = 1 WHERE "rowid" IN (\ SELECT "rowid" \ FROM "passport" \ GROUP BY "countryCode", "citizenId") @@ -516,7 +516,7 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase { do { try Passport.all().group(Column.rowID).updateAll(db, Column("active").set(to: true)) XCTAssertEqual(self.lastSQLQuery, """ - UPDATE "passport" SET "active" = 1 WHERE rowid IN (\ + UPDATE "passport" SET "active" = 1 WHERE "rowid" IN (\ SELECT "rowid" \ FROM "passport" \ GROUP BY "rowid")