Skip to content

Add support for explicit schema names #43

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 15, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion Sources/StructuredQueries/Macros.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,16 @@ import StructuredQueriesCore
named(init(_:)),
named(init(decoder:)),
named(QueryValue),
named(schemaName),
named(tableName)
)
@attached(
memberAttribute
)
public macro Table(_ name: String? = nil) =
public macro Table(
_ name: String? = nil,
schema schemaName: String? = nil
) =
#externalMacro(
module: "StructuredQueriesMacros",
type: "TableMacro"
Expand Down
4 changes: 4 additions & 0 deletions Sources/StructuredQueriesCore/QueryFragment.swift
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,10 @@ extension QueryFragment: ExpressibleByStringInterpolation {
///
/// - Parameter table: A table.
public mutating func appendInterpolation<T: Table>(_ table: T.Type) {
if let schemaName = table.schemaName {
appendInterpolation(quote: schemaName)
appendLiteral(".")
}
appendInterpolation(quote: table.tableAlias ?? table.tableName)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,10 @@ public struct With<QueryValue>: Statement {

public struct CommonTableExpressionClause: QueryExpression {
public typealias QueryValue = ()
let tableName: String
let tableName: QueryFragment
let select: QueryFragment
public var queryFragment: QueryFragment {
"\(quote: tableName) AS (\(.newline)\(select.indented())\(.newline))"
"\(tableName) AS (\(.newline)\(select.indented())\(.newline))"
}
}

Expand All @@ -55,7 +55,7 @@ public enum CommonTableExpressionBuilder {
public static func buildExpression<CTETable: Table>(
_ expression: some PartialSelectStatement<CTETable>
) -> CommonTableExpressionClause {
CommonTableExpressionClause(tableName: CTETable.tableName, select: expression.query)
CommonTableExpressionClause(tableName: "\(CTETable.self)", select: expression.query)
}

public static func buildBlock(
Expand Down
6 changes: 5 additions & 1 deletion Sources/StructuredQueriesCore/Statements/Delete.swift
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,11 @@ extension Delete: Statement {
public typealias QueryValue = Returning

public var query: QueryFragment {
var query: QueryFragment = "DELETE FROM \(quote: From.tableName)"
var query: QueryFragment = "DELETE FROM "
if let schemaName = From.schemaName {
query.append("\(quote: schemaName).")
}
query.append("\(quote: From.tableName)")
if let tableAlias = From.tableAlias {
query.append(" AS \(quote: tableAlias)")
}
Expand Down
6 changes: 5 additions & 1 deletion Sources/StructuredQueriesCore/Statements/Insert.swift
Original file line number Diff line number Diff line change
Expand Up @@ -403,7 +403,11 @@ extension Insert: Statement {
if let conflictResolution {
query.append(" OR \(conflictResolution)")
}
query.append(" INTO \(quote: Into.tableName)")
query.append(" INTO ")
if let schemaName = Into.schemaName {
query.append("\(quote: schemaName).")
}
query.append("\(quote: Into.tableName)")
if let tableAlias = Into.tableAlias {
query.append(" AS \(quote: tableAlias)")
}
Expand Down
6 changes: 5 additions & 1 deletion Sources/StructuredQueriesCore/Statements/Select.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1410,7 +1410,11 @@ extension Select: SelectStatement {
query.append(" DISTINCT")
}
query.append(" \(columns.joined(separator: ", "))")
query.append("\(.newlineOrSpace)FROM \(quote: From.tableName)")
query.append("\(.newlineOrSpace)FROM ")
if let schemaName = From.schemaName {
query.append("\(quote: schemaName).")
}
query.append("\(quote: From.tableName)")
if let tableAlias = From.tableAlias {
query.append(" AS \(quote: tableAlias)")
}
Expand Down
9 changes: 6 additions & 3 deletions Sources/StructuredQueriesCore/Statements/Update.swift
Original file line number Diff line number Diff line change
Expand Up @@ -196,11 +196,14 @@ extension Update: Statement {
guard !updates.isEmpty
else { return "" }

var query: QueryFragment = "UPDATE"
var query: QueryFragment = "UPDATE "
if let conflictResolution {
query.append(" OR \(conflictResolution)")
query.append("OR \(conflictResolution) ")
}
query.append(" \(quote: From.tableName)")
if let schemaName = From.schemaName {
query.append("\(quote: schemaName).")
}
query.append("\(quote: From.tableName)")
if let tableAlias = From.tableAlias {
query.append(" AS \(quote: tableAlias)")
}
Expand Down
7 changes: 7 additions & 0 deletions Sources/StructuredQueriesCore/Table.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ public protocol Table: QueryRepresentable where TableColumns.QueryValue == Self
/// This property should always return `nil` unless called on a ``TableAlias``.
static var tableAlias: String? { get }

/// The table schema's name.
static var schemaName: String? { get }

/// A select statement for this table.
///
/// The default implementation of this property returns a fully unscoped query for the table
Expand Down Expand Up @@ -90,6 +93,10 @@ extension Table {
nil
}

public static var schemaName: String? {
nil
}

/// Returns a table column to the resulting value of a given key path.
///
/// Allows, _e.g._ `Reminder.columns.id` to be abbreviated `Reminder.id`, which is useful when
Expand Down
80 changes: 55 additions & 25 deletions Sources/StructuredQueriesMacros/TableMacro.swift
Original file line number Diff line number Diff line change
Expand Up @@ -49,32 +49,56 @@ extension TableMacro: ExtensionMacro {
let selfRewriter = SelfRewriter(
selfEquivalent: type.as(IdentifierTypeSyntax.self)?.name ?? "QueryValue"
)
let tableName: ExprSyntax
if case let .argumentList(arguments) = node.arguments,
let expression = arguments.first?.expression
{
if node.attributeName.identifier == "_Draft" {
let memberAccess = expression.cast(MemberAccessExprSyntax.self)
let base = memberAccess.base!
draftTableType = TypeSyntax("\(base)")
tableName = "\(base).tableName"
} else {
if !expression.isNonEmptyStringLiteral {
diagnostics.append(
Diagnostic(
node: expression,
message: MacroExpansionErrorMessage("Argument must be a non-empty string literal")
)
)
var schemaName: ExprSyntax?
var tableName = ExprSyntax(
StringLiteralExprSyntax(
content: declaration.name.trimmed.text.lowerCamelCased().pluralized()
)
)
if case let .argumentList(arguments) = node.arguments {
for argumentIndex in arguments.indices {
let argument = arguments[argumentIndex]
switch argument.label {
case nil:
if node.attributeName.identifier == "_Draft" {
let memberAccess = argument.expression.cast(MemberAccessExprSyntax.self)
let base = memberAccess.base!
draftTableType = TypeSyntax("\(base)")
tableName = "\(base).tableName"
} else {
if !argument.expression.isNonEmptyStringLiteral {
diagnostics.append(
Diagnostic(
node: argument.expression,
message: MacroExpansionErrorMessage("Argument must be a non-empty string literal")
)
)
}
tableName = argument.expression.trimmed
}

case let .some(label) where label.text == "schema":
if node.attributeName.identifier == "_Draft" {
let memberAccess = argument.expression.cast(MemberAccessExprSyntax.self)
let base = memberAccess.base!
draftTableType = TypeSyntax("\(base)")
schemaName = "\(base).schemaName"
} else {
if !argument.expression.isNonEmptyStringLiteral {
diagnostics.append(
Diagnostic(
node: argument.expression,
message: MacroExpansionErrorMessage("Argument must be a non-empty string literal")
)
)
}
schemaName = argument.expression.trimmed
}

case let argument?:
fatalError("Unexpected argument: \(argument)")
}
tableName = expression.trimmed
}
} else {
tableName = ExprSyntax(
StringLiteralExprSyntax(
content: declaration.name.trimmed.text.lowerCamelCased().pluralized()
)
)
}
for member in declaration.memberBlock.members {
guard
Expand Down Expand Up @@ -545,6 +569,12 @@ extension TableMacro: ExtensionMacro {
}

var typeAliases: [DeclSyntax] = []
var letSchemaName: DeclSyntax?
if let schemaName {
letSchemaName = """
public static let schemaName: Swift.String? = \(schemaName)
"""
}
var initDecoder: DeclSyntax?
if declaration.hasMacroApplication("Selection") {
conformances.append("\(moduleName).PartialSelectStatement")
Expand Down Expand Up @@ -579,7 +609,7 @@ extension TableMacro: ExtensionMacro {
}
}\(draft)\(typeAliases, separator: "\n")
public static let columns = TableColumns()
public static let tableName = \(tableName)\(initDecoder)\(initFromOther)
public static let tableName = \(tableName)\(letSchemaName)\(initDecoder)\(initFromOther)
}
"""
)
Expand Down
16 changes: 16 additions & 0 deletions Sources/StructuredQueriesTestSupport/AssertQuery.swift
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,22 @@ public func assertQuery<each V: QueryRepresentable, S: Statement<(repeat each V)
line: line,
column: column
)
} else {
assertInlineSnapshot(
of: table,
as: .lines,
message: "Results did not match",
syntaxDescriptor: InlineSnapshotSyntaxDescriptor(
trailingClosureLabel: "results",
trailingClosureOffset: snapshotTrailingClosureOffset + 1
),
matches: nil,
fileID: fileID,
file: filePath,
function: function,
line: line,
column: column
)
}
} catch {
assertInlineSnapshot(
Expand Down
83 changes: 80 additions & 3 deletions Tests/StructuredQueriesMacrosTests/TableMacroTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -198,15 +198,15 @@ extension SnapshotTests {
@Test func tableNameEmpty() {
assertMacro {
"""
@Table(nil)
@Table("")
struct Foo {
var bar: Int
}
"""
} diagnostics: {
"""
@Table(nil)
┬─
@Table("")
┬─
╰─ 🛑 Argument must be a non-empty string literal
struct Foo {
var bar: Int
Expand All @@ -215,6 +215,83 @@ extension SnapshotTests {
}
}

@Test func schemaName() {
assertMacro {
"""
@Table("bar", schema: "foo")
struct Bar {
var baz: Int
}
"""
} expansion: {
#"""
struct Bar {
var baz: Int
}

extension Bar: StructuredQueries.Table {
public struct TableColumns: StructuredQueries.TableDefinition {
public typealias QueryValue = Bar
public let baz = StructuredQueries.TableColumn<QueryValue, Int>("baz", keyPath: \QueryValue.baz)
public static var allColumns: [any StructuredQueries.TableColumnExpression] {
[QueryValue.columns.baz]
}
}
public static let columns = TableColumns()
public static let tableName = "bar"
public static let schemaName: Swift.String? = "foo"
public init(decoder: inout some StructuredQueries.QueryDecoder) throws {
let baz = try decoder.decode(Int.self)
guard let baz else {
throw QueryDecodingError.missingRequiredColumn
}
self.baz = baz
}
}
"""#
}
}

@Test func schemaNameNil() {
assertMacro {
"""
@Table(schema: nil)
struct Foo {
var bar: Int
}
"""
} diagnostics: {
"""
@Table(schema: nil)
┬──
╰─ 🛑 Argument must be a non-empty string literal
struct Foo {
var bar: Int
}
"""
}
}

@Test func schemaNameEmpty() {
assertMacro {
"""
@Table(schema: "")
struct Foo {
var bar: Int
}
"""
} diagnostics: {
"""
@Table(schema: "")
┬─
╰─ 🛑 Argument must be a non-empty string literal
struct Foo {
var bar: Int
}
"""
}
}

@Test func literals() {
assertMacro {
"""
Expand Down
Loading
Loading