diff --git a/GRDB/Configuration.swift b/GRDB/Configuration.swift index c6291a1e5..1a272049e 100644 --- a/GRDB/Configuration.swift +++ b/GRDB/Configuration.swift @@ -48,7 +48,7 @@ public struct Configuration { database is opened readonly. - parameter trace: An optional tracing function (default nil). - - returns: A Configuration + - returns: A Configuration. */ public init(foreignKeysEnabled: Bool = true, readonly: Bool = false, trace: TraceFunction? = nil) { self.foreignKeysEnabled = foreignKeysEnabled diff --git a/GRDB/Database.swift b/GRDB/Database.swift index 236d577dc..b4249e7df 100644 --- a/GRDB/Database.swift +++ b/GRDB/Database.swift @@ -22,67 +22,99 @@ // THE SOFTWARE. +/** +A Database connection. + +You don't create a database directly. Instead, you use a DatabaseQueue: + + let dbQueue = DatabaseQueue(...) + + // The Database is the `db` in the closure: + dbQueue.inDatabase { db in + db.execute(...) + } +*/ public final class Database { + // MARK: - Configuration + + /// The database configuration + public let configuration: Configuration + + + // MARK: - Select Statements + + /** + Returns a select statement that can be reused. + + let statement = db.selectStatement("SELECT * FROM persons WHERE id = ?") + + - parameter sql: An SQL query. + - parameter bindings: Optional bindings for query parameters. + - parameter unsafe: TODO. + + - returns: A SelectStatement. + */ + public func selectStatement(sql: String, bindings: Bindings? = nil, unsafe: Bool = false) throws -> SelectStatement { + return try SelectStatement(database: self, sql: sql, bindings: bindings, unsafe: unsafe) + } + + + // MARK: - Update Statements + + /** + Returns an update statement that can be reused. + + let statement = db.updateStatement("INSERT INTO persons (name) VALUES (?)") + + - parameter sql: An SQL query. + - parameter bindings: Optional bindings for query parameters. + + - returns: An UpdateStatement. + */ + public func updateStatement(sql: String, bindings: Bindings? = nil) throws -> UpdateStatement { + return try UpdateStatement(database: self, sql: sql, bindings: bindings) + } + + /** + Executes an update statement. + + db.excute("INSERT INTO persons (name) VALUES (?)", bindings: ["Arthur"]) + + - parameter sql: An SQL query. + - parameter bindings: Optional bindings for query parameters. + */ + public func execute(sql: String, bindings: Bindings? = nil) throws { + return try updateStatement(sql, bindings: bindings).execute() + } + + + // MARK: - Transactions + + /// A SQLite transaction type. See https://www.sqlite.org/lang_transaction.html public enum TransactionType { case Deferred case Immediate case Exclusive } - public let configuration: Configuration - let sqliteConnection = SQLiteConnection() - - init(path: String, configuration: Configuration) throws { - self.configuration = configuration - - // See https://www.sqlite.org/c3ref/open.html - let code = sqlite3_open_v2(path, &sqliteConnection, configuration.sqliteOpenFlags, nil) - try SQLiteError.checkCResultCode(code, sqliteConnection: sqliteConnection) - - if configuration.foreignKeysEnabled { - try execute("PRAGMA foreign_keys = ON") - } - } - - convenience init(configuration: Configuration) { - try! self.init(path: ":memory:", configuration: configuration) - } - - deinit { - if sqliteConnection != nil { - sqlite3_close(sqliteConnection) - } - } - - // MARK: - selectStatement - - public func selectStatement(sql: String, bindings: Bindings? = nil, unsafe: Bool = false) throws -> SelectStatement { - return try SelectStatement(database: self, sql: sql, bindings: bindings, unsafe: unsafe) - } - - - // MARK: - updateStatement - - public func updateStatement(sql: String, bindings: Bindings? = nil) throws -> UpdateStatement { - return try UpdateStatement(database: self, sql: sql, bindings: bindings) - } - - - // MARK: - execute - - public func execute(sql: String, bindings: Bindings? = nil) throws { - return try updateStatement(sql, bindings: bindings).execute() - } - - - // MARK: - transactions - + /// The end of a transaction: Commit, or Rollback public enum TransactionCompletion { case Commit case Rollback } + /** + Executes a block inside a SQLite transaction. + + If the block throws an error, the transaction is rollbacked and the error is + rethrown. + + - parameter type: The transaction type (default Exclusive) + See https://www.sqlite.org/lang_transaction.html + - parameter block: A function that executes SQL statements and return either + .Commit or .Rollback. + */ public func inTransaction(type: TransactionType = .Exclusive, block: () throws -> TransactionCompletion) throws { var completion: TransactionCompletion = .Rollback var dbError: ErrorType? = nil @@ -114,6 +146,57 @@ public final class Database { } } + + // MARK: - Miscellaneous + + /// The last inserted Row ID + public var lastInsertedRowID: Int64? { + let rowid = sqlite3_last_insert_rowid(sqliteConnection) + return rowid == 0 ? nil : rowid + } + + /** + Returns whether a table exists. + + - parameter tableName: A table name. + - returns: true if the table exists. + */ + public func tableExists(tableName: String) -> Bool { + if let _ = fetchOneRow("SELECT [sql] FROM sqlite_master WHERE [type] = 'table' AND LOWER(name) = ?", bindings: [tableName.lowercaseString]) { + return true + } else { + return false + } + } + + + // MARK: - Non public + + let sqliteConnection = SQLiteConnection() + + init(path: String, configuration: Configuration) throws { + self.configuration = configuration + + // See https://www.sqlite.org/c3ref/open.html + let code = sqlite3_open_v2(path, &sqliteConnection, configuration.sqliteOpenFlags, nil) + try SQLiteError.checkCResultCode(code, sqliteConnection: sqliteConnection) + + if configuration.foreignKeysEnabled { + try execute("PRAGMA foreign_keys = ON") + } + } + + // Initializes an in-memory database + convenience init(configuration: Configuration) { + try! self.init(path: ":memory:", configuration: configuration) + } + + deinit { + if sqliteConnection != nil { + sqlite3_close(sqliteConnection) + } + } + private func beginTransaction(type: TransactionType = .Exclusive) throws { switch type { case .Deferred: @@ -132,28 +215,15 @@ public final class Database { private func commit() throws { try execute("COMMIT TRANSACTION") } - - - // MARK: - - - public var lastInsertedRowID: Int64? { - let rowid = sqlite3_last_insert_rowid(sqliteConnection) - return rowid == 0 ? nil : rowid - } - - - // MARK: - - - public func tableExists(tableName: String) -> Bool { - let statement = try! selectStatement("SELECT [sql] FROM sqlite_master WHERE [type] = 'table' AND LOWER(name) = ?") - statement.bind(tableName.lowercaseString, atIndex: 1) - for _ in statement.fetchRows() { - return true - } - return false - } } +/** +Convenience function that calls fatalError in case of error + + let x = failOnError { + ... + } +*/ func failOnError(@noescape block: (Void) throws -> Result) -> Result { do { return try block() @@ -164,9 +234,24 @@ func failOnError(@noescape block: (Void) throws -> Result) -> Result { } } + +// MARK: - Feching Rows + +/** +The Database methods that fetch rows. +*/ extension Database { - // let rows = db.fetchRows("SELECT ...", bindings: ...) + /** + Fetches a lazy sequence of rows. + + let rows = db.fetchRows("SELECT ...") + + - parameter sql: An SQL query. + - parameter bindings: Optional bindings for query parameters. + + - returns: A lazy sequence of rows. + */ public func fetchRows(sql: String, bindings: Bindings? = nil) -> AnySequence { return failOnError { let statement = try selectStatement(sql, bindings: bindings) @@ -174,20 +259,54 @@ extension Database { } } - // let rows = db.fetchAllRows("SELECT ...", bindings: ...) + /** + Fetches an array of rows. + + let rows = db.fetchAllRows("SELECT ...") + + - parameter sql: An SQL query. + - parameter bindings: Optional bindings for query parameters. + + - returns: An array of rows. + */ public func fetchAllRows(sql: String, bindings: Bindings? = nil) -> [Row] { return Array(fetchRows(sql, bindings: bindings)) } - // let row = db.fetchOneRows("SELECT ...", bindings: ...) + /** + Fetches a single row. + + let row = db.fetchOneRow("SELECT ...") + + - parameter sql: An SQL query. + - parameter bindings: Optional bindings for query parameters. + + - returns: An optional row. + */ public func fetchOneRow(sql: String, bindings: Bindings? = nil) -> Row? { return fetchRows(sql, bindings: bindings).generate().next() } } + +// MARK: - Feching Values + +/** +The Database methods that fetch values. +*/ extension Database { - // let names = db.fetch(String.self, "SELECT name ...", bindings: ...) + /** + Fetches a lazy sequence of values. + + let names = db.fetch(String.self, "SELECT ...") + + - parameter type: The type of fetched values. It must adopt SQLiteValueConvertible. + - parameter sql: An SQL query. + - parameter bindings: Optional bindings for query parameters. + + - returns: A lazy sequence of values. + */ public func fetch(type: Value.Type, _ sql: String, bindings: Bindings? = nil) -> AnySequence { return failOnError { let statement = try selectStatement(sql, bindings: bindings) @@ -195,12 +314,33 @@ extension Database { } } - // let names = db.fetchAll(String.self, "SELECT name ...", bindings: ...) + /** + Fetches an array of values. + + let names = db.fetchAll(String.self, "SELECT ...") + + - parameter type: The type of fetched values. It must adopt SQLiteValueConvertible. + - parameter sql: An SQL query. + - parameter bindings: Optional bindings for query parameters. + + - returns: An array of values. + */ public func fetchAll(type: Value.Type, _ sql: String, bindings: Bindings? = nil) -> [Value?] { return Array(fetch(type, sql, bindings: bindings)) } - // let name = db.fetchOne(String.self, "SELECT name ...", bindings: ...) + + /** + Fetches a single value. + + let name = db.fetchOne(String.self, "SELECT ...") + + - parameter type: The type of fetched values. It must adopt SQLiteValueConvertible. + - parameter sql: An SQL query. + - parameter bindings: Optional bindings for query parameters. + + - returns: An optional value. + */ public func fetchOne(type: Value.Type, _ sql: String, bindings: Bindings? = nil) -> Value? { if let first = fetch(type, sql, bindings: bindings).generate().next() { // one row containing an optional value