TableAlias is generic

This commit is contained in:
Gwendal Roué committed 2025-05-10 14:52:48 +02:00
1 parent 55edcff97f
commit 6cc3116ff4
21 files changed
+333 -119

No files matched your search

+2 -2
View File
@@ -118,7 +118,7 @@ public struct SQL: Sendable {
}
}
fileprivate func qualified(with alias: TableAlias) -> Element {
fileprivate func qualified(with alias: TableAliasBase) -> Element {
switch self {
case .sql:
// A raw SQL string can't be qualified with a table alias,
@@ -192,7 +192,7 @@ public struct SQL: Sendable {
try elements.map { try $0.sql(context) }.joined()
}
func qualified(with alias: TableAlias) -> SQL {
func qualified(with alias: TableAliasBase) -> SQL {
SQL(elements: elements.map { $0.qualified(with: alias) })
}
}
@@ -21,7 +21,7 @@ extension TableRequest where Self: FilteredRequest {
}
let alias = TableAlias()
let matchExpression = SQLExpression.tableMatch(alias, pattern.sqlExpression)
return self.aliased(alias).filter(matchExpression)
return self._aliased(alias).filter(matchExpression)
}
}
@@ -22,7 +22,7 @@ extension TableRequest where Self: FilteredRequest {
}
let alias = TableAlias()
let matchExpression = SQLExpression.tableMatch(alias, pattern.sqlExpression)
return self.aliased(alias).filter(matchExpression)
return self._aliased(alias).filter(matchExpression)
}
}
@@ -164,7 +164,7 @@ extension Association {
// TableRequest conformance
extension Association {
public func aliased(_ alias: TableAlias) -> Self {
public func _aliased(_ alias: TableAliasBase) -> Self {
withDestinationRelation { relation in
relation = relation.aliased(alias)
}
@@ -385,12 +385,18 @@ extension CommonTableExpression {
/// - returns: An association to the common table expression.
public func association<Destination>(
to cte: CommonTableExpression<Destination>,
on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
on condition: @escaping @Sendable (
_ left: TableAlias<RowDecoder>,
_ right: TableAlias<Destination>
) -> any SQLExpressible
)
-> JoinAssociation<RowDecoder, Destination>
{
JoinAssociation(
to: cte.relationForAll,
condition: .expression { condition($0, $1).sqlExpression })
condition: .expression { left, right in
condition(TableAlias(root: left), TableAlias(root: right)).sqlExpression
})
}
/// Creates an association to a common table expression that you can join
@@ -421,13 +427,18 @@ extension CommonTableExpression {
/// - returns: An association to the common table expression.
public func association<Destination>(
to destination: Destination.Type,
on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
on condition: @escaping @Sendable (
_ left: TableAlias<RowDecoder>,
_ right: TableAlias<Destination>
) -> any SQLExpressible)
-> JoinAssociation<RowDecoder, Destination>
where Destination: TableRecord
{
JoinAssociation(
to: Destination.relationForAll,
condition: .expression { condition($0, $1).sqlExpression })
condition: .expression { left, right in
condition(TableAlias(root: left), TableAlias(root: right)).sqlExpression
})
}
/// Creates an association to a table record that you can join
@@ -458,12 +469,17 @@ extension CommonTableExpression {
/// - returns: An association to the common table expression.
public func association<Destination>(
to destination: Table<Destination>,
on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
on condition: @escaping @Sendable (
_ left: TableAlias<RowDecoder>,
_ right: TableAlias<Destination>
) -> any SQLExpressible)
-> JoinAssociation<RowDecoder, Destination>
{
JoinAssociation(
to: destination.relationForAll,
condition: .expression { condition($0, $1).sqlExpression })
condition: .expression { left, right in
condition(TableAlias(root: left), TableAlias(root: right)).sqlExpression
})
}
/// Creates an association to a table that you can join
@@ -493,7 +493,7 @@ extension QueryInterfaceRequest: TableRequest {
relation.source.tableName
}
public func aliased(_ alias: TableAlias) -> Self {
public func _aliased(_ alias: TableAliasBase) -> Self {
with {
$0.relation = $0.relation.aliased(alias)
}
@@ -557,7 +557,19 @@ public protocol TableRequest {
/// .filter(sql: "b.publishDate >= a.deathDate")
/// .fetchAll(db)
/// ```
func aliased(_ alias: TableAlias) -> Self
func _aliased(_ alias: TableAliasBase) -> Self
}
extension TableRequest where Self: TypedRequest {
// TODO: DocC
public func aliased(_ alias: TableAlias<Void>) -> Self {
self._aliased(alias)
}
// TODO: DocC
public func aliased(_ alias: TableAlias<RowDecoder>) -> Self {
self._aliased(alias)
}
}
extension TableRequest where Self: FilteredRequest, Self: TypedRequest {
@@ -1607,9 +1619,17 @@ extension JoinableRequest where Self: SelectionRequest {
/// For example:
///
/// ```swift
/// struct Player: TableRecord { }
///
/// struct Team: TableRecord {
/// enum Columns {
/// static let color = Column("color")
/// }
/// }
///
/// // SELECT player.*, team.color
/// // FROM player JOIN team ...
/// let teamColor = Player.team.select(Column("color"))
/// let teamColor = Player.team.select { $0.color }
/// let request = Player.all().annotated(withRequired: teamColor)
/// ```
///
@@ -1635,9 +1655,9 @@ extension JoinableRequest where Self: SelectionRequest {
/// ``JoinableRequest/joining(required:)``:
///
/// ```swift
/// let teamAlias = TableAlias()
/// let teamAlias = TableAlias<Team>()
/// let request = Player.all()
/// .annotated(with: teamAlias[Column("color")])
/// .annotated(with: teamAlias.color])
/// .joining(required: Player.team.aliased(teamAlias))
/// ```
public func annotated<A: Association>(withRequired association: A) -> Self where A.OriginRowDecoder == RowDecoder {
+1 -1
View File
@@ -39,7 +39,7 @@ struct SQLCollection {
extension SQLCollection {
/// Returns a qualified collection.
func qualified(with alias: TableAlias) -> SQLCollection {
func qualified(with alias: TableAliasBase) -> SQLCollection {
switch impl {
case .subquery,
.table:
+16 -16
View File
@@ -68,7 +68,7 @@ public struct SQLExpression: Sendable {
///
/// player.id
/// player.name
case qualifiedColumn(String, TableAlias)
case qualifiedColumn(String, TableAliasBase)
/// A database value.
///
@@ -151,7 +151,7 @@ public struct SQLExpression: Sendable {
/// A table full-text match.
///
/// <table> MATCH <pattern>
indirect case tableMatch(TableAlias, SQLExpression)
indirect case tableMatch(TableAliasBase, SQLExpression)
/// A logical `NOT` operator.
///
@@ -199,7 +199,7 @@ public struct SQLExpression: Sendable {
/// player.id
/// document.rowid
/// country.code
case qualifiedFastPrimaryKey(TableAlias)
case qualifiedFastPrimaryKey(TableAliasBase)
/// An expression that is true iff the row exists:
///
@@ -207,10 +207,10 @@ public struct SQLExpression: Sendable {
/// - For tables WITHOUT ROWID, it is true iff any primary key column is not null.
/// - For views, it is true iff any column is not null.
/// - For CTEs, it is not implemented yet.
case qualifiedExists(TableAlias, isNegated: Bool)
case qualifiedExists(TableAliasBase, isNegated: Bool)
/// Returns a qualified expression
func qualified(with alias: TableAlias) -> Impl {
func qualified(with alias: TableAliasBase) -> Impl {
switch self {
case .databaseValue,
.qualifiedColumn,
@@ -642,7 +642,7 @@ extension SQLExpression {
///
/// player.id
/// player.name
static func qualifiedColumn(_ name: String, _ alias: TableAlias) -> Self {
static func qualifiedColumn(_ name: String, _ alias: TableAliasBase) -> Self {
self.init(impl: .qualifiedColumn(name, alias))
}
@@ -865,7 +865,7 @@ extension SQLExpression {
/// A table full-text match.
///
/// <table> MATCH <pattern>
static func tableMatch(_ alias: TableAlias, _ expression: SQLExpression) -> Self {
static func tableMatch(_ alias: TableAliasBase, _ expression: SQLExpression) -> Self {
self.init(impl: .tableMatch(alias, expression))
}
@@ -1153,7 +1153,7 @@ extension SQLExpression {
/// player.id
/// document.rowid
/// country.code
static func qualifiedFastPrimaryKey(_ alias: TableAlias) -> Self {
static func qualifiedFastPrimaryKey(_ alias: TableAliasBase) -> Self {
self.init(impl: .qualifiedFastPrimaryKey(alias))
}
@@ -1163,7 +1163,7 @@ extension SQLExpression {
/// - For tables WITHOUT ROWID, it is true iff any primary key column is not null.
/// - For views, it is true iff any column is not null.
/// - For CTEs, it is not implemented yet.
static func qualifiedExists(_ alias: TableAlias) -> Self {
static func qualifiedExists(_ alias: TableAliasBase) -> Self {
self.init(impl: .qualifiedExists(alias, isNegated: false))
}
}
@@ -1172,7 +1172,7 @@ extension SQLExpression {
extension SQLExpression {
/// Returns a qualified expression
func qualified(with alias: TableAlias) -> Self {
func qualified(with alias: TableAliasBase) -> Self {
.init(impl: impl.qualified(with: alias), preferredJSONInterpretation: preferredJSONInterpretation)
}
@@ -1217,7 +1217,7 @@ extension SQLExpression {
/// - parameter acceptsBijection: If true, expressions that define a
/// bijection on a column return this column. For example: `-score`
/// returns `score`.
func column(_ db: Database, for alias: TableAlias, acceptsBijection: Bool = false) throws -> String? {
func column(_ db: Database, for alias: TableAliasBase, acceptsBijection: Bool = false) throws -> String? {
switch impl {
case let .qualifiedColumn(name, a):
if alias == a {
@@ -1504,7 +1504,7 @@ extension SQLExpression {
///
/// // SELECT * FROM "player" WHERE "name" = 'Arthur' LIMIT 1
/// try Player.filter(Column("name") == "Arthur").fetchOne(db)
func identifyingColums(_ db: Database, for alias: TableAlias) throws -> Set<String> {
func identifyingColums(_ db: Database, for alias: TableAliasBase) throws -> Set<String> {
switch impl {
case let .rowValue(expressions):
assert(!expressions.isEmpty)
@@ -1572,7 +1572,7 @@ extension SQLExpression {
/// let request = Player.filter(keys: [1, 2, 3])
/// let regionObservation = DatabaseRegionObservation(tracking: request)
/// let valueObservation = ValueObservation.tracking(request.fetchAll)
func identifyingRowIDs(_ db: Database, for alias: TableAlias) throws -> Set<Int64>? {
func identifyingRowIDs(_ db: Database, for alias: TableAliasBase) throws -> Set<Int64>? {
switch impl {
case let .databaseValue(dbValue):
if dbValue.isNull || dbValue == false.databaseValue {
@@ -1979,7 +1979,7 @@ struct SQLSimpleFunctionInvocation {
isPure && arguments.allSatisfy(\.isConstantInRequest)
}
func qualified(with alias: TableAlias) -> Self {
func qualified(with alias: TableAliasBase) -> Self {
SQLSimpleFunctionInvocation(
name: name,
arguments: arguments.map { $0.qualified(with: alias) },
@@ -1987,7 +1987,7 @@ struct SQLSimpleFunctionInvocation {
isJSONValue: isJSONValue)
}
func column(_ db: Database, for alias: TableAlias) throws -> String? {
func column(_ db: Database, for alias: TableAliasBase) throws -> String? {
let name = name.uppercased()
if ["HEX", "QUOTE"].contains(name) && arguments.count == 1 {
return try arguments[0].column(db, for: alias, acceptsBijection: true)
@@ -2023,7 +2023,7 @@ struct SQLAggregateFunctionInvocation {
/// A false value does not provide any information.
var isJSONValue: Bool
func qualified(with alias: TableAlias) -> Self {
func qualified(with alias: TableAliasBase) -> Self {
SQLAggregateFunctionInvocation(
name: name,
arguments: arguments.map { $0.qualified(with: alias) },
+1 -1
View File
@@ -86,7 +86,7 @@ extension SQLOrdering {
}
extension SQLOrdering {
func qualified(with alias: TableAlias) -> SQLOrdering {
func qualified(with alias: TableAliasBase) -> SQLOrdering {
switch impl {
case .expression(let expression):
return .expression(expression.qualified(with: alias))
+9 -9
View File
@@ -331,7 +331,7 @@ extension SQLRelation: Refinable {
}
}
func aliased(_ alias: TableAlias) -> Self {
func aliased(_ alias: TableAliasBase) -> Self {
with {
$0.source = $0.source.aliased(alias)
}
@@ -674,9 +674,9 @@ struct SQLLimit {
struct SQLSource: Sendable {
var tableName: String
var alias: TableAlias?
var alias: TableAliasBase?
func aliased(_ alias: TableAlias) -> SQLSource {
func aliased(_ alias: TableAliasBase) -> SQLSource {
if let sourceAlias = self.alias {
alias.becomeProxy(of: sourceAlias)
return self
@@ -705,7 +705,7 @@ extension SQLRelation {
}
}
func qualified(with alias: TableAlias) -> Element {
func qualified(with alias: TableAliasBase) -> Element {
switch self {
case .terms(let terms):
return .terms(terms.map { $0.map { $0.qualified(with: alias) } })
@@ -752,7 +752,7 @@ extension SQLRelation {
isReversed: !isReversed)
}
func qualified(with alias: TableAlias) -> Ordering {
func qualified(with alias: TableAliasBase) -> Ordering {
Ordering(
elements: elements.map { $0.qualified(with: alias) },
isReversed: isReversed)
@@ -814,7 +814,7 @@ enum SQLAssociationCondition: Sendable {
/// player[Column("id")] == bonus[Column("playerID")]
/// })
/// Player.with(bonus).joining(required: association)
case expression(@Sendable (_ left: TableAlias, _ right: TableAlias) -> SQLExpression?)
case expression(@Sendable (_ left: TableAliasBase, _ right: TableAliasBase) -> SQLExpression?)
/// The condition that does not constrain the two associated tables
/// in any way.
@@ -831,8 +831,8 @@ enum SQLAssociationCondition: Sendable {
func joinExpression(
_ db: Database,
leftAlias: TableAlias,
rightAlias: TableAlias)
leftAlias: TableAliasBase,
rightAlias: TableAliasBase)
throws -> SQLExpression?
{
switch self {
@@ -999,7 +999,7 @@ extension JoinMapping {
/// JOIN operator.
/// - parameter rightAlias: A TableAlias for the table on the right of the
/// JOIN operator.
func joinExpression(leftAlias: TableAlias, rightAlias: TableAlias) -> SQLExpression {
func joinExpression(leftAlias: TableAliasBase, rightAlias: TableAliasBase) -> SQLExpression {
map { rightAlias[$0.right] == leftAlias[$0.left] }.joined(operator: .and)
}
}
+5 -5
View File
@@ -24,13 +24,13 @@ public struct SQLSelection: Sendable {
case allColumns
/// All columns, qualified: `player.*`
case qualifiedAllColumns(TableAlias)
case qualifiedAllColumns(TableAliasBase)
/// All columns but the specified ones
case allColumnsExcluding(Set<CaseInsensitiveIdentifier>)
/// All columns but the specified ones, qualified.
case qualifiedAllColumnsExcluding(TableAlias, Set<CaseInsensitiveIdentifier>)
case qualifiedAllColumnsExcluding(TableAliasBase, Set<CaseInsensitiveIdentifier>)
/// An expression
case expression(SQLExpression)
@@ -53,13 +53,13 @@ public struct SQLSelection: Sendable {
}
/// All columns, qualified: `player.*`
static func qualifiedAllColumns(_ alias: TableAlias) -> Self {
static func qualifiedAllColumns(_ alias: TableAliasBase) -> Self {
self.init(impl: .qualifiedAllColumns(alias))
}
/// All columns but the specified ones, qualified.
static func qualifiedAllColumnsExcluding(
_ alias: TableAlias,
_ alias: TableAliasBase,
_ excludedColumns: Set<CaseInsensitiveIdentifier>
) -> Self {
self.init(impl: .qualifiedAllColumnsExcluding(alias, excludedColumns))
@@ -261,7 +261,7 @@ extension SQLSelection {
}
/// Returns a qualified selection
func qualified(with alias: TableAlias) -> SQLSelection {
func qualified(with alias: TableAliasBase) -> SQLSelection {
switch impl {
case .qualifiedAllColumns, .qualifiedAllColumnsExcluding:
return self
+16 -3
View File
@@ -745,7 +745,15 @@ extension Table {
///
/// `table.aliased(alias)` is equivalent to `table.all().aliased(alias)`.
/// See ``TableRequest/aliased(_:)`` for more information.
public func aliased(_ alias: TableAlias) -> QueryInterfaceRequest<RowDecoder> {
public func aliased(_ alias: TableAlias<Void>) -> QueryInterfaceRequest<RowDecoder> {
all().aliased(alias)
}
/// Returns a request that can be referred to with the provided alias.
///
/// `table.aliased(alias)` is equivalent to `table.all().aliased(alias)`.
/// See ``TableRequest/aliased(_:)`` for more information.
public func aliased(_ alias: TableAlias<RowDecoder>) -> QueryInterfaceRequest<RowDecoder> {
all().aliased(alias)
}
@@ -1331,12 +1339,17 @@ extension Table {
/// - returns: An association to the common table expression.
public func association<Destination>(
to cte: CommonTableExpression<Destination>,
on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
on condition: @escaping @Sendable (
_ left: TableAlias<RowDecoder>,
_ right: TableAlias<Destination>
) -> any SQLExpressible)
-> JoinAssociation<RowDecoder, Destination>
{
JoinAssociation(
to: cte.relationForAll,
condition: .expression { condition($0, $1).sqlExpression })
condition: .expression { left, right in
condition(TableAlias(root: left), TableAlias(root: right)).sqlExpression
})
}
/// Creates an association to a common table expression.
@@ -37,8 +37,8 @@ final class SQLGenerationContext {
}
}
private let resolvedNames: [TableAlias: String]
private let ownAliases: Set<TableAlias>
private let resolvedNames: [TableAliasBase: String]
private let ownAliases: Set<TableAliasBase>
private let ownCTEs: [String: SQLCTE]
/// Creates a generation context.
@@ -50,7 +50,7 @@ final class SQLGenerationContext {
init(
_ db: Database,
argumentsSink: StatementArgumentsSink = StatementArgumentsSink(),
aliases: [TableAlias] = [],
aliases: [TableAliasBase] = [],
ctes: OrderedDictionary<String, SQLCTE> = [:])
{
self.parent = .none(db: db, argumentsSink: argumentsSink)
@@ -66,7 +66,7 @@ final class SQLGenerationContext {
/// - parameter ctes: An dictionary of available CTEs.
private init(
parent: SQLGenerationContext,
aliases: [TableAlias],
aliases: [TableAliasBase],
ctes: OrderedDictionary<String, SQLCTE>)
{
self.parent = .context(parent)
@@ -77,7 +77,7 @@ final class SQLGenerationContext {
/// Returns a generation context suitable for subqueries.
func subqueryContext(
aliases: [TableAlias] = [],
aliases: [TableAliasBase] = [],
ctes: OrderedDictionary<String, SQLCTE> = [:]) -> SQLGenerationContext
{
SQLGenerationContext(parent: self, aliases: aliases, ctes: ctes)
@@ -118,7 +118,7 @@ final class SQLGenerationContext {
///
/// WHERE column == 1
/// SELECT *
func qualifier(for alias: TableAlias) -> String? {
func qualifier(for alias: TableAliasBase) -> String? {
if alias.hasUserName {
return alias.identityName
}
@@ -132,7 +132,7 @@ final class SQLGenerationContext {
}
/// WHERE <resolvedName> MATCH pattern
func resolvedName(for alias: TableAlias) -> String {
func resolvedName(for alias: TableAliasBase) -> String {
if let name = resolvedNames[alias] {
return name
}
@@ -145,7 +145,7 @@ final class SQLGenerationContext {
}
/// FROM tableName <alias>
func aliasName(for alias: TableAlias) -> String? {
func aliasName(for alias: TableAliasBase) -> String? {
let resolvedName = self.resolvedName(for: alias)
if resolvedName != alias.tableName {
return resolvedName
@@ -244,9 +244,9 @@ class StatementArgumentsSink {
}
}
extension [TableAlias] {
extension [TableAliasBase] {
/// Resolve ambiguities in aliases' names.
fileprivate var resolvedNames: [TableAlias: String] {
fileprivate var resolvedNames: [TableAliasBase: String] {
// It is a programmer error to reuse the same TableAlias for
// multiple tables.
//
@@ -262,7 +262,7 @@ extension [TableAlias] {
}
var uniqueLowercaseNames: Set<String> = []
var ambiguousGroups: [[TableAlias]] = []
var ambiguousGroups: [[TableAliasBase]] = []
for (lowercaseName, group) in groups {
if group.count > 1 {
@@ -276,7 +276,7 @@ extension [TableAlias] {
}
}
var resolvedNames: [TableAlias: String] = [:]
var resolvedNames: [TableAliasBase: String] = [:]
for group in ambiguousGroups {
var index = 1
for alias in group {
@@ -573,7 +573,7 @@ struct SQLQueryGenerator: Refinable {
/// LIMIT ... -- limit
private struct SQLQualifiedRelation: Sendable {
/// All aliases, including aliases of joined relations
var allAliases: [TableAlias] {
var allAliases: [TableAliasBase] {
joins.reduce(into: [source.alias].compactMap { $0 }) {
$0.append(contentsOf: $1.value.relation.allAliases)
}
@@ -739,7 +739,7 @@ extension SQLQualifiedRelation: Refinable { }
/// A "qualified" source, where all tables are identified with a table alias.
private struct SQLQualifiedSource {
var tableName: String
var alias: TableAlias
var alias: TableAliasBase
init(_ source: SQLSource) {
self.tableName = source.tableName
@@ -788,13 +788,13 @@ private struct SQLQualifiedJoin: Refinable {
self.relation = SQLQualifiedRelation(child.relation)
}
func sql(_ context: SQLGenerationContext, leftAlias: TableAlias) throws -> String {
func sql(_ context: SQLGenerationContext, leftAlias: TableAliasBase) throws -> String {
try sql(context, leftAlias: leftAlias, allowingInnerJoin: true)
}
private func sql(
_ context: SQLGenerationContext,
leftAlias: TableAlias,
leftAlias: TableAliasBase,
allowingInnerJoin allowsInnerJoin: Bool)
throws -> String
{
@@ -3,7 +3,7 @@
/// See ``TableRequest/aliased(_:)`` for more information and examples.
///
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
public class TableAlias: @unchecked Sendable {
public class TableAliasBase: @unchecked Sendable {
// This Sendable conformance is transient. TableAlias IS NOT really Sendable.
// TODO: Make TableAlias really Sendable
private enum Impl {
@@ -50,13 +50,13 @@ public class TableAlias: @unchecked Sendable {
/// .including(required: Player.team)
/// .filter(sql: "custom.name = 'Arthur'")
/// .aliased(customAlias)
case proxy(TableAlias)
case proxy(TableAliasBase)
}
private var impl: Impl
/// Resolve all proxies
private var root: TableAlias {
private var root: TableAliasBase {
if case .proxy(let base) = impl {
return base.root
} else {
@@ -107,7 +107,7 @@ public class TableAlias: @unchecked Sendable {
/// let alias = TableAlias(name: "p")
/// let request = Player.all().aliased(alias)
/// ```
public init(name: String? = nil) {
init(name: String? = nil) {
self.impl = .undefined(userName: name)
}
@@ -115,7 +115,7 @@ public class TableAlias: @unchecked Sendable {
self.impl = .table(tableName: tableName, userName: userName)
}
func becomeProxy(of base: TableAlias) {
func becomeProxy(of base: TableAliasBase) {
if self === base {
return
}
@@ -142,7 +142,7 @@ public class TableAlias: @unchecked Sendable {
}
/// Returns nil if aliases can't be merged (conflict in tables, aliases...)
func merged(with other: TableAlias) -> TableAlias? {
func merged(with other: TableAliasBase) -> TableAliasBase? {
if self === other {
return self
}
@@ -198,7 +198,21 @@ public class TableAlias: @unchecked Sendable {
base.setTableName(tableName)
}
}
}
extension TableAliasBase: Equatable {
public static func == (lhs: TableAliasBase, rhs: TableAliasBase) -> Bool {
ObjectIdentifier(lhs.root) == ObjectIdentifier(rhs.root)
}
}
extension TableAliasBase: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(ObjectIdentifier(root))
}
}
extension TableAliasBase {
/// Returns a result column that refers to the aliased table.
public subscript(_ selectable: some SQLSelectable) -> SQLSelection {
// TODO: test
@@ -210,14 +224,28 @@ public class TableAlias: @unchecked Sendable {
/// For example, let's sort books by author name first, and then by title:
///
/// ```swift
/// struct Author: TableRecord {
/// enum Columns {
/// static let name = Column("name")
/// }
/// }
///
/// struct Book: TableRecord {
/// static let author = belongsTo(Author.self)
///
/// enum Columns {
/// static let title = Column("title")
/// }
/// }
///
/// // SELECT book.*
/// // FROM book
/// // JOIN author ON author.id = book.authorId
/// // ORDER BY author.name, book.title
/// let authorAlias = TableAlias()
/// let authorAlias = TableAlias<Author>()
/// let request = Book
/// .joining(required: Book.author.aliased(authorAlias))
/// .order(authorAlias[Column("name")], Column("title"))
/// .order { [authorAlias.name, $0.title] }
/// ```
public subscript(_ expression: some SQLSpecificExpressible & SQLSelectable & SQLOrderingTerm) -> SQLExpression {
expression.sqlExpression.qualified(with: self)
@@ -232,20 +260,6 @@ public class TableAlias: @unchecked Sendable {
AnySQLJSONExpressible(sqlExpression: expression.sqlExpression.qualified(with: self))
}
/// Returns an SQL ordering term that refers to the aliased table.
///
/// For example, let's sort books by author name first, and then by title:
///
/// ```swift
/// // SELECT book.*
/// // FROM book
/// // JOIN author ON author.id = book.authorId
/// // ORDER BY author.name ASC, book.title ASC
/// let authorAlias = TableAlias()
/// let request = Book
/// .joining(required: Book.author.aliased(authorAlias))
/// .order(authorAlias[Column("name").asc], Column("title").asc)
/// ```
public subscript(_ ordering: some SQLOrderingTerm) -> SQLOrdering {
ordering.sqlOrdering.qualified(with: self)
}
@@ -267,7 +281,58 @@ public class TableAlias: @unchecked Sendable {
public subscript(_ column: String) -> SQLExpression {
.qualifiedColumn(column, self)
}
}
// MARK: - TableAlias
@dynamicMemberLookup
public final class TableAlias<RowDecoder>: TableAliasBase, @unchecked Sendable {
init(tableName: String, userName: String? = nil)
where RowDecoder == Void
{
super.init(tableName: tableName, userName: userName)
}
init(root: TableAliasBase) {
super.init()
becomeProxy(of: root)
}
/// Creates a TableAlias.
///
/// When the alias is given a name, this name is guaranteed to be used as
/// the table alias in the SQL query:
///
/// ```swift
/// // SELECT p.* FROM player p
/// let alias = TableAlias(name: "p")
/// let request = Player.all().aliased(alias)
/// ```
public init(name: String? = nil)
where RowDecoder == Void
{
super.init(name: name)
}
/// Creates a TableAlias for the specified record type.
///
/// When the alias is given a name, this name is guaranteed to be used as
/// the table alias in the SQL query:
///
/// ```swift
/// // SELECT p.* FROM player p
/// let alias = TableAlias<Player>(name: "p")
/// let request = Player.all().aliased(alias)
/// ```
public init(
name: String? = nil,
for record: RowDecoder.Type = RowDecoder.self
) {
super.init(name: name)
}
}
extension TableAlias {
/// A boolean SQL expression indicating whether this alias refers to some
/// rows, or not.
///
@@ -281,7 +346,7 @@ public class TableAlias: @unchecked Sendable {
/// }
///
/// try dbQueue.read { db in
/// let authorAlias = TableAlias()
/// let authorAlias = TableAlias<Author>()
/// let request = Book
/// .joining(optional: Book.author.aliased(authorAlias))
/// .filter(!authorAlias.exists)
@@ -293,14 +358,69 @@ public class TableAlias: @unchecked Sendable {
}
}
extension TableAlias: Equatable {
public static func == (lhs: TableAlias, rhs: TableAlias) -> Bool {
ObjectIdentifier(lhs.root) == ObjectIdentifier(rhs.root)
}
}
extension TableAlias: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(ObjectIdentifier(root))
extension TableAlias where RowDecoder: TableRecord {
/// Returns a result column that refers to the aliased table.
public subscript<T>(
dynamicMember keyPath: KeyPath<RowDecoder.ColumnsProvider, T>
) -> SQLSelection
where T: SQLSelectable
{
self[RowDecoder.columns[keyPath: keyPath]]
}
/// Returns an SQL expression that refers to the aliased table.
///
/// For example, let's sort books by author name first, and then by title:
///
/// ```swift
/// struct Author: TableRecord {
/// enum Columns {
/// static let name = Column("name")
/// }
/// }
///
/// struct Book: TableRecord {
/// static let author = belongsTo(Author.self)
///
/// enum Columns {
/// static let title = Column("title")
/// }
/// }
///
/// // SELECT book.*
/// // FROM book
/// // JOIN author ON author.id = book.authorId
/// // ORDER BY author.name, book.title
/// let authorAlias = TableAlias<Author>()
/// let request = Book
/// .joining(required: Book.author.aliased(authorAlias))
/// .order { [authorAlias.name, $0.title] }
/// ```
public subscript<T>(
dynamicMember keyPath: KeyPath<RowDecoder.ColumnsProvider, T>
) -> SQLExpression
where T: SQLSpecificExpressible &
SQLSelectable &
SQLOrderingTerm
{
self[RowDecoder.columns[keyPath: keyPath]]
}
public subscript<T>(
dynamicMember keyPath: KeyPath<RowDecoder.ColumnsProvider, T>
) -> AnySQLJSONExpressible
where T: SQLJSONExpressible &
SQLSpecificExpressible &
SQLSelectable &
SQLOrderingTerm
{
self[RowDecoder.columns[keyPath: keyPath]]
}
public subscript<T>(
dynamicMember keyPath: KeyPath<RowDecoder.ColumnsProvider, T>
) -> SQLOrdering
where T: SQLOrderingTerm {
self[RowDecoder.columns[keyPath: keyPath]]
}
}
@@ -339,12 +339,17 @@ extension TableRecord {
/// - returns: An association to the common table expression.
public static func association<Destination>(
to cte: CommonTableExpression<Destination>,
on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
on condition: @escaping @Sendable (
_ left: TableAlias<Self>,
_ right: TableAlias<Destination>
) -> any SQLExpressible)
-> JoinAssociation<Self, Destination>
{
JoinAssociation(
to: cte.relationForAll,
condition: .expression { condition($0, $1).sqlExpression })
condition: .expression { left, right in
condition(TableAlias(root: left), TableAlias(root: right)).sqlExpression
})
}
/// Creates an association to a common table expression.
@@ -749,7 +749,44 @@ extension TableRecord {
/// ```
///
/// See ``TableRequest/aliased(_:)`` for more information.
public static func aliased(_ alias: TableAlias) -> QueryInterfaceRequest<Self> {
public static func aliased(_ alias: TableAlias<Void>) -> QueryInterfaceRequest<Self> {
all().aliased(alias)
}
/// Returns a request that can be referred to with the provided alias.
///
/// Use this method when you need to refer to this table from
/// another request.
///
/// For example, the request below fetches posthumous books:
///
/// ```swift
/// struct Author: TableRecord {
/// enum Columns {
/// static let deathDate = Column("deathDate")
/// }
/// }
///
/// struct Book: TableRecord {
/// static let author = belongsTo(Author.self)
///
/// enum Columns {
/// static let publishDate = Column("publishDate")
/// }
/// }
///
/// // SELECT book.*
/// // FROM book
/// // JOIN author ON author.id = book.authorId
/// // AND author.deathDate <= book.publishDate
/// let bookAlias = TableAlias<Book>()
/// let request = Book
/// .aliased(bookAlias)
/// .joining(required: Book.author.filter { $0.deathDate <= bookAlias.publishDate })
/// ```
///
/// See ``TableRequest/aliased(_:)`` for more information.
public static func aliased(_ alias: TableAlias<Self>) -> QueryInterfaceRequest<Self> {
all().aliased(alias)
}
@@ -42,8 +42,11 @@ final class DAO<Record: MutablePersistableRecord> {
func upsertStatement(
_ db: Database,
onConflict conflictTargetColumns: [String],
doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])?,
updateCondition: ((_ existing: TableAlias, _ excluded: TableAlias) -> any SQLExpressible)? = nil,
doUpdate assignments: ((_ excluded: TableAlias<Record>) -> [ColumnAssignment])?,
updateCondition: ((
_ existing: TableAlias<Record>,
_ excluded: TableAlias<Record>
) -> any SQLExpressible)? = nil,
returning selection: [any SQLSelectable])
throws -> Statement
{
@@ -73,7 +76,7 @@ final class DAO<Record: MutablePersistableRecord> {
// that no information stored in the record is lost, unless explicitly
// requested by the user.
sql += " DO UPDATE SET "
let excluded = TableAlias(name: "excluded")
let excluded = TableAlias<Record>(name: "excluded")
var assignments = assignments?(excluded) ?? []
let lowercaseExcludedColumns = Set(primaryKey.columns.map { $0.lowercased() })
.union(conflictTargetColumns.map { $0.lowercased() })
@@ -119,7 +122,7 @@ final class DAO<Record: MutablePersistableRecord> {
}
// WHERE
let existing = TableAlias(name: databaseTableName)
let existing = TableAlias<Record>(name: databaseTableName)
if let condition = updateCondition?(existing, excluded) {
let context = SQLGenerationContext(db)
sql += try " WHERE " + condition.sqlExpression.sql(context)
@@ -253,7 +256,7 @@ final class DAO<Record: MutablePersistableRecord> {
// Make sure the selection is qualified with a table alias, so
// that selectables such as `.allColumns(excluding:)` can query
// the database about the database table.
let alias = TableAlias(tableName: databaseTableName)
let alias = TableAliasBase(tableName: databaseTableName)
let context = SQLGenerationContext(db, aliases: [alias])
var sql = sql
var arguments = arguments
@@ -128,7 +128,7 @@ extension MutablePersistableRecord {
public mutating func upsertAndFetch(
_ db: Database,
onConflict conflictTarget: [String] = [],
doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil)
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
throws -> Self
where Self: FetchableRecord
{
@@ -156,7 +156,7 @@ extension MutablePersistableRecord {
_ db: Database,
as returnedType: T.Type,
onConflict conflictTarget: [String] = [],
doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil)
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
throws -> T
{
try willSave(db)
@@ -306,7 +306,7 @@ extension MutablePersistableRecord {
public mutating func upsertAndFetch(
_ db: Database,
onConflict conflictTarget: [String] = [],
doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil)
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
throws -> Self
where Self: FetchableRecord
{
@@ -335,7 +335,7 @@ extension MutablePersistableRecord {
_ db: Database,
as returnedType: T.Type,
onConflict conflictTarget: [String] = [],
doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil)
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
throws -> T
{
try willSave(db)
@@ -378,7 +378,7 @@ extension MutablePersistableRecord {
mutating func upsertAndFetchWithCallbacks<T>(
_ db: Database,
onConflict conflictTarget: [String],
doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])?,
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])?,
selection: [any SQLSelectable],
decode: (Row) throws -> T)
throws -> (InsertionSuccess, T)
@@ -408,7 +408,7 @@ extension MutablePersistableRecord {
func upsertAndFetchWithoutCallbacks<T>(
_ db: Database,
onConflict conflictTarget: [String],
doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])?,
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])?,
selection: [any SQLSelectable],
decode: (Row) throws -> T)
throws -> (InsertionSuccess, T)
+5 -5
View File
@@ -128,7 +128,7 @@ extension PersistableRecord {
public func upsertAndFetch(
_ db: Database,
onConflict conflictTarget: [String] = [],
doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil)
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
throws -> Self
where Self: FetchableRecord
{
@@ -156,7 +156,7 @@ extension PersistableRecord {
_ db: Database,
as returnedType: T.Type,
onConflict conflictTarget: [String] = [],
doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil)
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
throws -> T
{
try willSave(db)
@@ -306,7 +306,7 @@ extension PersistableRecord {
public func upsertAndFetch(
_ db: Database,
onConflict conflictTarget: [String] = [],
doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil)
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
throws -> Self
where Self: FetchableRecord
{
@@ -335,7 +335,7 @@ extension PersistableRecord {
_ db: Database,
as returnedType: T.Type,
onConflict conflictTarget: [String] = [],
doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil)
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
throws -> T
{
try willSave(db)
@@ -378,7 +378,7 @@ extension PersistableRecord {
func upsertAndFetchWithCallbacks<T>(
_ db: Database,
onConflict conflictTarget: [String],
doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])?,
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])?,
selection: [any SQLSelectable],
decode: (Row) throws -> T)
throws -> (InsertionSuccess, T)