mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-27 04:14:21 +00:00
Merge pull request #521 from groue/feature/join-condition-cleanup
Associations: join condition cleanup
This commit is contained in:
11 files changed
+264
-210
No files matched your search
@@ -279,12 +279,6 @@ extension DatabaseValue {
|
||||
public func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
|
||||
return self
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression {
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
// CustomStringConvertible
|
||||
@@ -305,3 +299,45 @@ extension DatabaseValue {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Compares DatabaseValue like SQLite.
|
||||
///
|
||||
/// See RxGRDB for tests.
|
||||
///
|
||||
/// This comparison is not public because it does not handle text collations,
|
||||
/// and may be dangerous when put in user hands.
|
||||
///
|
||||
/// So far, the only goal of this sorting method so far is aesthetic, and
|
||||
/// easier testing.
|
||||
func < (lhs: DatabaseValue, rhs: DatabaseValue) -> Bool {
|
||||
switch (lhs.storage, rhs.storage) {
|
||||
case (.int64(let lhs), .int64(let rhs)):
|
||||
return lhs < rhs
|
||||
case (.double(let lhs), .double(let rhs)):
|
||||
return lhs < rhs
|
||||
case (.int64(let lhs), .double(let rhs)):
|
||||
return Double(lhs) < rhs
|
||||
case (.double(let lhs), .int64(let rhs)):
|
||||
return lhs < Double(rhs)
|
||||
case (.string(let lhs), .string(let rhs)):
|
||||
return lhs.utf8.lexicographicallyPrecedes(rhs.utf8)
|
||||
case (.blob(let lhs), .blob(let rhs)):
|
||||
return lhs.lexicographicallyPrecedes(rhs, by: <)
|
||||
case (.blob, _):
|
||||
return false
|
||||
case (_, .blob):
|
||||
return true
|
||||
case (.string, _):
|
||||
return false
|
||||
case (_, .string):
|
||||
return true
|
||||
case (.int64, _), (.double, _):
|
||||
return false
|
||||
case (_, .int64), (_, .double):
|
||||
return true
|
||||
case (.null, _):
|
||||
return false
|
||||
case (_, .null):
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -246,28 +246,36 @@ extension Association {
|
||||
/// associated record are selected. The returned association does not
|
||||
/// require that the associated database table contains a matching row.
|
||||
public func including<A: Association>(optional association: A) -> Self where A.OriginRowDecoder == RowDecoder {
|
||||
return mapRelation { association.sqlAssociation.relation(from: $0, required: false) }
|
||||
return mapRelation {
|
||||
association.sqlAssociation.relation(from: $0, required: false)
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates an association that includes another one. The columns of the
|
||||
/// associated record are selected. The returned association requires
|
||||
/// that the associated database table contains a matching row.
|
||||
public func including<A: Association>(required association: A) -> Self where A.OriginRowDecoder == RowDecoder {
|
||||
return mapRelation { association.sqlAssociation.relation(from: $0, required: true) }
|
||||
return mapRelation {
|
||||
association.sqlAssociation.relation(from: $0, required: true)
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates an association that joins another one. The columns of the
|
||||
/// associated record are not selected. The returned association does not
|
||||
/// require that the associated database table contains a matching row.
|
||||
public func joining<A: Association>(optional association: A) -> Self where A.OriginRowDecoder == RowDecoder {
|
||||
return mapRelation { association.select([]).sqlAssociation.relation(from: $0, required: false) }
|
||||
return mapRelation {
|
||||
association.select([]).sqlAssociation.relation(from: $0, required: false)
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates an association that joins another one. The columns of the
|
||||
/// associated record are not selected. The returned association requires
|
||||
/// that the associated database table contains a matching row.
|
||||
public func joining<A: Association>(required association: A) -> Self where A.OriginRowDecoder == RowDecoder {
|
||||
return mapRelation { association.select([]).sqlAssociation.relation(from: $0, required: true) }
|
||||
return mapRelation {
|
||||
association.select([]).sqlAssociation.relation(from: $0, required: true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -402,7 +410,7 @@ public /* TODO: internal */ struct SQLAssociation {
|
||||
// SQLAssociation is a non-empty array of association elements
|
||||
private struct Element {
|
||||
var key: String
|
||||
var condition: SQLJoin.Condition
|
||||
var condition: SQLJoinCondition
|
||||
var relation: SQLRelation
|
||||
}
|
||||
private var head: Element
|
||||
@@ -415,7 +423,7 @@ public /* TODO: internal */ struct SQLAssociation {
|
||||
self.tail = tail
|
||||
}
|
||||
|
||||
init(key: String, condition: SQLJoin.Condition, relation: SQLRelation) {
|
||||
init(key: String, condition: SQLJoinCondition, relation: SQLRelation) {
|
||||
head = Element(key: key, condition: condition, relation: relation)
|
||||
tail = []
|
||||
}
|
||||
@@ -480,26 +488,26 @@ public /* TODO: internal */ struct SQLAssociation {
|
||||
///
|
||||
/// // SELECT head.* FROM head WHERE head.originId = 123
|
||||
/// origin.request(for: association)
|
||||
func relation(to originTable: String, container originContainer: @escaping (Database) throws -> PersistenceContainer) -> SQLRelation {
|
||||
// Build a "pivot" relation whose filter is the pivot condition
|
||||
// injected with values contained in originContainer.
|
||||
func pivotRelation(from originAlias: TableAlias, rows originRows: @escaping (Database) throws -> [Row]) -> SQLRelation {
|
||||
let pivotCondition = pivot.condition
|
||||
let pivotAlias = TableAlias()
|
||||
let pivotRelation = pivot.relation
|
||||
.qualified(with: pivotAlias)
|
||||
.filter { db in
|
||||
let originAlias = TableAlias(tableName: originTable)
|
||||
// Build a join expression: `association.originId = origin.id`
|
||||
let joinExpression = try pivotCondition.joinExpression(db, leftAlias: originAlias, rightAlias: pivotAlias)
|
||||
|
||||
// Build a join condition: `association.originId = origin.id`
|
||||
let joinExpression = try pivotCondition.sqlExpression(db, leftAlias: originAlias, rightAlias: pivotAlias)
|
||||
|
||||
// Replace `origin.id` with 123
|
||||
return try joinExpression.resolvedExpression(inContext: [originAlias: originContainer(db)])
|
||||
// Resolve to `association.originId = 123` or `association.originId IN (1, 2, 3)`
|
||||
return try joinExpression.resolved(withLeftRows: originRows(db))
|
||||
}
|
||||
|
||||
// We use elements backward: join conditions have to be reversed.
|
||||
// We join elements backward: join conditions have to be reversed.
|
||||
let reversedElements = zip([head] + tail, tail)
|
||||
.map { Element(key: $1.key, condition: $0.condition.reversed, relation: $1.relation.select([])) }
|
||||
.map { (element, nextElement) in
|
||||
Element(
|
||||
key: nextElement.key,
|
||||
condition: element.condition.reversed,
|
||||
relation: nextElement.relation.select([])) }
|
||||
.reversed()
|
||||
|
||||
// Empty tail?
|
||||
|
||||
@@ -146,7 +146,7 @@ extension TableRecord {
|
||||
destinationTable: Destination.databaseTableName,
|
||||
foreignKey: foreignKey)
|
||||
|
||||
let condition = SQLJoin.Condition(
|
||||
let condition = SQLJoinCondition(
|
||||
foreignKeyRequest: foreignKeyRequest,
|
||||
originIsLeft: true)
|
||||
|
||||
|
||||
@@ -146,7 +146,7 @@ extension TableRecord {
|
||||
destinationTable: databaseTableName,
|
||||
foreignKey: foreignKey)
|
||||
|
||||
let condition = SQLJoin.Condition(
|
||||
let condition = SQLJoinCondition(
|
||||
foreignKeyRequest: foreignKeyRequest,
|
||||
originIsLeft: false)
|
||||
|
||||
|
||||
@@ -148,7 +148,7 @@ extension TableRecord {
|
||||
destinationTable: databaseTableName,
|
||||
foreignKey: foreignKey)
|
||||
|
||||
let condition = SQLJoin.Condition(
|
||||
let condition = SQLJoinCondition(
|
||||
foreignKeyRequest: foreignKeyRequest,
|
||||
originIsLeft: false)
|
||||
|
||||
|
||||
@@ -36,12 +36,6 @@ extension ColumnExpression {
|
||||
public func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
|
||||
return QualifiedColumn(name, alias: alias)
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression {
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
/// A column in a database table.
|
||||
@@ -85,16 +79,6 @@ struct QualifiedColumn: ColumnExpression {
|
||||
// Never requalify
|
||||
return self
|
||||
}
|
||||
|
||||
func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression {
|
||||
guard
|
||||
let container = context[alias],
|
||||
let value = container.value(forCaseInsensitiveColumn: name) else
|
||||
{
|
||||
return self
|
||||
}
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
/// Support for column enums:
|
||||
|
||||
@@ -107,10 +107,12 @@ extension TableRecord where Self: EncodableRecord {
|
||||
/// let team: Team = ...
|
||||
/// let players = try team.players.fetchAll(db) // [Player]
|
||||
public func request<A: Association>(for association: A) -> QueryInterfaceRequest<A.RowDecoder> where A.OriginRowDecoder == Self {
|
||||
let relation = association.sqlAssociation.relation(
|
||||
to: type(of: self).databaseTableName,
|
||||
container: { try PersistenceContainer($0, self) })
|
||||
return QueryInterfaceRequest<A.RowDecoder>(query: SQLSelectQuery(relation: relation))
|
||||
let originAlias = TableAlias(tableName: type(of: self).databaseTableName)
|
||||
let pivotRelation = association.sqlAssociation.pivotRelation(
|
||||
from: originAlias,
|
||||
rows: { db in try [Row(PersistenceContainer(db, self))] })
|
||||
let query = SQLSelectQuery(relation: pivotRelation)
|
||||
return QueryInterfaceRequest<A.RowDecoder>(query: query)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -89,12 +89,6 @@ public struct SQLExpressionLiteral : SQLExpression {
|
||||
public func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
|
||||
return self
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression {
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressionUnary
|
||||
@@ -166,12 +160,6 @@ public struct SQLExpressionUnary : SQLExpression {
|
||||
public func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
|
||||
return SQLExpressionUnary(op, expression.qualifiedExpression(with: alias))
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression {
|
||||
return SQLExpressionUnary(op, expression.resolvedExpression(inContext: context))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressionBinary
|
||||
@@ -275,12 +263,6 @@ public struct SQLExpressionBinary : SQLExpression {
|
||||
public func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
|
||||
return SQLExpressionBinary(op, lhs.qualifiedExpression(with: alias), rhs.qualifiedExpression(with: alias))
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression {
|
||||
return SQLExpressionBinary(op, lhs.resolvedExpression(inContext: context), rhs.resolvedExpression(inContext: context))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressionAnd
|
||||
@@ -308,10 +290,6 @@ struct SQLExpressionAnd : SQLExpression {
|
||||
return SQLExpressionAnd(expressions.map { $0.qualifiedExpression(with: alias) })
|
||||
}
|
||||
|
||||
func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression {
|
||||
return SQLExpressionAnd(expressions.map { $0.resolvedExpression(inContext: context) })
|
||||
}
|
||||
|
||||
func matchedRowIds(rowIdName: String?) -> Set<Int64>? {
|
||||
let matchedRowIds = expressions.compactMap {
|
||||
$0.matchedRowIds(rowIdName: rowIdName)
|
||||
@@ -348,10 +326,6 @@ struct SQLExpressionOr : SQLExpression {
|
||||
return SQLExpressionOr(expressions.map { $0.qualifiedExpression(with: alias) })
|
||||
}
|
||||
|
||||
func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression {
|
||||
return SQLExpressionOr(expressions.map { $0.resolvedExpression(inContext: context) })
|
||||
}
|
||||
|
||||
func matchedRowIds(rowIdName: String?) -> Set<Int64>? {
|
||||
if expressions.isEmpty {
|
||||
return []
|
||||
@@ -414,10 +388,6 @@ struct SQLExpressionEqual: SQLExpression {
|
||||
return SQLExpressionEqual(op, lhs.qualifiedExpression(with: alias), rhs.qualifiedExpression(with: alias))
|
||||
}
|
||||
|
||||
func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression {
|
||||
return SQLExpressionEqual(op, lhs.resolvedExpression(inContext: context), rhs.resolvedExpression(inContext: context))
|
||||
}
|
||||
|
||||
func matchedRowIds(rowIdName: String?) -> Set<Int64>? {
|
||||
// FIXME: this implementation ignores column aliases
|
||||
switch op {
|
||||
@@ -486,10 +456,6 @@ struct SQLExpressionContains : SQLExpression {
|
||||
return SQLExpressionContains(expression.qualifiedExpression(with: alias), collection, negated: isNegated)
|
||||
}
|
||||
|
||||
func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression {
|
||||
return SQLExpressionContains(expression.resolvedExpression(inContext: context), collection, negated: isNegated)
|
||||
}
|
||||
|
||||
func matchedRowIds(rowIdName: String?) -> Set<Int64>? {
|
||||
// FIXME: this implementation ignores column aliases
|
||||
// Look for `id IN (1, 2, 3)`
|
||||
@@ -560,14 +526,6 @@ struct SQLExpressionBetween : SQLExpression {
|
||||
upperBound.qualifiedExpression(with: alias),
|
||||
negated: isNegated)
|
||||
}
|
||||
|
||||
func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression {
|
||||
return SQLExpressionBetween(
|
||||
expression.resolvedExpression(inContext: context),
|
||||
lowerBound.resolvedExpression(inContext: context),
|
||||
upperBound.resolvedExpression(inContext: context),
|
||||
negated: isNegated)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressionFunction
|
||||
@@ -646,12 +604,6 @@ public struct SQLExpressionFunction : SQLExpression {
|
||||
public func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
|
||||
return SQLExpressionFunction(functionName, arguments: arguments.map { $0.qualifiedExpression(with: alias) })
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression {
|
||||
return SQLExpressionFunction(functionName, arguments: arguments.map { $0.resolvedExpression(inContext: context) })
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressionCount
|
||||
@@ -675,10 +627,6 @@ struct SQLExpressionCount : SQLExpression {
|
||||
func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
|
||||
return SQLExpressionCount(counted.qualifiedSelectable(with: alias))
|
||||
}
|
||||
|
||||
func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression {
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressionCountDistinct
|
||||
@@ -701,10 +649,6 @@ struct SQLExpressionCountDistinct : SQLExpression {
|
||||
func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
|
||||
return SQLExpressionCountDistinct(counted.qualifiedExpression(with: alias))
|
||||
}
|
||||
|
||||
func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression {
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressionIsEmpty
|
||||
@@ -737,10 +681,6 @@ struct SQLExpressionIsEmpty : SQLExpression {
|
||||
func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
|
||||
return SQLExpressionIsEmpty(countExpression.qualifiedExpression(with: alias), isEmpty: isEmpty)
|
||||
}
|
||||
|
||||
func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression {
|
||||
return SQLExpressionIsEmpty(countExpression.resolvedExpression(inContext: context), isEmpty: isEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - TableMatchExpression
|
||||
@@ -758,12 +698,6 @@ struct TableMatchExpression: SQLExpression {
|
||||
alias: self.alias,
|
||||
pattern: pattern.qualifiedExpression(with: alias))
|
||||
}
|
||||
|
||||
func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression {
|
||||
return TableMatchExpression(
|
||||
alias: alias,
|
||||
pattern: pattern.resolvedExpression(inContext: context))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressionCollate
|
||||
@@ -793,8 +727,4 @@ struct SQLExpressionCollate : SQLExpression {
|
||||
func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
|
||||
return SQLExpressionCollate(expression.qualifiedExpression(with: alias), collationName: collationName)
|
||||
}
|
||||
|
||||
func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression {
|
||||
return SQLExpressionCollate(expression.resolvedExpression(inContext: context), collationName: collationName)
|
||||
}
|
||||
}
|
||||
@@ -48,9 +48,6 @@ public protocol SQLExpression : SQLSpecificExpressible, SQLSelectable, SQLOrderi
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
func qualifiedExpression(with alias: TableAlias) -> SQLExpression
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression
|
||||
}
|
||||
|
||||
extension SQLExpression {
|
||||
@@ -147,8 +144,4 @@ struct SQLExpressionNot : SQLExpression {
|
||||
func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
|
||||
return SQLExpressionNot(expression.qualifiedExpression(with: alias))
|
||||
}
|
||||
|
||||
func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression {
|
||||
return SQLExpressionNot(expression.resolvedExpression(inContext: context))
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,14 @@
|
||||
/// A "relation" as defined by the [relational terminology](https://en.wikipedia.org/wiki/Relational_database#Terminology):
|
||||
///
|
||||
/// > A set of tuples sharing the same attributes; a set of columns and rows.
|
||||
///
|
||||
/// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ...
|
||||
/// | | | | |
|
||||
/// | | | | • ordering
|
||||
/// | | | • filterPromise
|
||||
/// | | • joins
|
||||
/// | • source
|
||||
/// • selection
|
||||
struct SQLRelation {
|
||||
var source: SQLSource
|
||||
var selection: [SQLSelectable]
|
||||
@@ -198,89 +206,167 @@ extension SQLRelation {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLJoinCondition
|
||||
|
||||
/// The condition that links two joined tables.
|
||||
///
|
||||
/// Currently, we only support one kind of join condition: foreign keys.
|
||||
///
|
||||
/// SELECT ... FROM book JOIN author ON author.id = book.authorId
|
||||
/// <- the join condition -->
|
||||
///
|
||||
/// When we eventually add support for new ways to join tables, SQLJoinCondition
|
||||
/// is the type we'll need to update.
|
||||
///
|
||||
/// SQLJoinCondition equality allows merging of associations:
|
||||
///
|
||||
/// // request1 and request2 are equivalent
|
||||
/// let request1 = Book
|
||||
/// .including(required: Book.author)
|
||||
/// let request2 = Book
|
||||
/// .including(required: Book.author)
|
||||
/// .including(required: Book.author)
|
||||
///
|
||||
/// // request3 and request4 are equivalent
|
||||
/// let request3 = Book
|
||||
/// .including(required: Book.author.filter(condition1 && condition2))
|
||||
/// let request4 = Book
|
||||
/// .joining(required: Book.author.filter(condition1))
|
||||
/// .including(optional: Book.author.filter(condition2))
|
||||
struct SQLJoinCondition: Equatable {
|
||||
/// Definition of a foreign key
|
||||
var foreignKeyRequest: ForeignKeyRequest
|
||||
|
||||
/// True if the table at the origin of the foreign key is on the left of
|
||||
/// the sql JOIN operator.
|
||||
///
|
||||
/// Let's consider the `book.authorId -> author.id` foreign key.
|
||||
/// Its origin table is `book`.
|
||||
///
|
||||
/// The origin table `book` is on the left of the JOIN operator for
|
||||
/// the BelongsTo association:
|
||||
///
|
||||
/// -- Book.including(required: Book.author)
|
||||
/// SELECT ... FROM book JOIN author ON author.id = book.authorId
|
||||
///
|
||||
/// The origin table `book`is on the right of the JOIN operator for
|
||||
/// the HasMany and HasOne associations:
|
||||
///
|
||||
/// -- Author.including(required: Author.books)
|
||||
/// SELECT ... FROM author JOIN book ON author.id = book.authorId
|
||||
var originIsLeft: Bool
|
||||
|
||||
var reversed: SQLJoinCondition {
|
||||
return SQLJoinCondition(foreignKeyRequest: foreignKeyRequest, originIsLeft: !originIsLeft)
|
||||
}
|
||||
|
||||
/// Returns an SQL expression for the join condition.
|
||||
///
|
||||
/// SELECT * FROM left JOIN right ON (right.a = left.b)
|
||||
/// <---------------->
|
||||
/// SQLJoinExpression
|
||||
///
|
||||
/// - 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 SQL expression.
|
||||
func joinExpression(_ db: Database, leftAlias: TableAlias, rightAlias: TableAlias) throws -> SQLJoinExpression {
|
||||
let foreignKeyMapping = try foreignKeyRequest.fetchMapping(db)
|
||||
let columnMapping: [(left: String, right: String)]
|
||||
if originIsLeft {
|
||||
columnMapping = foreignKeyMapping.map { (left: $0.origin, right: $0.destination) }
|
||||
} else {
|
||||
columnMapping = foreignKeyMapping.map { (left: $0.destination, right: $0.origin) }
|
||||
}
|
||||
return SQLJoinExpression(leftAlias: leftAlias, rightAlias: rightAlias, columnMapping: columnMapping)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLJoinExpression
|
||||
|
||||
/// The expression used to join two tables:
|
||||
///
|
||||
/// SELECT * FROM left JOIN right ON (right.a = left.b)
|
||||
/// <---------------->
|
||||
/// SQLJoinExpression
|
||||
///
|
||||
/// SQLJoinExpression can be resolved against rows, in order to give
|
||||
/// `right.a = 1` or `right.a IN (1, 2, 3)`.
|
||||
struct SQLJoinExpression: SQLExpression {
|
||||
var leftAlias: TableAlias
|
||||
var rightAlias: TableAlias
|
||||
var columnMapping: [(left: String, right: String)]
|
||||
|
||||
func expressionSQL(_ context: inout SQLGenerationContext) -> String {
|
||||
return columnMapping
|
||||
.map { QualifiedColumn($0.right, alias: rightAlias) == QualifiedColumn($0.left, alias: leftAlias) }
|
||||
.joined(operator: .and)
|
||||
.expressionSQL(&context)
|
||||
}
|
||||
|
||||
func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
|
||||
// self is already qualified
|
||||
return self
|
||||
}
|
||||
|
||||
/// Resolves against given rows.
|
||||
///
|
||||
/// Given `right.a = left.b`, returns `right.a = 1` or
|
||||
/// `right.a IN (1, 2, 3)`.
|
||||
func resolved(withLeftRows rows: [Row]) -> SQLExpression {
|
||||
let valueMappings = columnMapping.map { columns in
|
||||
(column: QualifiedColumn(columns.right, alias: rightAlias),
|
||||
dbValues: rows.map { $0[columns.left] as DatabaseValue })
|
||||
}
|
||||
|
||||
guard let firstValueMapping = valueMappings.first else {
|
||||
// Likely a GRDB bug
|
||||
fatalError("No joining column")
|
||||
}
|
||||
|
||||
if valueMappings.count == 1 {
|
||||
// Join on a single column.
|
||||
// Unique and sort database values for nicer output:
|
||||
let dbValues = firstValueMapping.dbValues
|
||||
.reduce(into: Set<DatabaseValue>(), { $0.insert($1) })
|
||||
.sorted(by: <)
|
||||
|
||||
guard let dbValue = dbValues.first else {
|
||||
// Likely a GRDB bug
|
||||
fatalError("No resolving rows")
|
||||
}
|
||||
|
||||
if dbValues.count == 1 {
|
||||
// Single row: table.a = 1
|
||||
return (firstValueMapping.column == dbValue)
|
||||
} else {
|
||||
// Multiple rows: table.a IN (1, 2, 3)
|
||||
return dbValues.contains(firstValueMapping.column)
|
||||
}
|
||||
} else {
|
||||
// Join on a multiple columns.
|
||||
assert(Set(valueMappings.map { $0.dbValues.count }).count == 1, "inconsistent values count")
|
||||
if firstValueMapping.dbValues.count == 1 {
|
||||
// Single row: (table.a = 1) AND (table.b = 2)
|
||||
return valueMappings
|
||||
.map { $0.column == $0.dbValues[0] }
|
||||
.joined(operator: .and)
|
||||
|
||||
} else {
|
||||
// Multiple rows: TODO
|
||||
fatalError("not implemented")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLJoin
|
||||
|
||||
struct SQLJoin {
|
||||
/// The condition that links two joined tables.
|
||||
///
|
||||
/// Currently, we only support one kind of join condition: foreign keys.
|
||||
///
|
||||
/// SELECT ... FROM book JOIN author ON author.id = book.authorId
|
||||
/// <- the join condition -->
|
||||
///
|
||||
/// When we eventually add support for new ways to join tables, Condition
|
||||
/// is the type we'll need to update.
|
||||
///
|
||||
/// Condition equality allows merging of associations:
|
||||
///
|
||||
/// // request1 and request2 are equivalent
|
||||
/// let request1 = Book
|
||||
/// .including(required: Book.author)
|
||||
/// let request2 = Book
|
||||
/// .including(required: Book.author)
|
||||
/// .including(required: Book.author)
|
||||
///
|
||||
/// // request3 and request4 are equivalent
|
||||
/// let request3 = Book
|
||||
/// .including(required: Book.author.filter(condition1 && condition2))
|
||||
/// let request4 = Book
|
||||
/// .joining(required: Book.author.filter(condition1))
|
||||
/// .including(optional: Book.author.filter(condition2))
|
||||
struct Condition: Equatable {
|
||||
/// Definition of a foreign key
|
||||
var foreignKeyRequest: ForeignKeyRequest
|
||||
|
||||
/// True if the table at the origin of the foreign key is on the left of
|
||||
/// the sql JOIN operator.
|
||||
///
|
||||
/// Let's consider the `book.authorId -> author.id` foreign key.
|
||||
/// Its origin table is `book`.
|
||||
///
|
||||
/// The origin table `book` is on the left of the JOIN operator for
|
||||
/// the BelongsTo association:
|
||||
///
|
||||
/// -- Book.including(required: Book.author)
|
||||
/// SELECT ... FROM book JOIN author ON author.id = book.authorId
|
||||
///
|
||||
/// The origin table `book`is on the right of the JOIN operator for
|
||||
/// the HasMany and HasOne associations:
|
||||
///
|
||||
/// -- Author.including(required: Author.books)
|
||||
/// SELECT ... FROM author JOIN book ON author.id = book.authorId
|
||||
var originIsLeft: Bool
|
||||
|
||||
var reversed: Condition {
|
||||
return Condition(foreignKeyRequest: foreignKeyRequest, originIsLeft: !originIsLeft)
|
||||
}
|
||||
|
||||
/// Returns an SQL expression for the join condition.
|
||||
///
|
||||
/// SELECT ... FROM book JOIN author ON author.id = book.authorId
|
||||
/// <- the SQL expression -->
|
||||
///
|
||||
/// - 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 SQL expression.
|
||||
func sqlExpression(_ db: Database, leftAlias: TableAlias, rightAlias: TableAlias) throws -> SQLExpression {
|
||||
let foreignKeyMapping = try foreignKeyRequest.fetchMapping(db)
|
||||
let columnMapping: [(left: Column, right: Column)]
|
||||
if originIsLeft {
|
||||
columnMapping = foreignKeyMapping.map { (left: Column($0.origin), right: Column($0.destination)) }
|
||||
} else {
|
||||
columnMapping = foreignKeyMapping.map { (left: Column($0.destination), right: Column($0.origin)) }
|
||||
}
|
||||
|
||||
return columnMapping
|
||||
.map { $0.right.qualifiedExpression(with: rightAlias) == $0.left.qualifiedExpression(with: leftAlias) }
|
||||
.joined(operator: .and)
|
||||
}
|
||||
}
|
||||
|
||||
var isRequired: Bool
|
||||
var condition: Condition
|
||||
var condition: SQLJoinCondition
|
||||
var relation: SQLRelation
|
||||
}
|
||||
|
||||
|
||||
@@ -215,11 +215,21 @@ struct SQLSelectQueryGenerator {
|
||||
}
|
||||
|
||||
/// A "qualified" relation, where all tables are identified with a table alias.
|
||||
///
|
||||
/// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ...
|
||||
/// | | | | | |
|
||||
/// | | | | | • ordering
|
||||
/// | | | | • filterPromise
|
||||
/// | | | • directJoins
|
||||
/// | | • alias
|
||||
/// | • source
|
||||
/// • fullSelection
|
||||
private struct SQLQualifiedRelation {
|
||||
/// The alias for the relation
|
||||
///
|
||||
/// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ...
|
||||
/// ^ alias
|
||||
/// |
|
||||
/// • alias
|
||||
let alias: TableAlias
|
||||
|
||||
/// All aliases, including aliases of joined relations
|
||||
@@ -235,7 +245,8 @@ private struct SQLQualifiedRelation {
|
||||
/// The source
|
||||
///
|
||||
/// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ...
|
||||
/// ^ source
|
||||
/// |
|
||||
/// • source
|
||||
let source: SQLQualifiedSource
|
||||
|
||||
/// The selection, not including selection of joined relations
|
||||
@@ -244,7 +255,8 @@ private struct SQLQualifiedRelation {
|
||||
/// The full selection, including selection of joined relations
|
||||
///
|
||||
/// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ...
|
||||
/// ^ fullSelection
|
||||
/// |
|
||||
/// • fullSelection
|
||||
var selection: [SQLSelectable] {
|
||||
return joins.reduce(into: ownSelection) {
|
||||
$0.append(contentsOf: $1.value.relation.selection)
|
||||
@@ -254,7 +266,8 @@ private struct SQLQualifiedRelation {
|
||||
/// The filtering clause
|
||||
///
|
||||
/// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ...
|
||||
/// ^ filterPromise
|
||||
/// |
|
||||
/// • filterPromise
|
||||
let filterPromise: DatabasePromise<SQLExpression?>
|
||||
|
||||
/// The ordering, not including ordering of joined relations
|
||||
@@ -263,7 +276,8 @@ private struct SQLQualifiedRelation {
|
||||
/// The full ordering, including orderings of joined relations
|
||||
///
|
||||
/// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ...
|
||||
/// ^ ordering
|
||||
/// |
|
||||
/// • ordering
|
||||
var ordering: SQLRelation.Ordering {
|
||||
return joins.reduce(ownOrdering) {
|
||||
$0.appending($1.value.relation.ordering)
|
||||
@@ -273,7 +287,8 @@ private struct SQLQualifiedRelation {
|
||||
/// The joins
|
||||
///
|
||||
/// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ...
|
||||
/// ^ joins
|
||||
/// |
|
||||
/// • joins
|
||||
let joins: OrderedDictionary<String, SQLQualifiedJoin>
|
||||
|
||||
init(_ relation: SQLRelation) {
|
||||
@@ -405,7 +420,7 @@ private enum SQLQualifiedSource {
|
||||
/// A "qualified" join, where all tables are identified with a table alias.
|
||||
private struct SQLQualifiedJoin {
|
||||
private let isRequired: Bool
|
||||
private let condition: SQLJoin.Condition
|
||||
private let condition: SQLJoinCondition
|
||||
let relation: SQLQualifiedRelation
|
||||
|
||||
init(_ join: SQLJoin) {
|
||||
@@ -433,7 +448,7 @@ private struct SQLQualifiedJoin {
|
||||
|
||||
let rightAlias = relation.alias
|
||||
let filters = try [
|
||||
condition.sqlExpression(db, leftAlias: leftAlias, rightAlias: rightAlias),
|
||||
condition.joinExpression(db, leftAlias: leftAlias, rightAlias: rightAlias),
|
||||
relation.filterPromise.resolve(db)
|
||||
].compactMap { $0 }
|
||||
if !filters.isEmpty {
|
||||
|
||||
Reference in new issue
Block a user