Association name is turned into singularized or pluralized keys

This commit is contained in:
Gwendal Roué committed 2019-05-19 07:33:18 +02:00
1 parent 35027a825f
commit ca76032b8b
12 files changed
+138 -52

No files matched your search

+29
View File
@@ -155,3 +155,32 @@ extension Configuration {
set { preconditionFailure() }
}
}
extension TableRecord {
@available(*, unavailable, renamed: "belongsTo(_:name:using:)")
public static func belongsTo<Destination>(
_ destination: Destination.Type,
key: String?,
using foreignKey: ForeignKey? = nil)
-> BelongsToAssociation<Self, Destination>
where Destination: TableRecord
{ preconditionFailure() }
@available(*, unavailable, renamed: "hasMany(_:name:using:)")
public static func hasMany<Destination>(
_ destination: Destination.Type,
key: String?,
using foreignKey: ForeignKey? = nil)
-> HasManyAssociation<Self, Destination>
where Destination: TableRecord
{ preconditionFailure() }
@available(*, unavailable, renamed: "hasOne(_:name:using:)")
public static func hasOne<Destination>(
_ destination: Destination.Type,
key: String?,
using foreignKey: ForeignKey? = nil)
-> HasOneAssociation<Self, Destination>
where Destination: TableRecord
{ preconditionFailure() }
}
@@ -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<OriginRowDecoder> {
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<OriginRowDecoder> {
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<OriginRowDecoder> {
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<OriginRowDecoder> {
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<OriginRowDecoder> {
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()
@@ -136,7 +136,7 @@ extension TableRecord {
/// foreign keys to the destination table.
public static func belongsTo<Destination>(
_ destination: Destination.Type,
key: String? = nil,
name: String? = nil, // TODD: fixit because `name` has replaced `key`
using foreignKey: ForeignKey? = nil)
-> BelongsToAssociation<Self, Destination>
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))
}
}
@@ -136,7 +136,7 @@ extension TableRecord {
/// foreign keys from the destination table.
public static func hasMany<Destination>(
_ destination: Destination.Type,
key: String? = nil,
name: String? = nil, // TODD: fixit because `name` has replaced `key`
using foreignKey: ForeignKey? = nil)
-> HasManyAssociation<Self, Destination>
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))
}
}
@@ -138,7 +138,7 @@ extension TableRecord {
/// foreign keys from the destination table.
public static func hasOne<Destination>(
_ destination: Destination.Type,
key: String? = nil,
name: String? = nil, // TODD: fixit because `name` has replaced `key`
using foreignKey: ForeignKey? = nil)
-> HasOneAssociation<Self, Destination>
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))
}
}
+11 -1
View File
@@ -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 {
+2
View File
@@ -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",
@@ -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
}
@@ -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
@@ -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 {
@@ -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
@@ -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,