#if !USING_BUILTIN_SQLITE #if os(OSX) import SQLiteMacOSX #elseif os(iOS) #if (arch(i386) || arch(x86_64)) import SQLiteiPhoneSimulator #else import SQLiteiPhoneOS #endif #elseif os(watchOS) #if (arch(i386) || arch(x86_64)) import SQLiteWatchSimulator #else import SQLiteWatchOS #endif #endif #endif // MARK: - SQLExpressible /// The protocol for all types that can be turned into an SQL expression. /// /// It is adopted by protocols like DatabaseValueConvertible, and types /// like Column. /// /// See https://github.com/groue/GRDB.swift/#the-query-interface public protocol SQLExpressible { /// Returns an SQLExpression /// /// See https://github.com/groue/GRDB.swift/#the-query-interface var sqlExpression: SQLExpression { get } } // MARK: - DatabaseValueConvertible /// Types that adopt DatabaseValueConvertible can be initialized from /// database values. /// /// The protocol comes with built-in methods that allow to fetch cursors, /// arrays, or single values: /// /// try String.fetchCursor(db, "SELECT name FROM ...", arguments:...) // DatabaseCursor /// try String.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String] /// try String.fetchOne(db, "SELECT name FROM ...", arguments:...) // String? /// /// let statement = try db.makeSelectStatement("SELECT name FROM ...") /// try String.fetchCursor(statement, arguments:...) // DatabaseCursor /// try String.fetchAll(statement, arguments:...) // [String] /// try String.fetchOne(statement, arguments:...) // String? /// /// DatabaseValueConvertible is adopted by Bool, Int, String, etc. public protocol DatabaseValueConvertible : SQLExpressible { /// Returns a value that can be stored in the database. var databaseValue: DatabaseValue { get } /// Returns a value initialized from *databaseValue*, if possible. static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? } // SQLExpressible adoption extension DatabaseValueConvertible { /// This property is an implementation detail of the query interface. /// Do not use it directly. /// /// See https://github.com/groue/GRDB.swift/#the-query-interface /// /// # Low Level Query Interface /// /// See SQLExpression.sqlExpression public var sqlExpression: SQLExpression { return databaseValue } } /// DatabaseValueConvertible comes with built-in methods that allow to fetch /// cursors, arrays, or single values: /// /// try String.fetchCursor(db, "SELECT name FROM ...", arguments:...) // DatabaseCursor /// try String.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String] /// try String.fetchOne(db, "SELECT name FROM ...", arguments:...) // String? /// /// let statement = try db.makeSelectStatement("SELECT name FROM ...") /// try String.fetchCursor(statement, arguments:...) // DatabaseCursor /// try String.fetchAll(statement, arguments:...) // [String] /// try String.fetchOne(statement, arguments:...) // String /// /// DatabaseValueConvertible is adopted by Bool, Int, String, etc. extension DatabaseValueConvertible { // MARK: Fetching From SelectStatement /// Returns a cursor over values fetched from a prepared statement. /// /// let statement = try db.makeSelectStatement("SELECT name FROM ...") /// let names = try String.fetchCursor(statement) // DatabaseCursor /// while let name = try names.next() { // String /// ... /// } /// /// If the database is modified during the cursor iteration, the remaining /// elements are undefined. /// /// The cursor must be iterated in a protected dispath queue. /// /// - parameters: /// - statement: The statement to run. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor { // Reuse a single mutable row for performance let row = try Row(statement: statement).adaptedRow(adapter: adapter, statement: statement) return statement.fetchCursor(arguments: arguments) { () -> Self in let dbv: DatabaseValue = row.value(atIndex: 0) if let value = Self.fromDatabaseValue(dbv) { return value } else { throw DatabaseError(code: SQLITE_ERROR, message: "could not convert database value \(dbv) to \(Self.self)", sql: statement.sql, arguments: arguments) } } } /// Returns an array of values fetched from a prepared statement. /// /// let statement = try db.makeSelectStatement("SELECT name FROM ...") /// let names = try String.fetchAll(statement) // [String] /// /// - parameters: /// - statement: The statement to run. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter /// - returns: An array. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] { return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter)) } /// Returns a single value fetched from a prepared statement. /// /// The result is nil if the query returns no row, or if no value can be /// extracted from the first row. /// /// let statement = try db.makeSelectStatement("SELECT name FROM ...") /// let name = try String.fetchOne(statement) // String? /// /// - parameters: /// - statement: The statement to run. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter /// - returns: An optional value. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? { // Reuse a single mutable row for performance let row = try Row(statement: statement).adaptedRow(adapter: adapter, statement: statement) let cursor = statement.fetchCursor(arguments: arguments) { () -> Self? in let dbv: DatabaseValue = row.value(atIndex: 0) if let value = Self.fromDatabaseValue(dbv) { return value } else if dbv.isNull { return nil } else { throw DatabaseError(code: SQLITE_ERROR, message: "could not convert database value \(dbv) to \(Self.self)", sql: statement.sql, arguments: arguments) } } return try cursor.next() ?? nil } } extension DatabaseValueConvertible { // MARK: Fetching From FetchRequest /// Returns a cursor over values fetched from a fetch request. /// /// let nameColumn = Column("name") /// let request = Person.select(nameColumn) /// let names = try String.fetchCursor(db, request) // DatabaseCursor /// for let name = try names.next() { // String /// ... /// } /// /// If the database is modified during the cursor iteration, the remaining /// elements are undefined. /// /// The cursor must be iterated in a protected dispath queue. /// /// - parameters: /// - db: A database connection. /// - request: A fetch request. /// - returns: A cursor over fetched values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, _ request: FetchRequest) throws -> DatabaseCursor { let (statement, adapter) = try request.prepare(db) return try fetchCursor(statement, adapter: adapter) } /// Returns an array of values fetched from a fetch request. /// /// let nameColumn = Column("name") /// let request = Person.select(nameColumn) /// let names = try String.fetchAll(db, request) // [String] /// /// - parameter db: A database connection. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll(_ db: Database, _ request: FetchRequest) throws -> [Self] { let (statement, adapter) = try request.prepare(db) return try fetchAll(statement, adapter: adapter) } /// Returns a single value fetched from a fetch request. /// /// The result is nil if the query returns no row, or if no value can be /// extracted from the first row. /// /// let nameColumn = Column("name") /// let request = Person.select(nameColumn) /// let name = try String.fetchOne(db, request) // String? /// /// - parameter db: A database connection. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchOne(_ db: Database, _ request: FetchRequest) throws -> Self? { let (statement, adapter) = try request.prepare(db) return try fetchOne(statement, adapter: adapter) } } extension DatabaseValueConvertible { // MARK: Fetching From SQL /// Returns a cursor over values fetched from an SQL query. /// /// let names = try String.fetchCursor(db, "SELECT name FROM ...") // DatabaseCursor /// while let name = try name.next() { // String /// ... /// } /// /// If the database is modified during the cursor iteration, the remaining /// elements are undefined. /// /// The cursor must be iterated in a protected dispath queue. /// /// - parameters: /// - db: A database connection. /// - sql: An SQL query. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor { return try fetchCursor(db, SQLFetchRequest(sql: sql, arguments: arguments, adapter: adapter)) } /// Returns an array of values fetched from an SQL query. /// /// let names = try String.fetchAll(db, "SELECT name FROM ...") // [String] /// /// - parameters: /// - db: A database connection. /// - sql: An SQL query. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter /// - returns: An array. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] { return try fetchAll(db, SQLFetchRequest(sql: sql, arguments: arguments, adapter: adapter)) } /// Returns a single value fetched from an SQL query. /// /// The result is nil if the query returns no row, or if no value can be /// extracted from the first row. /// /// let name = try String.fetchOne(db, "SELECT name FROM ...") // String? /// /// - parameters: /// - db: A database connection. /// - sql: An SQL query. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter /// - returns: An optional value. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? { return try fetchOne(db, SQLFetchRequest(sql: sql, arguments: arguments, adapter: adapter)) } } /// Swift's Optional comes with built-in methods that allow to fetch cursors /// and arrays of optional DatabaseValueConvertible: /// /// try Optional.fetchCursor(db, "SELECT name FROM ...", arguments:...) // DatabaseCursor /// try Optional.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String?] /// /// let statement = try db.makeSelectStatement("SELECT name FROM ...") /// try Optional.fetchCursor(statement, arguments:...) // DatabaseCursor /// try Optional.fetchAll(statement, arguments:...) // [String?] /// /// DatabaseValueConvertible is adopted by Bool, Int, String, etc. extension Optional where Wrapped: DatabaseValueConvertible { // MARK: Fetching From SelectStatement /// Returns a cursor over optional values fetched from a prepared statement. /// /// let statement = try db.makeSelectStatement("SELECT name FROM ...") /// let names = try Optional.fetchCursor(statement) // DatabaseCursor /// while let name = try names.next() { // String? /// ... /// } /// /// If the database is modified during the cursor iteration, the remaining /// elements are undefined. /// /// The cursor must be iterated in a protected dispath queue. /// /// - parameters: /// - statement: The statement to run. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor { // Reuse a single mutable row for performance let row = try Row(statement: statement).adaptedRow(adapter: adapter, statement: statement) return statement.fetchCursor(arguments: arguments) { () -> Wrapped? in let dbv: DatabaseValue = row.value(atIndex: 0) if let value = Wrapped.fromDatabaseValue(dbv) { return value } else if dbv.isNull { return nil } else { throw DatabaseError(code: SQLITE_ERROR, message: "could not convert database value \(dbv) to \(Wrapped.self)", sql: statement.sql, arguments: arguments) } } } /// Returns an array of optional values fetched from a prepared statement. /// /// let statement = try db.makeSelectStatement("SELECT name FROM ...") /// let names = try Optional.fetchAll(statement) // [String?] /// /// - parameters: /// - statement: The statement to run. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter /// - returns: An array of optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] { return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter)) } } extension Optional where Wrapped: DatabaseValueConvertible { // MARK: Fetching From FetchRequest /// Returns a cursor over optional values fetched from a fetch request. /// /// let nameColumn = Column("name") /// let request = Person.select(nameColumn) /// let names = try Optional.fetchCursor(db, request) // DatabaseCursor /// while let name = try names.next() { // String? /// ... /// } /// /// If the database is modified during the cursor iteration, the remaining /// elements are undefined. /// /// The cursor must be iterated in a protected dispath queue. /// /// - parameters: /// - db: A database connection. /// - requet: A fetch request. /// - returns: A cursor over fetched optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, _ request: FetchRequest) throws -> DatabaseCursor { let (statement, adapter) = try request.prepare(db) return try fetchCursor(statement, adapter: adapter) } /// Returns an array of optional values fetched from a fetch request. /// /// let nameColumn = Column("name") /// let request = Person.select(nameColumn) /// let names = try Optional.fetchAll(db, request) // [String?] /// /// - parameter db: A database connection. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll(_ db: Database, _ request: FetchRequest) throws -> [Wrapped?] { let (statement, adapter) = try request.prepare(db) return try fetchAll(statement, adapter: adapter) } } extension Optional where Wrapped: DatabaseValueConvertible { // MARK: Fetching From SQL /// Returns a cursor over optional values fetched from an SQL query. /// /// let names = try Optional.fetchCursor(db, "SELECT name FROM ...") // DatabaseCursor /// while let name = try names.next() { // String? /// ... /// } /// /// If the database is modified during the cursor iteration, the remaining /// elements are undefined. /// /// The cursor must be iterated in a protected dispath queue. /// /// - parameters: /// - db: A database connection. /// - sql: An SQL query. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter /// - returns: A cursor over fetched optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor { return try fetchCursor(db, SQLFetchRequest(sql: sql, arguments: arguments, adapter: adapter)) } /// Returns an array of optional values fetched from an SQL query. /// /// let names = try String.fetchAll(db, "SELECT name FROM ...") // [String?] /// /// - parameters: /// - db: A database connection. /// - sql: An SQL query. /// - parameter arguments: Optional statement arguments. /// - adapter: Optional RowAdapter /// - returns: An array of optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] { return try fetchAll(db, SQLFetchRequest(sql: sql, arguments: arguments, adapter: adapter)) } }