mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-23 04:04:22 +00:00
SQLString everywhere
This commit is contained in:
1 parent
f27a1e9504
commit
09e85ba341
13 files changed
+186
-103
No files matched your search
@@ -127,7 +127,36 @@ extension Database {
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public func execute(_ sql: String, arguments: StatementArguments? = nil) throws {
|
||||
// TODO: force sql parameter name: execute(sql:...)
|
||||
|
||||
// TODO: make arguments non optional
|
||||
try execute(SQLString(sql: sql, arguments: arguments ?? .init()))
|
||||
}
|
||||
|
||||
/// Executes one or several SQL statements, separated by semi-colons.
|
||||
///
|
||||
/// try db.execute(SQLString(
|
||||
/// sql: "INSERT INTO player (name) VALUES (:name)",
|
||||
/// arguments: ["name": "Arthur"]))
|
||||
///
|
||||
/// try db.execute(SQLString(sql: """
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// """, arguments: ["Arthur", "Barbara", "O'Brien"]))
|
||||
///
|
||||
/// With Swift 5, you can safely embed raw values in your SQL queries,
|
||||
/// without any risk of syntax errors or SQL injection:
|
||||
///
|
||||
/// try db.execute(SQLString("""
|
||||
/// INSERT INTO player (name) VALUES (\("Arthur"));
|
||||
/// INSERT INTO player (name) VALUES (\("Barbara"));
|
||||
/// INSERT INTO player (name) VALUES (\("O'Brien"));
|
||||
/// """))
|
||||
///
|
||||
/// This method may throw a DatabaseError.
|
||||
///
|
||||
/// - parameter sqlString: An SQLString.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public func execute(_ sqlString: SQLString) throws {
|
||||
// This method is like sqlite3_exec (https://www.sqlite.org/c3ref/exec.html)
|
||||
// It adds support for arguments, and the tricky part is to consume
|
||||
// arguments as statements are executed.
|
||||
@@ -138,7 +167,9 @@ extension Database {
|
||||
// all statements have been executed, in the same way
|
||||
// as Statement.validate(arguments:)
|
||||
|
||||
var arguments = arguments ?? StatementArguments()
|
||||
let sql = sqlString.sql
|
||||
var arguments = sqlString.arguments
|
||||
|
||||
let initialValuesCount = arguments.values.count
|
||||
let consumeArguments = { (statement: UpdateStatement) throws -> StatementArguments in
|
||||
let bindings = try arguments.consume(statement, allowingRemainingValues: true)
|
||||
@@ -192,35 +223,6 @@ extension Database {
|
||||
// arguments that do not match the statement.
|
||||
try! validateRemainingArguments() // throws if there are remaining arguments.
|
||||
}
|
||||
|
||||
/// Executes one or several SQL statements, separated by semi-colons.
|
||||
///
|
||||
/// try db.execute(SQLString(
|
||||
/// sql: "INSERT INTO player (name) VALUES (:name)",
|
||||
/// arguments: ["name": "Arthur"]))
|
||||
///
|
||||
/// try db.execute(SQLString(sql: """
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// """, arguments: ["Arthur", "Barbara", "O'Brien"]))
|
||||
///
|
||||
/// With Swift 5, you can safely embed raw values in your SQL queries,
|
||||
/// without any risk of syntax errors or SQL injection:
|
||||
///
|
||||
/// try db.execute(SQLString("""
|
||||
/// INSERT INTO player (name) VALUES (\("Arthur"));
|
||||
/// INSERT INTO player (name) VALUES (\("Barbara"));
|
||||
/// INSERT INTO player (name) VALUES (\("O'Brien"));
|
||||
/// """))
|
||||
///
|
||||
/// This method may throw a DatabaseError.
|
||||
///
|
||||
/// - parameter sqlString: An SQLString.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public func execute(_ sqlString: SQLString) throws {
|
||||
try execute(sqlString.sql, arguments: sqlString.arguments)
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
@@ -260,7 +260,7 @@ extension DatabaseValueConvertible {
|
||||
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self> {
|
||||
// TODO: make arguments non optional
|
||||
// TODO: force sql parameter name: fetchCursor(db, sql:...)
|
||||
return try fetchCursor(db, SQLString(sql: sql, arguments: arguments ?? []), adapter: adapter)
|
||||
return try fetchCursor(db, SQLString(sql: sql, arguments: arguments ?? .init()), adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of values fetched from an SQL query.
|
||||
@@ -277,7 +277,7 @@ extension DatabaseValueConvertible {
|
||||
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] {
|
||||
// TODO: make arguments non optional
|
||||
// TODO: force sql parameter name: fetchCursor(db, sql:...)
|
||||
return try fetchAll(db, SQLString(sql: sql, arguments: arguments ?? []), adapter: adapter)
|
||||
return try fetchAll(db, SQLString(sql: sql, arguments: arguments ?? .init()), adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns a single value fetched from an SQL query.
|
||||
@@ -297,7 +297,7 @@ extension DatabaseValueConvertible {
|
||||
public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? {
|
||||
// TODO: make arguments non optional
|
||||
// TODO: force sql parameter name: fetchCursor(db, sql:...)
|
||||
return try fetchOne(db, SQLString(sql: sql, arguments: arguments ?? []), adapter: adapter)
|
||||
return try fetchOne(db, SQLString(sql: sql, arguments: arguments ?? .init()), adapter: adapter)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -588,7 +588,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped> {
|
||||
// TODO: make arguments non optional
|
||||
// TODO: force sql parameter name: fetchCursor(db, sql:...)
|
||||
return try fetchCursor(db, SQLString(sql: sql, arguments: arguments ?? []), adapter: adapter)
|
||||
return try fetchCursor(db, SQLString(sql: sql, arguments: arguments ?? .init()), adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of optional values fetched from an SQL query.
|
||||
@@ -605,7 +605,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] {
|
||||
// TODO: make arguments non optional
|
||||
// TODO: force sql parameter name: fetchCursor(db, sql:...)
|
||||
return try fetchAll(db, SQLString(sql: sql, arguments: arguments ?? []), adapter: adapter)
|
||||
return try fetchAll(db, SQLString(sql: sql, arguments: arguments ?? .init()), adapter: adapter)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+3
-3
@@ -751,7 +751,7 @@ extension Row {
|
||||
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RowCursor {
|
||||
// TODO: make arguments non optional
|
||||
// TODO: force sql parameter name: fetchCursor(db, sql:...)
|
||||
return try fetchCursor(db, SQLString(sql: sql, arguments: arguments ?? []), adapter: adapter)
|
||||
return try fetchCursor(db, SQLString(sql: sql, arguments: arguments ?? .init()), adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of rows fetched from an SQL query.
|
||||
@@ -772,7 +772,7 @@ extension Row {
|
||||
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Row] {
|
||||
// TODO: make arguments non optional
|
||||
// TODO: force sql parameter name: fetchCursor(db, sql:...)
|
||||
return try fetchAll(db, SQLString(sql: sql, arguments: arguments ?? []), adapter: adapter)
|
||||
return try fetchAll(db, SQLString(sql: sql, arguments: arguments ?? .init()), adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns a single row fetched from an SQL query.
|
||||
@@ -793,7 +793,7 @@ extension Row {
|
||||
public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Row? {
|
||||
// TODO: make arguments non optional
|
||||
// TODO: force sql parameter name: fetchCursor(db, sql:...)
|
||||
return try fetchOne(db, SQLString(sql: sql, arguments: arguments ?? []), adapter: adapter)
|
||||
return try fetchOne(db, SQLString(sql: sql, arguments: arguments ?? .init()), adapter: adapter)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ public struct SQLString {
|
||||
private(set) public var sql: String
|
||||
private(set) public var arguments: StatementArguments
|
||||
|
||||
public init(sql: String, arguments: StatementArguments = []) {
|
||||
public init(sql: String, arguments: StatementArguments = StatementArguments()) {
|
||||
self.sql = sql
|
||||
self.arguments = arguments
|
||||
}
|
||||
|
||||
@@ -96,7 +96,7 @@ public class Statement {
|
||||
// MARK: Arguments
|
||||
|
||||
var argumentsNeedValidation = true
|
||||
var _arguments: StatementArguments = []
|
||||
var _arguments = StatementArguments()
|
||||
|
||||
lazy var sqliteArgumentCount: Int = {
|
||||
Int(sqlite3_bind_parameter_count(self.sqliteStatement))
|
||||
@@ -599,7 +599,7 @@ public struct StatementArguments: CustomStringConvertible, Equatable, Expressibl
|
||||
// MARK: Empty Arguments
|
||||
|
||||
/// Creates empty StatementArguments.
|
||||
init() {
|
||||
public init() {
|
||||
}
|
||||
|
||||
// MARK: Positional Arguments
|
||||
|
||||
@@ -248,7 +248,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> FastDatabaseValueCursor<Self> {
|
||||
// TODO: make arguments non optional
|
||||
// TODO: force sql parameter name: fetchCursor(db, sql:...)
|
||||
return try fetchCursor(db, SQLString(sql: sql, arguments: arguments ?? []), adapter: adapter)
|
||||
return try fetchCursor(db, SQLString(sql: sql, arguments: arguments ?? .init()), adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of values fetched from an SQL query.
|
||||
@@ -265,7 +265,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] {
|
||||
// TODO: make arguments non optional
|
||||
// TODO: force sql parameter name: fetchCursor(db, sql:...)
|
||||
return try fetchAll(db, SQLString(sql: sql, arguments: arguments ?? []), adapter: adapter)
|
||||
return try fetchAll(db, SQLString(sql: sql, arguments: arguments ?? .init()), adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns a single value fetched from an SQL query.
|
||||
@@ -282,7 +282,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? {
|
||||
// TODO: make arguments non optional
|
||||
// TODO: force sql parameter name: fetchCursor(db, sql:...)
|
||||
return try fetchOne(db, SQLString(sql: sql, arguments: arguments ?? []), adapter: adapter)
|
||||
return try fetchOne(db, SQLString(sql: sql, arguments: arguments ?? .init()), adapter: adapter)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -569,7 +569,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
|
||||
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> FastNullableDatabaseValueCursor<Wrapped> {
|
||||
// TODO: make arguments non optional
|
||||
// TODO: force sql parameter name: fetchCursor(db, sql:...)
|
||||
return try fetchCursor(db, SQLString(sql: sql, arguments: arguments ?? []), adapter: adapter)
|
||||
return try fetchCursor(db, SQLString(sql: sql, arguments: arguments ?? .init()), adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of optional values fetched from an SQL query.
|
||||
@@ -586,7 +586,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
|
||||
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] {
|
||||
// TODO: make arguments non optional
|
||||
// TODO: force sql parameter name: fetchCursor(db, sql:...)
|
||||
return try fetchAll(db, SQLString(sql: sql, arguments: arguments ?? []), adapter: adapter)
|
||||
return try fetchAll(db, SQLString(sql: sql, arguments: arguments ?? .init()), adapter: adapter)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -108,7 +108,7 @@ extension QueryInterfaceRequest : DerivableRequest, AggregatingRequest {
|
||||
/// }
|
||||
public func select<RowDecoder>(sql: String, arguments: StatementArguments? = nil, as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder> {
|
||||
// TODO: make arguments non optional
|
||||
return select(SQLString(sql: sql, arguments: arguments ?? []), as: type)
|
||||
return select(SQLString(sql: sql, arguments: arguments ?? .init()), as: type)
|
||||
}
|
||||
|
||||
/// Creates a request which selects *sql*, and fetches values of
|
||||
@@ -139,7 +139,7 @@ extension QueryInterfaceRequest : DerivableRequest, AggregatingRequest {
|
||||
/// let name: String? = try request.fetchOne(db)
|
||||
/// }
|
||||
public func select<RowDecoder>(_ sqlString: SQLString, as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder> {
|
||||
return select(SQLSelectionLiteral(sqlString: sqlString), as: type)
|
||||
return select(SQLSelectionLiteral(sqlString), as: type)
|
||||
}
|
||||
|
||||
/// Creates a request which appends *selection*.
|
||||
@@ -374,7 +374,7 @@ extension TableRecord {
|
||||
/// let request = Player.select(sql: "id, email")
|
||||
public static func select(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest<Self> {
|
||||
// TODO: make arguments non optional
|
||||
return select(SQLString(sql: sql, arguments: arguments ?? []))
|
||||
return select(SQLString(sql: sql, arguments: arguments ?? .init()))
|
||||
}
|
||||
|
||||
/// Creates a request which selects *sql*.
|
||||
@@ -419,7 +419,7 @@ extension TableRecord {
|
||||
/// }
|
||||
public static func select<RowDecoder>(sql: String, arguments: StatementArguments? = nil, as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder> {
|
||||
// TODO: make arguments non optional
|
||||
return all().select(SQLString(sql: sql, arguments: arguments ?? []), as: type)
|
||||
return all().select(SQLString(sql: sql, arguments: arguments ?? .init()), as: type)
|
||||
}
|
||||
|
||||
/// Creates a request which selects *sql*, and fetches values of
|
||||
@@ -509,9 +509,28 @@ extension TableRecord {
|
||||
/// all requests by the `TableRecord.databaseSelection` property, or
|
||||
/// for individual requests with the `TableRecord.select` method.
|
||||
public static func filter(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest<Self> {
|
||||
return all().filter(sql: sql, arguments: arguments)
|
||||
// TODO: make arguments non optional
|
||||
return filter(SQLString(sql: sql, arguments: arguments ?? .init()))
|
||||
}
|
||||
|
||||
/// Creates a request with the provided *predicate*.
|
||||
///
|
||||
/// // SELECT * FROM player WHERE email = 'arthur@example.com'
|
||||
/// let request = Player.filter(SQLString(sql: "email = ?", arguments: ["arthur@example.com"]))
|
||||
///
|
||||
/// With Swift 5, you can safely embed raw values in your SQL queries,
|
||||
/// without any risk of syntax errors or SQL injection:
|
||||
///
|
||||
/// let request = Player.filter(SQLString("email = \("arthur@example.com")))
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableRecord.databaseSelection` property, or
|
||||
/// for individual requests with the `TableRecord.select` method.
|
||||
public static func filter(_ sqlString: SQLString) -> QueryInterfaceRequest<Self> {
|
||||
// NOT TESTED
|
||||
return all().filter(sqlString)
|
||||
}
|
||||
|
||||
/// Creates a request sorted according to the
|
||||
/// provided *orderings*.
|
||||
///
|
||||
|
||||
@@ -53,7 +53,7 @@ extension SelectionRequest {
|
||||
/// .select(sql: "email")
|
||||
public func select(sql: String, arguments: StatementArguments? = nil) -> Self {
|
||||
// TODO: make arguments non optional
|
||||
return select(SQLString(sql: sql, arguments: arguments ?? []))
|
||||
return select(SQLString(sql: sql, arguments: arguments ?? .init()))
|
||||
}
|
||||
|
||||
/// Creates a request which selects *sql*.
|
||||
@@ -82,7 +82,8 @@ extension SelectionRequest {
|
||||
/// .select(...)
|
||||
/// .select(SQLString(sql: "email"))
|
||||
public func select(_ sqlString: SQLString) -> Self {
|
||||
return select(SQLSelectionLiteral(sqlString: sqlString))
|
||||
// NOT TESTED
|
||||
return select(SQLSelectionLiteral(sqlString))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -122,9 +123,32 @@ extension FilteredRequest {
|
||||
/// var request = Player.all()
|
||||
/// request = request.filter(sql: "email = ?", arguments: ["arthur@example.com"])
|
||||
public func filter(sql: String, arguments: StatementArguments? = nil) -> Self {
|
||||
return filter(SQLExpressionLiteral(sql, arguments: arguments))
|
||||
// TODO: make arguments non optional
|
||||
return filter(SQLString(sql: sql, arguments: arguments ?? .init()))
|
||||
}
|
||||
|
||||
/// Creates a request with the provided *predicate* added to the
|
||||
/// eventual set of already applied predicates.
|
||||
///
|
||||
/// // SELECT * FROM player WHERE email = 'arthur@example.com'
|
||||
/// var request = Player.all()
|
||||
/// request = request.filter(SQLString(sql: """
|
||||
/// email = ?
|
||||
/// """, arguments: ["arthur@example.com"])
|
||||
///
|
||||
/// With Swift 5, you can safely embed raw values in your SQL queries,
|
||||
/// without any risk of syntax errors or SQL injection:
|
||||
///
|
||||
/// // SELECT * FROM player WHERE email = 'arthur@example.com'
|
||||
/// var request = Player.all()
|
||||
/// request = request.filter(SQLString("""
|
||||
/// email = \("arthur@example.com")
|
||||
/// """)
|
||||
public func filter(_ sqlString: SQLString) -> Self {
|
||||
// NOT TESTED
|
||||
return filter(SQLExpressionLiteral(sqlString))
|
||||
}
|
||||
|
||||
/// Creates a request that matches nothing.
|
||||
///
|
||||
/// // SELECT * FROM player WHERE 0
|
||||
@@ -299,6 +323,13 @@ extension AggregatingRequest {
|
||||
|
||||
/// Creates a request with a new grouping.
|
||||
public func group(sql: String, arguments: StatementArguments? = nil) -> Self {
|
||||
// TODO: make arguments non optional
|
||||
return group(SQLString(sql: sql, arguments: arguments ?? .init()))
|
||||
}
|
||||
|
||||
/// Creates a request with a new grouping.
|
||||
public func group(_ sqlString: SQLString) -> Self {
|
||||
// NOT TESTED
|
||||
// This "expression" is not a real expression. We support raw sql which
|
||||
// actually contains several expressions:
|
||||
//
|
||||
@@ -307,15 +338,23 @@ extension AggregatingRequest {
|
||||
// This is why we use the "unsafe" flag, so that the SQLExpressionLiteral
|
||||
// does not output its safe wrapping parenthesis, and generates
|
||||
// invalid SQL.
|
||||
var expression = SQLExpressionLiteral(sql, arguments: arguments)
|
||||
var expression = SQLExpressionLiteral(sqlString)
|
||||
expression.unsafeRaw = true
|
||||
return group(expression)
|
||||
}
|
||||
|
||||
|
||||
/// Creates a request with the provided *sql* added to the
|
||||
/// eventual set of already applied predicates.
|
||||
public func having(sql: String, arguments: StatementArguments? = nil) -> Self {
|
||||
return having(SQLExpressionLiteral(sql, arguments: arguments))
|
||||
// TODO: make arguments non optional
|
||||
return having(SQLString(sql: sql, arguments: arguments ?? .init()))
|
||||
}
|
||||
|
||||
/// Creates a request with the provided *sql* added to the
|
||||
/// eventual set of already applied predicates.
|
||||
public func having(_ sqlString: SQLString) -> Self {
|
||||
// NOT TESTED
|
||||
return having(SQLExpressionLiteral(sqlString))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -405,6 +444,24 @@ extension OrderedRequest {
|
||||
/// .order(sql: "email")
|
||||
/// .order(sql: "name")
|
||||
public func order(sql: String, arguments: StatementArguments? = nil) -> Self {
|
||||
// TODO: make arguments non optional
|
||||
return order(SQLString(sql: sql, arguments: arguments ?? .init()))
|
||||
}
|
||||
|
||||
/// Creates a request with the provided *sql* used for sorting.
|
||||
///
|
||||
/// // SELECT * FROM player ORDER BY name
|
||||
/// var request = Player.all()
|
||||
/// request = request.order(sql: "name")
|
||||
///
|
||||
/// Any previous ordering is replaced:
|
||||
///
|
||||
/// // SELECT * FROM player ORDER BY name
|
||||
/// request
|
||||
/// .order(sql: "email")
|
||||
/// .order(sql: "name")
|
||||
public func order(_ sqlString: SQLString) -> Self {
|
||||
// NOT TESTED
|
||||
// This "expression" is not a real expression. We support raw sql which
|
||||
// actually contains several expressions:
|
||||
//
|
||||
@@ -413,7 +470,7 @@ extension OrderedRequest {
|
||||
// This is why we use the "unsafe" flag, so that the SQLExpressionLiteral
|
||||
// does not output its safe wrapping parenthesis, and generates
|
||||
// invalid SQL.
|
||||
var expression = SQLExpressionLiteral(sql, arguments: arguments)
|
||||
var expression = SQLExpressionLiteral(sqlString)
|
||||
expression.unsafeRaw = true
|
||||
return order([expression])
|
||||
}
|
||||
|
||||
@@ -1,16 +1,15 @@
|
||||
// MARK: - SQLExpression
|
||||
|
||||
extension SQLExpression {
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Converts an expression to an SQLExpressionLiteral
|
||||
/// Converts an expression to an SQLString
|
||||
///
|
||||
/// :nodoc:
|
||||
public var literal: SQLExpressionLiteral {
|
||||
public var sqlString: SQLString {
|
||||
var context = SQLGenerationContext.literalGenerationContext(withArguments: true)
|
||||
let sql = expressionSQL(&context)
|
||||
return SQLExpressionLiteral(sql, arguments: context.arguments)
|
||||
return SQLString(sql: sql, arguments: context.arguments!)
|
||||
}
|
||||
|
||||
/// The expression as a quoted SQL literal (not public in order to avoid abuses)
|
||||
@@ -35,16 +34,7 @@ extension SQLExpression {
|
||||
/// SQLExpressionLiteral("? + ?", arguments: [1, 2])
|
||||
/// SQLExpressionLiteral(":one + :two", arguments: ["one": 1, "two": 2])
|
||||
public struct SQLExpressionLiteral : SQLExpression {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// The SQL literal
|
||||
public let sql: String
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Eventual arguments that feed the `?` and colon-prefixed arguments in the
|
||||
/// SQL literal
|
||||
public let arguments: StatementArguments?
|
||||
private let sqlString: SQLString
|
||||
|
||||
/// If safe, an SQLExpressionLiteral("foo") wraps itself in parenthesis,
|
||||
/// and outputs "(foo)" in SQL queries. This avoids any bug due to operator
|
||||
@@ -60,24 +50,41 @@ public struct SQLExpressionLiteral : SQLExpression {
|
||||
/// SQLExpressionLiteral("? + ?", arguments: [1, 2])
|
||||
/// SQLExpressionLiteral(":one + :two", arguments: ["one": 1, "two": 2])
|
||||
public init(_ sql: String, arguments: StatementArguments? = nil) {
|
||||
self.sql = sql
|
||||
self.arguments = arguments
|
||||
// TODO: make arguments non optional
|
||||
// TODO: force sql parameter name: fetchCursor(db, sql:...)
|
||||
self.init(SQLString(sql: sql, arguments: arguments ?? .init()))
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Creates an SQL literal expression.
|
||||
///
|
||||
/// SQLExpressionLiteral(SQLString(sql: "1 + 2")
|
||||
/// SQLExpressionLiteral(SQLString(sql: "? + ?", arguments: [1, 2]))
|
||||
/// SQLExpressionLiteral(SQLString(sql: ":one + :two", arguments: ["one": 1, "two": 2]))
|
||||
///
|
||||
/// With Swift 5, you can safely embed raw values in your SQL queries,
|
||||
/// without any risk of syntax errors or SQL injection:
|
||||
///
|
||||
/// SQLExpressionLiteral(SQLString("\(1) + \(2)"))
|
||||
public init(_ sqlString: SQLString) {
|
||||
self.sqlString = sqlString
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func expressionSQL(_ context: inout SQLGenerationContext) -> String {
|
||||
if let arguments = arguments {
|
||||
if context.appendArguments(arguments) == false {
|
||||
if !sqlString.arguments.isEmpty {
|
||||
if context.appendArguments(sqlString.arguments) == false {
|
||||
// GRDB limitation: we don't know how to look for `?` in sql and
|
||||
// replace them with with literals.
|
||||
fatalError("Not implemented")
|
||||
}
|
||||
}
|
||||
if unsafeRaw {
|
||||
return sql
|
||||
return sqlString.sql
|
||||
} else {
|
||||
return "(" + sql + ")"
|
||||
return "(" + sqlString.sql + ")"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -26,23 +26,21 @@ public protocol SQLSelectable {
|
||||
// MARK: - SQLSelectionLiteral
|
||||
|
||||
struct SQLSelectionLiteral : SQLSelectable {
|
||||
private let sql: String
|
||||
private let arguments: StatementArguments
|
||||
private let sqlString: SQLString
|
||||
|
||||
init(sqlString: SQLString) {
|
||||
self.sql = sqlString.sql
|
||||
self.arguments = sqlString.arguments
|
||||
init(_ sqlString: SQLString) {
|
||||
self.sqlString = sqlString
|
||||
}
|
||||
|
||||
func resultColumnSQL(_ context: inout SQLGenerationContext) -> String {
|
||||
if !arguments.isEmpty {
|
||||
if context.appendArguments(arguments) == false {
|
||||
if !sqlString.arguments.isEmpty {
|
||||
if context.appendArguments(sqlString.arguments) == false {
|
||||
// GRDB limitation: we don't know how to look for `?` in sql and
|
||||
// replace them with with literals.
|
||||
fatalError("Not implemented")
|
||||
}
|
||||
}
|
||||
return sql
|
||||
return sqlString.sql
|
||||
}
|
||||
|
||||
func countedSQL(_ context: inout SQLGenerationContext) -> String {
|
||||
|
||||
@@ -219,7 +219,7 @@ extension FetchableRecord {
|
||||
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RecordCursor<Self> {
|
||||
// TODO: make arguments non optional
|
||||
// TODO: force sql parameter name: fetchCursor(db, sql:...)
|
||||
return try fetchCursor(db, SQLString(sql: sql, arguments: arguments ?? []), adapter: adapter)
|
||||
return try fetchCursor(db, SQLString(sql: sql, arguments: arguments ?? .init()), adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of records fetched from an SQL query.
|
||||
@@ -236,7 +236,7 @@ extension FetchableRecord {
|
||||
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] {
|
||||
// TODO: make arguments non optional
|
||||
// TODO: force sql parameter name: fetchCursor(db, sql:...)
|
||||
return try fetchAll(db, SQLString(sql: sql, arguments: arguments ?? []), adapter: adapter)
|
||||
return try fetchAll(db, SQLString(sql: sql, arguments: arguments ?? .init()), adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns a single record fetched from an SQL query.
|
||||
@@ -253,7 +253,7 @@ extension FetchableRecord {
|
||||
public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? {
|
||||
// TODO: make arguments non optional
|
||||
// TODO: force sql parameter name: fetchCursor(db, sql:...)
|
||||
return try fetchOne(db, SQLString(sql: sql, arguments: arguments ?? []), adapter: adapter)
|
||||
return try fetchOne(db, SQLString(sql: sql, arguments: arguments ?? .init()), adapter: adapter)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -70,9 +70,9 @@ class ColumnExpressionTests: GRDBTestCase {
|
||||
|
||||
// Test FTS3 match expression
|
||||
let expression = try Player.Columns.name.match(FTS3Pattern(rawPattern: "foo"))
|
||||
let literal = expression.literal
|
||||
XCTAssertEqual(literal.sql, "(\"name\" MATCH ?)")
|
||||
XCTAssertEqual(literal.arguments, ["foo"])
|
||||
let sqlString = expression.sqlString
|
||||
XCTAssertEqual(sqlString.sql, "(\"name\" MATCH ?)")
|
||||
XCTAssertEqual(sqlString.arguments, ["foo"])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -131,9 +131,9 @@ class ColumnExpressionTests: GRDBTestCase {
|
||||
|
||||
// Test FTS3 match expression
|
||||
let expression = try Player.Columns.name.match(FTS3Pattern(rawPattern: "foo"))
|
||||
let literal = expression.literal
|
||||
XCTAssertEqual(literal.sql, "(\"name\" MATCH ?)")
|
||||
XCTAssertEqual(literal.arguments, ["foo"])
|
||||
let sqlString = expression.sqlString
|
||||
XCTAssertEqual(sqlString.sql, "(\"name\" MATCH ?)")
|
||||
XCTAssertEqual(sqlString.arguments, ["foo"])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -180,9 +180,9 @@ class ColumnExpressionTests: GRDBTestCase {
|
||||
|
||||
// Test FTS3 match expression
|
||||
let expression = try Player.CodingKeys.name.match(FTS3Pattern(rawPattern: "foo"))
|
||||
let literal = expression.literal
|
||||
XCTAssertEqual(literal.sql, "(\"full_name\" MATCH ?)")
|
||||
XCTAssertEqual(literal.arguments, ["foo"])
|
||||
let sqlString = expression.sqlString
|
||||
XCTAssertEqual(sqlString.sql, "(\"full_name\" MATCH ?)")
|
||||
XCTAssertEqual(sqlString.arguments, ["foo"])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -40,14 +40,14 @@ func ~= (_ lhs: SQLExpressible, _ rhs: Column) -> SQLExpression {
|
||||
// CAST
|
||||
|
||||
func cast(_ value: SQLExpressible, as type: Database.ColumnType) -> SQLExpression {
|
||||
// Turn the value into a literal expression
|
||||
let literal: SQLExpressionLiteral = value.sqlExpression.literal
|
||||
// Turn the value into an SQLString
|
||||
let sqlString = value.sqlExpression.sqlString
|
||||
|
||||
// Build our "CAST(value AS type)" sql snippet
|
||||
let sql = "CAST(\(literal.sql) AS \(type.rawValue))"
|
||||
let sql = "CAST(\(sqlString.sql) AS \(type.rawValue))"
|
||||
|
||||
// And return a new literal expression, preserving input arguments
|
||||
return SQLExpressionLiteral(sql, arguments: literal.arguments)
|
||||
return SQLExpressionLiteral(SQLString(sql: sql, arguments: sqlString.arguments))
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user