More Associations and inflections

This commit is contained in:
Gwendal Roué committed 2019-05-19 15:03:54 +02:00
1 parent a1b0baaca9
commit 8e2a8fe9d8
17 files changed
+236 -203

No files matched your search

-29
View File
@@ -155,32 +155,3 @@ 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() }
}
@@ -196,9 +196,15 @@ 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))
let associationKey: SQLAssociationKey
if sqlAssociation.destinationIsSingular {
assert(key.singularized == key)
associationKey = .inflectableSingular(key)
} else {
assert(key.pluralized == key)
associationKey = .inflectablePlural(key)
}
return Self.init(sqlAssociation: sqlAssociation.forDestinationKey(associationKey))
}
/// Creates an association with the given key.
@@ -459,22 +465,36 @@ public protocol AssociationToOne: Association { }
// MARK: - SQLAssociationKey
struct SQLAssociationKey {
var name: String
var isInflectable: Bool
enum SQLAssociationKey {
case inflectableSingular(String)
case inflectablePlural(String)
case inflectable(String)
case fixed(String)
var pluralizedName: String {
guard isInflectable else {
switch self {
case .inflectableSingular(let name):
return name.pluralized
case .inflectablePlural(let name):
return name
case .inflectable(let name):
return name.pluralized
case .fixed(let name):
return name
}
return name.pluralized
}
var singularizedName: String {
guard isInflectable else {
switch self {
case .inflectableSingular(let name):
return name
case .inflectablePlural(let name):
return name.singularized
case .inflectable(let name):
return name.singularized
case .fixed(let name):
return name
}
return name.singularized
}
}
@@ -558,6 +578,7 @@ public /* TODO: internal */ struct SQLAssociation {
set { steps[steps.count - 1] = newValue }
}
var destinationKey: SQLAssociationKey { return destination.key }
var destinationIsSingular: Bool { return destination.isSingular }
private var pivot: AssociationStep {
get { return steps[0] }
@@ -751,7 +772,7 @@ public /* TODO: internal */ struct SQLAssociation {
// key, and prevent merging of intermediate steps of
// indirect associations:
return reducedAssociation
.forPivotKey(SQLAssociationKey(name: "grdb_\(UUID().uuidString)", isInflectable: false))
.forPivotKey(SQLAssociationKey.fixed("grdb_\(UUID().uuidString)"))
.extendedRelation(origin, kind: .allNotPrefetched)
}
}
@@ -136,7 +136,7 @@ extension TableRecord {
/// foreign keys to the destination table.
public static func belongsTo<Destination>(
_ destination: Destination.Type,
name: String? = nil, // TODD: fixit because `name` has replaced `key`
key: String? = nil,
using foreignKey: ForeignKey? = nil)
-> BelongsToAssociation<Self, Destination>
where Destination: TableRecord
@@ -150,8 +150,16 @@ extension TableRecord {
foreignKeyRequest: foreignKeyRequest,
originIsLeft: true)
let associationKey: SQLAssociationKey
if let key = key {
assert(key.singularized == key)
associationKey = .inflectableSingular(key)
} else {
associationKey = .inflectable(Destination.databaseTableName)
}
return BelongsToAssociation(sqlAssociation: SQLAssociation(
key: SQLAssociationKey(name: name ?? Destination.databaseTableName, isInflectable: true),
key: associationKey,
condition: condition,
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,
name: String? = nil, // TODD: fixit because `name` has replaced `key`
key: String? = nil,
using foreignKey: ForeignKey? = nil)
-> HasManyAssociation<Self, Destination>
where Destination: TableRecord
@@ -150,8 +150,16 @@ extension TableRecord {
foreignKeyRequest: foreignKeyRequest,
originIsLeft: false)
let associationKey: SQLAssociationKey
if let key = key {
assert(key.pluralized == key)
associationKey = .inflectablePlural(key)
} else {
associationKey = .inflectable(Destination.databaseTableName)
}
return HasManyAssociation(sqlAssociation: SQLAssociation(
key: SQLAssociationKey(name: name ?? Destination.databaseTableName, isInflectable: true),
key: associationKey,
condition: condition,
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,
name: String? = nil, // TODD: fixit because `name` has replaced `key`
key: String? = nil,
using foreignKey: ForeignKey? = nil)
-> HasOneAssociation<Self, Destination>
where Destination: TableRecord
@@ -152,8 +152,16 @@ extension TableRecord {
foreignKeyRequest: foreignKeyRequest,
originIsLeft: false)
let associationKey: SQLAssociationKey
if let key = key {
assert(key.singularized == key)
associationKey = .inflectableSingular(key)
} else {
associationKey = .inflectable(Destination.databaseTableName)
}
return HasOneAssociation(sqlAssociation: SQLAssociation(
key: SQLAssociationKey(name: name ?? Destination.databaseTableName, isInflectable: true),
key: associationKey,
condition: condition,
relation: Destination.all().relation,
isSingular: true))
+1 -15
View File
@@ -321,7 +321,7 @@ extension Array where Element == TableAlias {
var index = 1
for alias in group {
if alias.hasUserName { continue }
let radical = alias.identityName.databaseQualifierRadical
let radical = alias.identityName.digitlessRadical
var resolvedName: String
repeat {
resolvedName = "\(radical)\(index)"
@@ -334,17 +334,3 @@ extension Array where Element == TableAlias {
return resolvedNames
}
}
extension String {
/// "bar" => "bar"
/// "foo12" => "foo"
fileprivate var databaseQualifierRadical: String {
let digits: ClosedRange<Character> = "0"..."9"
let radicalEndIndex = self // "foo12"
.reversed() // "21oof"
.prefix(while: { digits.contains($0) }) // "21"
.endIndex // reversed(foo^12)
.base // foo^12
return String(prefix(upTo: radicalEndIndex))
}
}
+1 -1
View File
@@ -138,7 +138,7 @@ struct SQLRelation {
}
fileprivate func makeAssociationForKey(_ key: String) -> SQLAssociation {
let key = SQLAssociationKey(name: key, isInflectable: false)
let key = SQLAssociationKey.fixed(key)
return SQLAssociation(key: key, condition: condition, relation: relation, isSingular: kind.isSingular)
}
+34 -13
View File
@@ -20,6 +20,12 @@ extension String {
var singularized: String {
return Inflections.default.singularize(self)
}
/// "bar" -> "bar"
/// "foo12" -> "foo"
var digitlessRadical: String {
return String(prefix(upTo: Inflections.endIndexOfDigitlessRadical(self)))
}
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
@@ -142,22 +148,12 @@ public struct Inflections {
///
/// Inflections.default.pluralize("player") // "players"
public func pluralize(_ string: String) -> String {
let indexOfLastWord = Inflections.startIndexOfLastWord(string)
let lastWord = String(string.suffix(from: indexOfLastWord))
if isUncountable(lastWord) {
return string
}
return string.prefix(upTo: indexOfLastWord) + inflect(lastWord, with: pluralizeRules)
return inflectString(string, with: pluralizeRules)
}
/// Returns a singularized string.
public func singularize(_ string: String) -> String {
let indexOfLastWord = Inflections.startIndexOfLastWord(string)
let lastWord = String(string.suffix(from: indexOfLastWord))
if isUncountable(lastWord) {
return string
}
return string.prefix(upTo: indexOfLastWord) + inflect(lastWord, with: singularizeRules)
return inflectString(string, with: singularizeRules)
}
// MARK: - Utils
@@ -172,7 +168,21 @@ public struct Inflections {
return false
}
private func inflect(_ string: String, with rules: [(NSRegularExpression, String)]) -> String {
private func inflectString(_ string: String, with rules: [(NSRegularExpression, String)]) -> String {
let indexOfLastWord = Inflections.startIndexOfLastWord(string)
let endIndexOfDigitlessRadical = Inflections.endIndexOfDigitlessRadical(string)
let lastWord = String(string[indexOfLastWord..<endIndexOfDigitlessRadical])
if isUncountable(lastWord) {
return string
}
return """
\(string.prefix(upTo: indexOfLastWord))\
\(inflectWord(lastWord, with: rules))\
\(string.suffix(from: endIndexOfDigitlessRadical))
"""
}
private func inflectWord(_ string: String, with rules: [(NSRegularExpression, String)]) -> String {
if string.isEmpty {
return string
}
@@ -210,6 +220,17 @@ public struct Inflections {
return [index1, index2, index3].compactMap { $0 }.max() ?? string.startIndex
}
/// "bar" -> "bar"
/// "foo12" -> "foo"
static func endIndexOfDigitlessRadical(_ string: String) -> String.Index {
let digits: ClosedRange<Character> = "0"..."9"
return string // "foo12"
.reversed() // "21oof"
.prefix(while: { digits.contains($0) }) // "21"
.endIndex // reversed(foo^12)
.base // foo^12
}
private static let wordBoundaryReg = try! NSRegularExpression(pattern: "\\b\\w+$", options: [])
private static let underscoreBoundaryReg = try! NSRegularExpression(pattern: "_[^_]+$", options: [])
private static let caseBoundaryReg = try! NSRegularExpression(pattern: "[^A-Z][A-Z]+[a-z1-9]+$", options: [])
+58 -58
View File
@@ -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, name: "custom")
static let customPlayers = hasMany(Player.self, key: "customPlayers")
var id: Int64
var name: String
}
@@ -38,11 +38,11 @@ private struct TeamInfo: Decodable, FetchableRecord {
private struct CustomTeamInfo: Decodable, FetchableRecord {
var team: Team
var averageCustomScore: Double?
var customCount: Int?
var maxCustomScore: Int?
var minCustomScore: Int?
var customScoreSum: Int?
var averageCustomPlayerScore: Double?
var customPlayerCount: Int?
var maxCustomPlayerScore: Int?
var minCustomPlayerScore: Int?
var customPlayerScoreSum: Int?
}
class AssociationAggregateTests: GRDBTestCase {
@@ -416,7 +416,7 @@ class AssociationAggregateTests: GRDBTestCase {
.asRequest(of: CustomTeamInfo.self)
try assertEqualSQL(db, request, """
SELECT "team".*, AVG("player"."score") AS "averageCustomScore" \
SELECT "team".*, AVG("player"."score") AS "averageCustomPlayerScore" \
FROM "team" \
LEFT JOIN "player" ON ("player"."teamId" = "team"."id") \
GROUP BY "team"."id" \
@@ -428,19 +428,19 @@ class AssociationAggregateTests: GRDBTestCase {
XCTAssertEqual(teamInfos[0].team.id, 1)
XCTAssertEqual(teamInfos[0].team.name, "Reds")
XCTAssertEqual(teamInfos[0].averageCustomScore, 550)
XCTAssertEqual(teamInfos[0].averageCustomPlayerScore, 550)
XCTAssertEqual(teamInfos[1].team.id, 2)
XCTAssertEqual(teamInfos[1].team.name, "Blues")
XCTAssertEqual(teamInfos[1].averageCustomScore, 500)
XCTAssertEqual(teamInfos[1].averageCustomPlayerScore, 500)
XCTAssertEqual(teamInfos[2].team.id, 3)
XCTAssertEqual(teamInfos[2].team.name, "Greens")
XCTAssertNil(teamInfos[2].averageCustomScore)
XCTAssertNil(teamInfos[2].averageCustomPlayerScore)
XCTAssertEqual(teamInfos[3].team.id, 4)
XCTAssertEqual(teamInfos[3].team.name, "Oranges")
XCTAssertEqual(teamInfos[3].averageCustomScore, 0)
XCTAssertEqual(teamInfos[3].averageCustomPlayerScore, 0)
}
}
@@ -453,7 +453,7 @@ class AssociationAggregateTests: GRDBTestCase {
.asRequest(of: CustomTeamInfo.self)
try assertEqualSQL(db, request, """
SELECT "team".*, COUNT(DISTINCT "player"."rowid") AS "customCount" \
SELECT "team".*, COUNT(DISTINCT "player"."rowid") AS "customPlayerCount" \
FROM "team" \
LEFT JOIN "player" ON ("player"."teamId" = "team"."id") \
GROUP BY "team"."id" \
@@ -465,19 +465,19 @@ class AssociationAggregateTests: GRDBTestCase {
XCTAssertEqual(teamInfos[0].team.id, 1)
XCTAssertEqual(teamInfos[0].team.name, "Reds")
XCTAssertEqual(teamInfos[0].customCount, 2)
XCTAssertEqual(teamInfos[0].customPlayerCount, 2)
XCTAssertEqual(teamInfos[1].team.id, 2)
XCTAssertEqual(teamInfos[1].team.name, "Blues")
XCTAssertEqual(teamInfos[1].customCount, 3)
XCTAssertEqual(teamInfos[1].customPlayerCount, 3)
XCTAssertEqual(teamInfos[2].team.id, 3)
XCTAssertEqual(teamInfos[2].team.name, "Greens")
XCTAssertEqual(teamInfos[2].customCount, 0)
XCTAssertEqual(teamInfos[2].customPlayerCount, 0)
XCTAssertEqual(teamInfos[3].team.id, 4)
XCTAssertEqual(teamInfos[3].team.name, "Oranges")
XCTAssertEqual(teamInfos[3].customCount, 1)
XCTAssertEqual(teamInfos[3].customPlayerCount, 1)
}
}
@@ -490,7 +490,7 @@ class AssociationAggregateTests: GRDBTestCase {
.asRequest(of: CustomTeamInfo.self)
try assertEqualSQL(db, request, """
SELECT "team".*, MAX("player"."score") AS "maxCustomScore" \
SELECT "team".*, MAX("player"."score") AS "maxCustomPlayerScore" \
FROM "team" \
LEFT JOIN "player" ON ("player"."teamId" = "team"."id") \
GROUP BY "team"."id" \
@@ -502,19 +502,19 @@ class AssociationAggregateTests: GRDBTestCase {
XCTAssertEqual(teamInfos[0].team.id, 1)
XCTAssertEqual(teamInfos[0].team.name, "Reds")
XCTAssertEqual(teamInfos[0].maxCustomScore, 1000)
XCTAssertEqual(teamInfos[0].maxCustomPlayerScore, 1000)
XCTAssertEqual(teamInfos[1].team.id, 2)
XCTAssertEqual(teamInfos[1].team.name, "Blues")
XCTAssertEqual(teamInfos[1].maxCustomScore, 800)
XCTAssertEqual(teamInfos[1].maxCustomPlayerScore, 800)
XCTAssertEqual(teamInfos[2].team.id, 3)
XCTAssertEqual(teamInfos[2].team.name, "Greens")
XCTAssertNil(teamInfos[2].maxCustomScore)
XCTAssertNil(teamInfos[2].maxCustomPlayerScore)
XCTAssertEqual(teamInfos[3].team.id, 4)
XCTAssertEqual(teamInfos[3].team.name, "Oranges")
XCTAssertEqual(teamInfos[3].maxCustomScore, 0)
XCTAssertEqual(teamInfos[3].maxCustomPlayerScore, 0)
}
}
@@ -527,7 +527,7 @@ class AssociationAggregateTests: GRDBTestCase {
.asRequest(of: CustomTeamInfo.self)
try assertEqualSQL(db, request, """
SELECT "team".*, MIN("player"."score") AS "minCustomScore" \
SELECT "team".*, MIN("player"."score") AS "minCustomPlayerScore" \
FROM "team" \
LEFT JOIN "player" ON ("player"."teamId" = "team"."id") \
GROUP BY "team"."id" \
@@ -539,19 +539,19 @@ class AssociationAggregateTests: GRDBTestCase {
XCTAssertEqual(teamInfos[0].team.id, 1)
XCTAssertEqual(teamInfos[0].team.name, "Reds")
XCTAssertEqual(teamInfos[0].minCustomScore, 100)
XCTAssertEqual(teamInfos[0].minCustomPlayerScore, 100)
XCTAssertEqual(teamInfos[1].team.id, 2)
XCTAssertEqual(teamInfos[1].team.name, "Blues")
XCTAssertEqual(teamInfos[1].minCustomScore, 200)
XCTAssertEqual(teamInfos[1].minCustomPlayerScore, 200)
XCTAssertEqual(teamInfos[2].team.id, 3)
XCTAssertEqual(teamInfos[2].team.name, "Greens")
XCTAssertNil(teamInfos[2].minCustomScore)
XCTAssertNil(teamInfos[2].minCustomPlayerScore)
XCTAssertEqual(teamInfos[3].team.id, 4)
XCTAssertEqual(teamInfos[3].team.name, "Oranges")
XCTAssertEqual(teamInfos[3].minCustomScore, 0)
XCTAssertEqual(teamInfos[3].minCustomPlayerScore, 0)
}
}
@@ -564,7 +564,7 @@ class AssociationAggregateTests: GRDBTestCase {
.asRequest(of: CustomTeamInfo.self)
try assertEqualSQL(db, request, """
SELECT "team".*, SUM("player"."score") AS "customScoreSum" \
SELECT "team".*, SUM("player"."score") AS "customPlayerScoreSum" \
FROM "team" \
LEFT JOIN "player" ON ("player"."teamId" = "team"."id") \
GROUP BY "team"."id" \
@@ -576,19 +576,19 @@ class AssociationAggregateTests: GRDBTestCase {
XCTAssertEqual(teamInfos[0].team.id, 1)
XCTAssertEqual(teamInfos[0].team.name, "Reds")
XCTAssertEqual(teamInfos[0].customScoreSum, 1100)
XCTAssertEqual(teamInfos[0].customPlayerScoreSum, 1100)
XCTAssertEqual(teamInfos[1].team.id, 2)
XCTAssertEqual(teamInfos[1].team.name, "Blues")
XCTAssertEqual(teamInfos[1].customScoreSum, 1500)
XCTAssertEqual(teamInfos[1].customPlayerScoreSum, 1500)
XCTAssertEqual(teamInfos[2].team.id, 3)
XCTAssertEqual(teamInfos[2].team.name, "Greens")
XCTAssertNil(teamInfos[2].customScoreSum)
XCTAssertNil(teamInfos[2].customPlayerScoreSum)
XCTAssertEqual(teamInfos[3].team.id, 4)
XCTAssertEqual(teamInfos[3].team.name, "Oranges")
XCTAssertEqual(teamInfos[3].customScoreSum, 0)
XCTAssertEqual(teamInfos[3].customPlayerScoreSum, 0)
}
}
@@ -605,11 +605,11 @@ class AssociationAggregateTests: GRDBTestCase {
try assertEqualSQL(db, request, """
SELECT "team".*, \
AVG("player"."score") AS "averageCustomScore", \
COUNT(DISTINCT "player"."rowid") AS "customCount", \
MIN("player"."score") AS "minCustomScore", \
MAX("player"."score") AS "maxCustomScore", \
SUM("player"."score") AS "customScoreSum" \
AVG("player"."score") AS "averageCustomPlayerScore", \
COUNT(DISTINCT "player"."rowid") AS "customPlayerCount", \
MIN("player"."score") AS "minCustomPlayerScore", \
MAX("player"."score") AS "maxCustomPlayerScore", \
SUM("player"."score") AS "customPlayerScoreSum" \
FROM "team" \
LEFT JOIN "player" ON ("player"."teamId" = "team"."id") \
GROUP BY "team"."id" \
@@ -621,35 +621,35 @@ class AssociationAggregateTests: GRDBTestCase {
XCTAssertEqual(teamInfos[0].team.id, 1)
XCTAssertEqual(teamInfos[0].team.name, "Reds")
XCTAssertEqual(teamInfos[0].averageCustomScore, 550)
XCTAssertEqual(teamInfos[0].customCount, 2)
XCTAssertEqual(teamInfos[0].maxCustomScore, 1000)
XCTAssertEqual(teamInfos[0].minCustomScore, 100)
XCTAssertEqual(teamInfos[0].customScoreSum, 1100)
XCTAssertEqual(teamInfos[0].averageCustomPlayerScore, 550)
XCTAssertEqual(teamInfos[0].customPlayerCount, 2)
XCTAssertEqual(teamInfos[0].maxCustomPlayerScore, 1000)
XCTAssertEqual(teamInfos[0].minCustomPlayerScore, 100)
XCTAssertEqual(teamInfos[0].customPlayerScoreSum, 1100)
XCTAssertEqual(teamInfos[1].team.id, 2)
XCTAssertEqual(teamInfos[1].team.name, "Blues")
XCTAssertEqual(teamInfos[1].averageCustomScore, 500)
XCTAssertEqual(teamInfos[1].customCount, 3)
XCTAssertEqual(teamInfos[1].maxCustomScore, 800)
XCTAssertEqual(teamInfos[1].minCustomScore, 200)
XCTAssertEqual(teamInfos[1].customScoreSum, 1500)
XCTAssertEqual(teamInfos[1].averageCustomPlayerScore, 500)
XCTAssertEqual(teamInfos[1].customPlayerCount, 3)
XCTAssertEqual(teamInfos[1].maxCustomPlayerScore, 800)
XCTAssertEqual(teamInfos[1].minCustomPlayerScore, 200)
XCTAssertEqual(teamInfos[1].customPlayerScoreSum, 1500)
XCTAssertEqual(teamInfos[2].team.id, 3)
XCTAssertEqual(teamInfos[2].team.name, "Greens")
XCTAssertNil(teamInfos[2].averageCustomScore)
XCTAssertEqual(teamInfos[2].customCount, 0)
XCTAssertNil(teamInfos[2].maxCustomScore)
XCTAssertNil(teamInfos[2].minCustomScore)
XCTAssertNil(teamInfos[2].customScoreSum)
XCTAssertNil(teamInfos[2].averageCustomPlayerScore)
XCTAssertEqual(teamInfos[2].customPlayerCount, 0)
XCTAssertNil(teamInfos[2].maxCustomPlayerScore)
XCTAssertNil(teamInfos[2].minCustomPlayerScore)
XCTAssertNil(teamInfos[2].customPlayerScoreSum)
XCTAssertEqual(teamInfos[3].team.id, 4)
XCTAssertEqual(teamInfos[3].team.name, "Oranges")
XCTAssertEqual(teamInfos[3].averageCustomScore, 0)
XCTAssertEqual(teamInfos[3].customCount, 1)
XCTAssertEqual(teamInfos[3].maxCustomScore, 0)
XCTAssertEqual(teamInfos[3].minCustomScore, 0)
XCTAssertEqual(teamInfos[3].customScoreSum, 0)
XCTAssertEqual(teamInfos[3].averageCustomPlayerScore, 0)
XCTAssertEqual(teamInfos[3].customPlayerCount, 1)
XCTAssertEqual(teamInfos[3].maxCustomPlayerScore, 0)
XCTAssertEqual(teamInfos[3].minCustomPlayerScore, 0)
XCTAssertEqual(teamInfos[3].customPlayerScoreSum, 0)
}
}
@@ -707,8 +707,8 @@ class AssociationAggregateTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in
let request = Team
.annotated(with: Team.players.filter(Column("score") < 500).forKey("lowPlayer").count)
.annotated(with: Team.players.filter(Column("score") >= 500).forKey("highPlayer").count)
.annotated(with: Team.players.filter(Column("score") < 500).forKey("lowPlayers").count)
.annotated(with: Team.players.filter(Column("score") >= 500).forKey("highPlayers").count)
.orderByPrimaryKey()
.asRequest(of: TeamInfo.self)
@@ -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, name: teamScope)
static let team = Player.belongsTo(Team.self, key: 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, name: "customTeam")
static let customTeam = belongsTo(Team.self, key: "customTeam")
var id: Int64
var teamId: Int64?
var name: String
@@ -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, name: "customB")
static let customD = belongsTo(D.self, name: "customD")
static let customB = belongsTo(B.self, key: "customB")
static let customD = belongsTo(D.self, key: "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, name: "customA")
static let customC = hasOne(C.self, name: "customC")
static let customA = hasOne(A.self, key: "customA")
static let customC = hasOne(C.self, key: "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, name: "customA")
static let customA = hasOne(A.self, key: "customA")
static let databaseTableName = "d"
var id: Int64
var name: String
@@ -109,49 +109,49 @@ class AssociationParallelSQLTests: GRDBTestCase {
func testParallelTwoIncludingIncludingOtherKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try assertEqualSQL(db, A.including(required: A.b).including(required: A.b.forKey("altb")), """
try assertEqualSQL(db, A.including(required: A.b).including(required: A.b.forKey("customB")), """
SELECT "a".*, "b1".*, "b2".* \
FROM "a" \
JOIN "b" "b1" ON ("b1"."id" = "a"."bid") \
JOIN "b" "b2" ON ("b2"."id" = "a"."bid")
""")
try assertEqualSQL(db, A.including(required: A.b).including(optional: A.b.forKey("altb")), """
try assertEqualSQL(db, A.including(required: A.b).including(optional: A.b.forKey("customB")), """
SELECT "a".*, "b1".*, "b2".* \
FROM "a" \
JOIN "b" "b1" ON ("b1"."id" = "a"."bid") \
LEFT JOIN "b" "b2" ON ("b2"."id" = "a"."bid")
""")
try assertEqualSQL(db, A.including(optional: A.b).including(required: A.b.forKey("altb")), """
try assertEqualSQL(db, A.including(optional: A.b).including(required: A.b.forKey("customB")), """
SELECT "a".*, "b1".*, "b2".* \
FROM "a" \
LEFT JOIN "b" "b1" ON ("b1"."id" = "a"."bid") \
JOIN "b" "b2" ON ("b2"."id" = "a"."bid")
""")
try assertEqualSQL(db, A.including(optional: A.b).including(optional: A.b.forKey("altb")), """
try assertEqualSQL(db, A.including(optional: A.b).including(optional: A.b.forKey("customB")), """
SELECT "a".*, "b1".*, "b2".* \
FROM "a" \
LEFT JOIN "b" "b1" ON ("b1"."id" = "a"."bid") \
LEFT JOIN "b" "b2" ON ("b2"."id" = "a"."bid")
""")
try assertEqualSQL(db, B.including(required: B.a).including(required: B.a.forKey("alta")), """
try assertEqualSQL(db, B.including(required: B.a).including(required: B.a.forKey("customA")), """
SELECT "b".*, "a1".*, "a2".* \
FROM "b" \
JOIN "a" "a1" ON ("a1"."bid" = "b"."id") \
JOIN "a" "a2" ON ("a2"."bid" = "b"."id")
""")
try assertEqualSQL(db, B.including(required: B.a).including(optional: B.a.forKey("alta")), """
try assertEqualSQL(db, B.including(required: B.a).including(optional: B.a.forKey("customA")), """
SELECT "b".*, "a1".*, "a2".* \
FROM "b" \
JOIN "a" "a1" ON ("a1"."bid" = "b"."id") \
LEFT JOIN "a" "a2" ON ("a2"."bid" = "b"."id")
""")
try assertEqualSQL(db, B.including(optional: B.a).including(required: B.a.forKey("alta")), """
try assertEqualSQL(db, B.including(optional: B.a).including(required: B.a.forKey("customA")), """
SELECT "b".*, "a1".*, "a2".* \
FROM "b" \
LEFT JOIN "a" "a1" ON ("a1"."bid" = "b"."id") \
JOIN "a" "a2" ON ("a2"."bid" = "b"."id")
""")
try assertEqualSQL(db, B.including(optional: B.a).including(optional: B.a.forKey("alta")), """
try assertEqualSQL(db, B.including(optional: B.a).including(optional: B.a.forKey("customA")), """
SELECT "b".*, "a1".*, "a2".* \
FROM "b" \
LEFT JOIN "a" "a1" ON ("a1"."bid" = "b"."id") \
@@ -9,7 +9,7 @@ private struct A: TableRecord, FetchableRecord, Decodable, Equatable {
var cola1: Int64
var cola2: String
}
private struct B: TableRecord, FetchableRecord, Decodable, Hashable {
private struct B: TableRecord, FetchableRecord, Decodable, Equatable, Hashable {
var colb1: Int64
var colb2: Int64?
var colb3: String
@@ -89,8 +89,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
let request = A
.including(all: A
.hasMany(B.self)
.orderByPrimaryKey()
.forKey("bs")) // TODO: auto-pluralization
.orderByPrimaryKey())
.orderByPrimaryKey()
// Array
@@ -244,10 +243,8 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
.hasMany(C.self)
.including(all: C
.hasMany(D.self)
.orderByPrimaryKey()
.forKey("ds")) // TODO: auto-pluralization
.orderByPrimaryKey()
.forKey("cs")) // TODO: auto-pluralization
.orderByPrimaryKey())
.orderByPrimaryKey())
.orderByPrimaryKey()
struct Record: FetchableRecord, Decodable, Equatable {
@@ -317,8 +314,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
.including(all: C
.hasMany(D.self)
.orderByPrimaryKey())
.orderByPrimaryKey()
.forKey("cs")) // TODO: auto-pluralization
.orderByPrimaryKey())
.orderByPrimaryKey()
struct Record: FetchableRecord, Decodable, Equatable {
@@ -478,8 +474,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
.including(required: C
.hasMany(D.self)
.orderByPrimaryKey())
.orderByPrimaryKey()
.forKey("cs")) // TODO: auto-pluralization
.orderByPrimaryKey())
.orderByPrimaryKey()
struct Record: FetchableRecord, Decodable, Equatable {
@@ -543,8 +538,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
.including(required: C
.hasMany(D.self)
.orderByPrimaryKey())
.orderByPrimaryKey()
.forKey("cs")) // TODO: auto-pluralization
.orderByPrimaryKey())
.orderByPrimaryKey()
struct Record: FetchableRecord, Decodable, Equatable {
@@ -592,12 +586,12 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
.hasMany(D.self)
.filter(Column("cold1") == 11)
.orderByPrimaryKey()
.forKey("d1"))
.forKey("ds1"))
.including(required: C
.hasMany(D.self)
.filter(Column("cold1") != 11)
.orderByPrimaryKey()
.forKey("d2"))
.forKey("ds2"))
.orderByPrimaryKey()
.forKey("cs1"))
.including(all: A
@@ -607,12 +601,12 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
.hasMany(D.self)
.filter(Column("cold1") == 11)
.orderByPrimaryKey()
.forKey("d1"))
.forKey("ds1"))
.including(required: C
.hasMany(D.self)
.filter(Column("cold1") != 11)
.orderByPrimaryKey()
.forKey("d2"))
.forKey("ds2"))
.orderByPrimaryKey()
.forKey("cs2"))
.orderByPrimaryKey()
@@ -687,8 +681,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
let request = A
.including(all: A
.hasMany(D.self, through: A.hasMany(C.self), using: C.hasMany(D.self))
.orderByPrimaryKey()
.forKey("ds")) // TODO: auto-pluralization
.orderByPrimaryKey())
.orderByPrimaryKey()
struct Record: FetchableRecord, Decodable, Equatable {
@@ -803,13 +796,12 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
try dbQueue.read { db in
// Plain request
do {
let cs = A.hasMany(C.self).forKey("cs")
let cs = A.hasMany(C.self)
let request = A
.including(all: cs.orderByPrimaryKey())
.including(all: A
.hasMany(D.self, through: cs, using: C.hasMany(D.self))
.orderByPrimaryKey()
.forKey("ds")) // TODO: auto-pluralization
.orderByPrimaryKey())
.orderByPrimaryKey()
struct Record: FetchableRecord, Decodable, Equatable {
@@ -959,8 +951,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
.belongsTo(A.self)
.including(all: A
.hasMany(C.self)
.orderByPrimaryKey()
.forKey("cs")) // TODO: auto-pluralization
.orderByPrimaryKey())
)
.orderByPrimaryKey()
@@ -75,8 +75,7 @@ class AssociationPrefetchingRowTests: GRDBTestCase {
let request = A
.including(all: A
.hasMany(B.self)
.orderByPrimaryKey()
.forKey("bs")) // TODO: auto-pluralization
.orderByPrimaryKey())
.orderByPrimaryKey()
// Row.fetchAll
@@ -201,10 +200,8 @@ class AssociationPrefetchingRowTests: GRDBTestCase {
.hasMany(C.self)
.including(all: C
.hasMany(D.self)
.orderByPrimaryKey()
.forKey("ds")) // TODO: auto-pluralization
.orderByPrimaryKey()
.forKey("cs")) // TODO: auto-pluralization
.orderByPrimaryKey())
.orderByPrimaryKey())
.orderByPrimaryKey()
// Row.fetchAll
@@ -267,8 +264,7 @@ class AssociationPrefetchingRowTests: GRDBTestCase {
.including(all: C
.hasMany(D.self)
.orderByPrimaryKey())
.orderByPrimaryKey()
.forKey("cs")) // TODO: auto-pluralization
.orderByPrimaryKey())
.orderByPrimaryKey()
// Row.fetchAll
@@ -415,8 +411,7 @@ class AssociationPrefetchingRowTests: GRDBTestCase {
.including(required: C
.hasMany(D.self)
.orderByPrimaryKey())
.orderByPrimaryKey()
.forKey("cs")) // TODO: auto-pluralization
.orderByPrimaryKey())
.orderByPrimaryKey()
// Row.fetchAll
@@ -477,8 +472,7 @@ class AssociationPrefetchingRowTests: GRDBTestCase {
.including(required: C
.hasMany(D.self)
.orderByPrimaryKey())
.orderByPrimaryKey()
.forKey("cs")) // TODO: auto-pluralization
.orderByPrimaryKey())
.orderByPrimaryKey()
// Row.fetchAll
@@ -526,12 +520,12 @@ class AssociationPrefetchingRowTests: GRDBTestCase {
.hasMany(D.self)
.filter(Column("cold1") == 11)
.orderByPrimaryKey()
.forKey("d1"))
.forKey("ds1"))
.including(required: C
.hasMany(D.self)
.filter(Column("cold1") != 11)
.orderByPrimaryKey()
.forKey("d2"))
.forKey("ds2"))
.orderByPrimaryKey()
.forKey("cs1"))
.including(all: A
@@ -541,12 +535,12 @@ class AssociationPrefetchingRowTests: GRDBTestCase {
.hasMany(D.self)
.filter(Column("cold1") == 11)
.orderByPrimaryKey()
.forKey("d1"))
.forKey("ds1"))
.including(required: C
.hasMany(D.self)
.filter(Column("cold1") != 11)
.orderByPrimaryKey()
.forKey("d2"))
.forKey("ds2"))
.orderByPrimaryKey()
.forKey("cs2"))
.orderByPrimaryKey()
@@ -615,8 +609,7 @@ class AssociationPrefetchingRowTests: GRDBTestCase {
let request = A
.including(all: A
.hasMany(D.self, through: A.hasMany(C.self), using: C.hasMany(D.self))
.orderByPrimaryKey()
.forKey("ds")) // TODO: auto-pluralization
.orderByPrimaryKey())
.orderByPrimaryKey()
// Row.fetchAll
@@ -730,13 +723,12 @@ class AssociationPrefetchingRowTests: GRDBTestCase {
try dbQueue.read { db in
// Plain request
do {
let cs = A.hasMany(C.self).forKey("cs")
let cs = A.hasMany(C.self)
let request = A
.including(all: cs.orderByPrimaryKey())
.including(all: A
.hasMany(D.self, through: cs, using: C.hasMany(D.self))
.orderByPrimaryKey()
.forKey("ds")) // TODO: auto-pluralization
.orderByPrimaryKey())
.orderByPrimaryKey()
// Row.fetchAll
@@ -877,8 +869,7 @@ class AssociationPrefetchingRowTests: GRDBTestCase {
.belongsTo(A.self)
.including(all: A
.hasMany(C.self)
.orderByPrimaryKey()
.forKey("cs")) // TODO: auto-pluralization
.orderByPrimaryKey())
)
.orderByPrimaryKey()
@@ -1085,10 +1076,10 @@ class AssociationPrefetchingRowTests: GRDBTestCase {
let request1 = A
.orderByPrimaryKey()
let request2 = A
.including(all: A.hasMany(B.self).orderByPrimaryKey().forKey("bs"))
.including(all: A.hasMany(B.self).orderByPrimaryKey())
.orderByPrimaryKey()
let request3 = A
.including(all: A.hasMany(B.self).none().forKey("bs"))
.including(all: A.hasMany(B.self).none())
.orderByPrimaryKey()
let row1 = try Row.fetchOne(db, request1)!
@@ -1134,10 +1125,10 @@ class AssociationPrefetchingRowTests: GRDBTestCase {
let request1 = A
.orderByPrimaryKey()
let request2 = A
.including(all: A.hasMany(B.self).orderByPrimaryKey().forKey("bs"))
.including(all: A.hasMany(B.self).orderByPrimaryKey())
.orderByPrimaryKey()
let request3 = A
.including(all: A.hasMany(B.self).none().forKey("bs"))
.including(all: A.hasMany(B.self).none())
.orderByPrimaryKey()
let row1 = try Row.fetchOne(db, request1)!.copy()
@@ -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, name: "b1", using: ForeignKey(["bid1"]))
static let b2 = belongsTo(B.self, name: "b2", using: ForeignKey(["bid2"]))
static let b1 = belongsTo(B.self, key: "b1", using: ForeignKey(["bid1"]))
static let b2 = belongsTo(B.self, key: "b2", using: ForeignKey(["bid2"]))
}
private struct B : TableRecord {
static let databaseTableName = "b"
static let a1 = hasOne(A.self, name: "a1", using: ForeignKey(["bid1"]))
static let a2 = hasOne(A.self, name: "a1", using: ForeignKey(["bid2"]))
static let a1 = hasOne(A.self, key: "a1", using: ForeignKey(["bid1"]))
static let a2 = hasOne(A.self, key: "a1", using: ForeignKey(["bid2"]))
}
/// Tests for table name conflicts, recursive associations,
+28
View File
@@ -88,6 +88,13 @@ class InflectionsTests: GRDBTestCase {
XCTAssertEqual(lastWord("PlayerScore1"), "Score1")
}
func testDigitlessRadical() {
XCTAssertEqual("".digitlessRadical, "")
XCTAssertEqual("player".digitlessRadical, "player")
XCTAssertEqual("player0".digitlessRadical, "player")
XCTAssertEqual("player123".digitlessRadical, "player")
}
func testPluralizePlurals() {
XCTAssertEqual("plurals".pluralized, "plurals")
XCTAssertEqual("Plurals".pluralized, "Plurals")
@@ -160,6 +167,10 @@ class InflectionsTests: GRDBTestCase {
let prefixedSingular = "prefixed" + singular.capitalized
let prefixedPlural = "prefixed" + plural.capitalized
XCTAssertEqual(prefixedSingular.pluralized, prefixedPlural)
let suffixedSingular = singular + "123"
let suffixedPlural = plural + "123"
XCTAssertEqual(suffixedSingular.pluralized, suffixedPlural)
}
}
@@ -171,6 +182,10 @@ class InflectionsTests: GRDBTestCase {
let prefixedSingular = "prefixed" + singular.capitalized
let prefixedPlural = "prefixed" + plural.capitalized
XCTAssertEqual(prefixedPlural.singularized, prefixedSingular)
let suffixedSingular = singular + "123"
let suffixedPlural = plural + "123"
XCTAssertEqual(suffixedPlural.singularized, suffixedSingular)
}
}
@@ -181,6 +196,9 @@ class InflectionsTests: GRDBTestCase {
let prefixedPlural = "prefixed" + plural.capitalized
XCTAssertEqual(prefixedPlural.pluralized, prefixedPlural)
let suffixedPlural = plural + "123"
XCTAssertEqual(suffixedPlural.pluralized, suffixedPlural)
}
}
@@ -191,6 +209,9 @@ class InflectionsTests: GRDBTestCase {
let prefixedSingular = "prefixed" + singular.capitalized
XCTAssertEqual(prefixedSingular.singularized, prefixedSingular)
let suffixedSingular = singular + "123"
XCTAssertEqual(suffixedSingular.singularized, suffixedSingular)
}
}
@@ -208,6 +229,13 @@ class InflectionsTests: GRDBTestCase {
XCTAssertEqual(prefixedSingular.pluralized, prefixedPlural)
XCTAssertEqual(prefixedSingular.singularized, prefixedSingular)
XCTAssertEqual(prefixedPlural.pluralized, prefixedPlural)
let suffixedSingular = singular + "123"
let suffixedPlural = plural + "123"
XCTAssertEqual(suffixedPlural.singularized, suffixedSingular)
XCTAssertEqual(suffixedSingular.pluralized, suffixedPlural)
XCTAssertEqual(suffixedSingular.singularized, suffixedSingular)
XCTAssertEqual(suffixedPlural.pluralized, suffixedPlural)
}
}
}