From ca76032b8b5531604b5ef4fa249a3ec45b4580a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 19 May 2019 07:33:18 +0200 Subject: [PATCH] Association name is turned into singularized or pluralized keys --- GRDB/Fixit/GRDB-4.0.swift | 29 ++++++ .../Association/Association.swift | 90 ++++++++++++++----- .../Association/BelongsToAssociation.swift | 7 +- .../Association/HasManyAssociation.swift | 7 +- .../Association/HasOneAssociation.swift | 7 +- GRDB/QueryInterface/SQLRelation.swift | 12 ++- GRDB/Utils/Inflections.swift | 2 + .../GRDBTests/AssociationAggregateTests.swift | 2 +- ...ciationBelongsToFetchableRecordTests.swift | 2 +- .../AssociationBelongsToRowScopeTests.swift | 14 +-- .../AssociationParallelRowScopesTests.swift | 10 +-- .../AssociationTableAliasTestsSQLTests.swift | 8 +- 12 files changed, 138 insertions(+), 52 deletions(-) diff --git a/GRDB/Fixit/GRDB-4.0.swift b/GRDB/Fixit/GRDB-4.0.swift index 048ed5de7..d63335ee8 100644 --- a/GRDB/Fixit/GRDB-4.0.swift +++ b/GRDB/Fixit/GRDB-4.0.swift @@ -155,3 +155,32 @@ extension Configuration { set { preconditionFailure() } } } + +extension TableRecord { + @available(*, unavailable, renamed: "belongsTo(_:name:using:)") + public static func belongsTo( + _ destination: Destination.Type, + key: String?, + using foreignKey: ForeignKey? = nil) + -> BelongsToAssociation + where Destination: TableRecord + { preconditionFailure() } + + @available(*, unavailable, renamed: "hasMany(_:name:using:)") + public static func hasMany( + _ destination: Destination.Type, + key: String?, + using foreignKey: ForeignKey? = nil) + -> HasManyAssociation + where Destination: TableRecord + { preconditionFailure() } + + @available(*, unavailable, renamed: "hasOne(_:name:using:)") + public static func hasOne( + _ destination: Destination.Type, + key: String?, + using foreignKey: ForeignKey? = nil) + -> HasOneAssociation + where Destination: TableRecord + { preconditionFailure() } +} diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift index 1ef246423..83191dd2c 100644 --- a/GRDB/QueryInterface/Association/Association.swift +++ b/GRDB/QueryInterface/Association/Association.swift @@ -69,7 +69,7 @@ extension Association { /// for row in Row.fetchAll(db, request) { /// let team: Team = row["custom"] /// } - var key: String { + var key: SQLAssociationKey { return sqlAssociation.destinationKey } @@ -196,6 +196,8 @@ extension Association { /// let team: Team = row["custom"] /// } public func forKey(_ key: String) -> Self { + // TODO: consider instead Player.including(required: Player.team, forKey: "custom") + let key = SQLAssociationKey(name: key, isInflectable: false) return Self.init(sqlAssociation: sqlAssociation.forDestinationKey(key)) } @@ -373,7 +375,7 @@ extension AssociationToMany where OriginRowDecoder: TableRecord { /// /// Team.annotated(with: Team.players.count()) public var count: AssociationAggregate { - return makeAggregate(SQLExpressionCountDistinct(Column.rowID)).aliased("\(key)Count") + return makeAggregate(SQLExpressionCountDistinct(Column.rowID)).aliased("\(key.singularizedName)Count") } /// An aggregate that is true if there exists no associated records. @@ -395,7 +397,8 @@ extension AssociationToMany where OriginRowDecoder: TableRecord { public func average(_ expression: SQLExpressible) -> AssociationAggregate { let aggregate = makeAggregate(SQLExpressionFunction(.avg, arguments: expression)) if let column = expression as? ColumnExpression { - return aggregate.aliased("average\(key.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") + let name = key.singularizedName + return aggregate.aliased("average\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") } else { return aggregate } @@ -409,7 +412,8 @@ extension AssociationToMany where OriginRowDecoder: TableRecord { public func max(_ expression: SQLExpressible) -> AssociationAggregate { let aggregate = makeAggregate(SQLExpressionFunction(.max, arguments: expression)) if let column = expression as? ColumnExpression { - return aggregate.aliased("max\(key.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") + let name = key.singularizedName + return aggregate.aliased("max\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") } else { return aggregate } @@ -423,7 +427,8 @@ extension AssociationToMany where OriginRowDecoder: TableRecord { public func min(_ expression: SQLExpressible) -> AssociationAggregate { let aggregate = makeAggregate(SQLExpressionFunction(.min, arguments: expression)) if let column = expression as? ColumnExpression { - return aggregate.aliased("min\(key.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") + let name = key.singularizedName + return aggregate.aliased("min\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") } else { return aggregate } @@ -437,7 +442,8 @@ extension AssociationToMany where OriginRowDecoder: TableRecord { public func sum(_ expression: SQLExpressible) -> AssociationAggregate { let aggregate = makeAggregate(SQLExpressionFunction(.sum, arguments: expression)) if let column = expression as? ColumnExpression { - return aggregate.aliased("\(key)\(column.name.uppercasingFirstCharacter)Sum") + let name = key.singularizedName + return aggregate.aliased("\(name)\(column.name.uppercasingFirstCharacter)Sum") } else { return aggregate } @@ -451,6 +457,27 @@ extension AssociationToMany where OriginRowDecoder: TableRecord { /// The base protocol for all associations that define a one-to-one connection. public protocol AssociationToOne: Association { } +// MARK: - SQLAssociationKey + +struct SQLAssociationKey { + var name: String + var isInflectable: Bool + + var pluralizedName: String { + guard isInflectable else { + return name + } + return name.pluralized + } + + var singularizedName: String { + guard isInflectable else { + return name + } + return name.singularized + } +} + // MARK: - SQLAssociation /// An SQL association is a non-empty chain on steps which starts from the @@ -506,24 +533,31 @@ public protocol AssociationToOne: Association { } /// :nodoc: public /* TODO: internal */ struct SQLAssociation { private struct AssociationStep { - var key: String + var key: SQLAssociationKey var condition: SQLAssociationCondition var relation: SQLRelation + var isSingular: Bool func mapRelation(_ transform: (SQLRelation) -> SQLRelation) -> AssociationStep { - return AssociationStep(key: key, condition: condition, relation: transform(relation)) + return AssociationStep(key: key, condition: condition, relation: transform(relation), isSingular: isSingular) } } // All steps, from pivot to destination. Never empty. private var steps: [AssociationStep] - var keyPath: [String] { return steps.map { $0.key} } + var keyPath: [String] { + return steps.map { + $0.isSingular + ? $0.key.singularizedName + : $0.key.pluralizedName + } + } private var destination: AssociationStep { get { return steps[steps.count - 1] } set { steps[steps.count - 1] = newValue } } - var destinationKey: String { return destination.key } + var destinationKey: SQLAssociationKey { return destination.key } private var pivot: AssociationStep { get { return steps[0] } @@ -538,19 +572,24 @@ public /* TODO: internal */ struct SQLAssociation { self.steps = steps } - init(key: String, condition: SQLAssociationCondition, relation: SQLRelation) { - self.init(steps: [AssociationStep(key: key, condition: condition, relation: relation)]) + init( + key: SQLAssociationKey, + condition: SQLAssociationCondition, + relation: SQLRelation, + isSingular: Bool) + { + self.init(steps: [AssociationStep(key: key, condition: condition, relation: relation, isSingular: isSingular)]) } /// Changes the destination key - func forDestinationKey(_ key: String) -> SQLAssociation { + func forDestinationKey(_ key: SQLAssociationKey) -> SQLAssociation { var result = self result.destination.key = key return result } /// Changes the pivot key - func forPivotKey(_ key: String) -> SQLAssociation { + func forPivotKey(_ key: SQLAssociationKey) -> SQLAssociation { var result = self result.pivot.key = key return result @@ -624,7 +663,10 @@ public /* TODO: internal */ struct SQLAssociation { // // let association = Origin.belongsTo(Destination.self) // Origin.including(required: association) - return origin.appendingChild(destinationChild, forKey: destination.key) + let key = kind.isSingular + ? destination.key.singularizedName + : destination.key.pluralizedName + return origin.appendingChild(destinationChild, forKey: key) } // This is an indirect join from origin to destination, through @@ -644,13 +686,12 @@ public /* TODO: internal */ struct SQLAssociation { // Let's recurse toward a direct join, by making a new association which // ends on the last pivot, to which we join our destination: var reducedAssociation = SQLAssociation(steps: Array(initialSteps)) - reducedAssociation = reducedAssociation.mapDestinationRelation { - $0.appendingChild(destinationChild, forKey: destination.key) - } - // Intermediate steps are not prefetched - reducedAssociation = reducedAssociation.mapDestinationRelation { - $0.select([]) - } + let key = (kind.isSingular || reducedAssociation.destination.isSingular) + ? destination.key.singularizedName + : destination.key.pluralizedName + reducedAssociation.destination.relation = reducedAssociation.destination.relation + .select([]) // Intermediate steps are not prefetched + .appendingChild(destinationChild, forKey: key) switch kind { case .oneRequired, .oneOptional, .allNotPrefetched: @@ -710,7 +751,7 @@ public /* TODO: internal */ struct SQLAssociation { // key, and prevent merging of intermediate steps of // indirect associations: return reducedAssociation - .forPivotKey("grdb_\(UUID().uuidString)") + .forPivotKey(SQLAssociationKey(name: "grdb_\(UUID().uuidString)", isInflectable: false)) .extendedRelation(origin, kind: .allNotPrefetched) } } @@ -799,7 +840,8 @@ public /* TODO: internal */ struct SQLAssociation { return AssociationStep( key: step.key, condition: nextStep.condition.reversed, - relation: relation) + relation: relation, + isSingular: step.isSingular) } .reversed() diff --git a/GRDB/QueryInterface/Association/BelongsToAssociation.swift b/GRDB/QueryInterface/Association/BelongsToAssociation.swift index e1ebb9107..1b0917157 100644 --- a/GRDB/QueryInterface/Association/BelongsToAssociation.swift +++ b/GRDB/QueryInterface/Association/BelongsToAssociation.swift @@ -136,7 +136,7 @@ extension TableRecord { /// foreign keys to the destination table. public static func belongsTo( _ destination: Destination.Type, - key: String? = nil, + name: String? = nil, // TODD: fixit because `name` has replaced `key` using foreignKey: ForeignKey? = nil) -> BelongsToAssociation where Destination: TableRecord @@ -151,8 +151,9 @@ extension TableRecord { originIsLeft: true) return BelongsToAssociation(sqlAssociation: SQLAssociation( - key: key ?? Destination.databaseTableName, + key: SQLAssociationKey(name: name ?? Destination.databaseTableName, isInflectable: true), condition: condition, - relation: Destination.all().relation)) + relation: Destination.all().relation, + isSingular: true)) } } diff --git a/GRDB/QueryInterface/Association/HasManyAssociation.swift b/GRDB/QueryInterface/Association/HasManyAssociation.swift index 88e59b5c1..66294dfd7 100644 --- a/GRDB/QueryInterface/Association/HasManyAssociation.swift +++ b/GRDB/QueryInterface/Association/HasManyAssociation.swift @@ -136,7 +136,7 @@ extension TableRecord { /// foreign keys from the destination table. public static func hasMany( _ destination: Destination.Type, - key: String? = nil, + name: String? = nil, // TODD: fixit because `name` has replaced `key` using foreignKey: ForeignKey? = nil) -> HasManyAssociation where Destination: TableRecord @@ -151,8 +151,9 @@ extension TableRecord { originIsLeft: false) return HasManyAssociation(sqlAssociation: SQLAssociation( - key: key ?? Destination.databaseTableName, + key: SQLAssociationKey(name: name ?? Destination.databaseTableName, isInflectable: true), condition: condition, - relation: Destination.all().relation)) + relation: Destination.all().relation, + isSingular: false)) } } diff --git a/GRDB/QueryInterface/Association/HasOneAssociation.swift b/GRDB/QueryInterface/Association/HasOneAssociation.swift index f5a6f6885..685f1b762 100644 --- a/GRDB/QueryInterface/Association/HasOneAssociation.swift +++ b/GRDB/QueryInterface/Association/HasOneAssociation.swift @@ -138,7 +138,7 @@ extension TableRecord { /// foreign keys from the destination table. public static func hasOne( _ destination: Destination.Type, - key: String? = nil, + name: String? = nil, // TODD: fixit because `name` has replaced `key` using foreignKey: ForeignKey? = nil) -> HasOneAssociation where Destination: TableRecord @@ -153,8 +153,9 @@ extension TableRecord { originIsLeft: false) return HasOneAssociation(sqlAssociation: SQLAssociation( - key: key ?? Destination.databaseTableName, + key: SQLAssociationKey(name: name ?? Destination.databaseTableName, isInflectable: true), condition: condition, - relation: Destination.all().relation)) + relation: Destination.all().relation, + isSingular: true)) } } diff --git a/GRDB/QueryInterface/SQLRelation.swift b/GRDB/QueryInterface/SQLRelation.swift index 62114fed3..a09abba9c 100644 --- a/GRDB/QueryInterface/SQLRelation.swift +++ b/GRDB/QueryInterface/SQLRelation.swift @@ -109,6 +109,15 @@ struct SQLRelation { case allPrefetched // Record.including(all: associationThroughPivot) case allNotPrefetched + + var isSingular: Bool { + switch self { + case .oneOptional, .oneRequired: + return true + case .allPrefetched, .allNotPrefetched: + return false + } + } } var kind: Kind @@ -129,7 +138,8 @@ struct SQLRelation { } fileprivate func makeAssociationForKey(_ key: String) -> SQLAssociation { - return SQLAssociation(key: key, condition: condition, relation: relation) + let key = SQLAssociationKey(name: key, isInflectable: false) + return SQLAssociation(key: key, condition: condition, relation: relation, isSingular: kind.isSingular) } func mapRelation(_ transform: (SQLRelation) -> SQLRelation) -> Child { diff --git a/GRDB/Utils/Inflections.swift b/GRDB/Utils/Inflections.swift index 2f34b3731..9f03cfa60 100644 --- a/GRDB/Utils/Inflections.swift +++ b/GRDB/Utils/Inflections.swift @@ -218,6 +218,7 @@ extension Inflections { inflections.plural("^(ox)$", "$1en") inflections.plural("^(oxen)$", "$1") inflections.plural("(quiz)$", "$1zes") + inflections.plural("(canva)s$", "$1ses") inflections.singular("s$", "") inflections.singular("(ss)$", "$1") @@ -246,6 +247,7 @@ extension Inflections { inflections.singular("(matr)ices$", "$1ix") inflections.singular("(quiz)zes$", "$1") inflections.singular("(database)s$", "$1") + inflections.singular("(canvas)(es)?$", "$1") inflections.uncountable( "equipment", diff --git a/Tests/GRDBTests/AssociationAggregateTests.swift b/Tests/GRDBTests/AssociationAggregateTests.swift index 32b86f5a6..5c7ccb798 100644 --- a/Tests/GRDBTests/AssociationAggregateTests.swift +++ b/Tests/GRDBTests/AssociationAggregateTests.swift @@ -8,7 +8,7 @@ import XCTest private struct Team: Codable, FetchableRecord, PersistableRecord { static let players = hasMany(Player.self) static let awards = hasMany(Award.self) - static let customPlayers = hasMany(Player.self, key: "custom") + static let customPlayers = hasMany(Player.self, name: "custom") var id: Int64 var name: String } diff --git a/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift b/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift index ec626f595..30bcde532 100644 --- a/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift @@ -14,7 +14,7 @@ private struct Team: Codable, FetchableRecord, PersistableRecord { private struct Player: Codable, FetchableRecord, PersistableRecord { static let databaseTableName = "players" static let teamScope = "team" - static let team = Player.belongsTo(Team.self, key: teamScope) + static let team = Player.belongsTo(Team.self, name: teamScope) var id: Int64 var teamId: Int64? var name: String diff --git a/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift b/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift index a255b93fb..c07a2b8f5 100644 --- a/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift @@ -14,7 +14,7 @@ private struct Team: Codable, FetchableRecord, PersistableRecord { private struct Player: Codable, FetchableRecord, PersistableRecord { static let databaseTableName = "players" static let defaultTeam = belongsTo(Team.self) - static let customTeam = belongsTo(Team.self, key: "customTeam") + static let customTeam = belongsTo(Team.self, name: "customTeam") var id: Int64 var teamId: Int64? var name: String @@ -56,8 +56,8 @@ class AssociationBelongsToRowScopeTests: GRDBTestCase { let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 1) XCTAssertEqual(rows[0].unscoped, ["id":1, "teamId":1, "name":"Arthur"]) - XCTAssertEqual(Set(rows[0].scopes.names), ["teams"]) - XCTAssertEqual(rows[0].scopes["teams"]!, ["id":1, "name":"Reds"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["team"]) + XCTAssertEqual(rows[0].scopes["team"]!, ["id":1, "name":"Reds"]) } func testDefaultScopeIncludingOptional() throws { @@ -66,11 +66,11 @@ class AssociationBelongsToRowScopeTests: GRDBTestCase { let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0].unscoped, ["id":1, "teamId":1, "name":"Arthur"]) - XCTAssertEqual(Set(rows[0].scopes.names), ["teams"]) - XCTAssertEqual(rows[0].scopes["teams"]!, ["id":1, "name":"Reds"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["team"]) + XCTAssertEqual(rows[0].scopes["team"]!, ["id":1, "name":"Reds"]) XCTAssertEqual(rows[1].unscoped, ["id":2, "teamId":nil, "name":"Barbara"]) - XCTAssertEqual(Set(rows[1].scopes.names), ["teams"]) - XCTAssertEqual(rows[1].scopes["teams"]!, ["id":nil, "name":nil]) + XCTAssertEqual(Set(rows[1].scopes.names), ["team"]) + XCTAssertEqual(rows[1].scopes["team"]!, ["id":nil, "name":nil]) } func testDefaultScopeJoiningRequired() throws { diff --git a/Tests/GRDBTests/AssociationParallelRowScopesTests.swift b/Tests/GRDBTests/AssociationParallelRowScopesTests.swift index a759451e9..a7dce00fb 100644 --- a/Tests/GRDBTests/AssociationParallelRowScopesTests.swift +++ b/Tests/GRDBTests/AssociationParallelRowScopesTests.swift @@ -11,8 +11,8 @@ private struct A: Codable, FetchableRecord, PersistableRecord { static let databaseTableName = "a" static let defaultB = belongsTo(B.self) static let defaultD = belongsTo(D.self) - static let customB = belongsTo(B.self, key: "customB") - static let customD = belongsTo(D.self, key: "customD") + static let customB = belongsTo(B.self, name: "customB") + static let customD = belongsTo(D.self, name: "customD") var id: Int64 var bid: Int64? var did: Int64? @@ -22,8 +22,8 @@ private struct A: Codable, FetchableRecord, PersistableRecord { private struct B: Codable, FetchableRecord, PersistableRecord { static let defaultA = hasOne(A.self) static let defaultC = hasOne(C.self) - static let customA = hasOne(A.self, key: "customA") - static let customC = hasOne(C.self, key: "customC") + static let customA = hasOne(A.self, name: "customA") + static let customC = hasOne(C.self, name: "customC") static let databaseTableName = "b" var id: Int64 var name: String @@ -38,7 +38,7 @@ private struct C: Codable, FetchableRecord, PersistableRecord { private struct D: Codable, FetchableRecord, PersistableRecord { static let defaultA = hasOne(A.self) - static let customA = hasOne(A.self, key: "customA") + static let customA = hasOne(A.self, name: "customA") static let databaseTableName = "d" var id: Int64 var name: String diff --git a/Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift b/Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift index 92c161bf6..33cba97de 100644 --- a/Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift +++ b/Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift @@ -12,13 +12,13 @@ private struct A : TableRecord { static let databaseTableName = "a" static let parent = belongsTo(A.self) static let child = hasOne(A.self) - static let b1 = belongsTo(B.self, key: "b1", using: ForeignKey(["bid1"])) - static let b2 = belongsTo(B.self, key: "b2", using: ForeignKey(["bid2"])) + static let b1 = belongsTo(B.self, name: "b1", using: ForeignKey(["bid1"])) + static let b2 = belongsTo(B.self, name: "b2", using: ForeignKey(["bid2"])) } private struct B : TableRecord { static let databaseTableName = "b" - static let a1 = hasOne(A.self, key: "a1", using: ForeignKey(["bid1"])) - static let a2 = hasOne(A.self, key: "a1", using: ForeignKey(["bid2"])) + static let a1 = hasOne(A.self, name: "a1", using: ForeignKey(["bid1"])) + static let a2 = hasOne(A.self, name: "a1", using: ForeignKey(["bid2"])) } /// Tests for table name conflicts, recursive associations,