SQLRequest

public struct SQLRequest<T> : FetchRequest

A FetchRequest built from raw SQL.

  • Declaration

    Swift

    public typealias RowDecoder = T
  • sql

    The raw SQL query

    let id = 42
    let request: SQLRequest<Player> = "SELECT * FROM player WHERE id = \(id)"
    request.sql // "SELECT * FROM player WHERE id = ?"
    

    Declaration

    Swift

    public var sql: String { get }
  • The request argument

    let id = 42
    let request: SQLRequest<Player> = "SELECT * FROM player WHERE id = \(id)"
    request.arguments // [42]
    

    Declaration

    Swift

    public var arguments: StatementArguments { get }
  • The request adapter

    Declaration

    Swift

    public var adapter: RowAdapter?
  • Creates a request from an SQL string, optional arguments, and optional row adapter.

    let request = SQLRequest<String>(sql: """
        SELECT name FROM player
        """)
    let request = SQLRequest<Player>(sql: """
        SELECT * FROM player WHERE id = ?
        """, arguments: [1])
    

    Declaration

    Swift

    public init(
        sql: String,
        arguments: StatementArguments = StatementArguments(),
        adapter: RowAdapter? = nil,
        cached: Bool = false)

    Parameters

    sql

    An SQL query.

    arguments

    Statement arguments.

    adapter

    Optional RowAdapter.

    cached

    Defaults to false. If true, the request reuses a cached prepared statement.

    Return Value

    A SQLRequest

  • Creates a request from an SQLLiteral, and optional row adapter.

    let request = SQLRequest<String>(literal: SQLLiteral(sql: """
        SELECT name FROM player
        """))
    let request = SQLRequest<Player>(literal: SQLLiteral(sql: """
        SELECT * FROM player WHERE name = ?
        """, arguments: ["O'Brien"]))
    

    With Swift 5, you can safely embed raw values in your SQL queries, without any risk of syntax errors or SQL injection:

    let request = SQLRequest<Player>(literal: """
        SELECT * FROM player WHERE name = \("O'brien")
        """)
    

    Declaration

    Swift

    public init(literal sqlLiteral: SQLLiteral, adapter: RowAdapter? = nil, cached: Bool = false)

    Parameters

    sqlLiteral

    An SQLLiteral.

    adapter

    Optional RowAdapter.

    cached

    Defaults to false. If true, the request reuses a cached prepared statement.

    Return Value

    A SQLRequest

  • Creates an SQL request from any other fetch request.

    Declaration

    Swift

    public init<Request>(
        _ db: Database,
        request: Request,
        cached: Bool = false)
        throws
        where Request: FetchRequest, Request.RowDecoder == RowDecoder

    Parameters

    db

    A database connection.

    request

    A request.

    cached

    Defaults to false. If true, the request reuses a cached prepared statement.

    Return Value

    An SQLRequest