GRDB

A sqlite3 wrapper for Swift 2.

Goals

  • RAII
  • Leverage the Swift standard library (errors, generators, etc.)
  • Foster SQL
  • Focus on rows, not on tables.

Inspirations

Usage (work in progress)

// GRDB uses database queues just like ccgus/FMDB:

let dbQueue = try DatabaseQueue(path: "/tmp/GRDB.sqlite")


// Queues serialize database accesses:

try dbQueue.inDatabase { db -> Void in
  try db.execute(
      "CREATE TABLE persons (" +
      "id INTEGER PRIMARY KEY, " +
      "name TEXT, " +
      "age INT)")
}


// Transactions:

try dbQueue.inTransaction { db in
    try db.execute(
        "CREATE TABLE persons (" +
        "id INTEGER PRIMARY KEY, " +
        "name TEXT, " +
        "age INT)")
        
    try db.execute(
        "INSERT INTO persons (name, age) VALUES (?, ?)",
        bindings: ["Arthur", 36])
        
    try db.execute(
        "INSERT INTO persons (name, age) VALUES (:name, :age)",
        bindings: [":name": "Barbara", ":age": 37])
    
    return .Commit
}


// Fetching rows and values:

try dbQueue.inDatabase { db -> Void in
    for row in try db.fetchRows("SELECT * FROM persons") {
        // Leverage Swift type inference
        let name: String? = row.value(atIndex: 1)
        
        // Force unwrap when column is NOT NULL
        let id: Int64 = row.value(named: "id")!
        
        // Both Int and Int64 are supported
        let age: Int? = row.value(named: "age")
        
        print("id: \(id), name: \(name), age: \(age)")
    }
    
    // Value sequences require explicit `type` parameter
    for name in try db.fetchValues("SELECT name FROM persons", type: String.self) {
        // name is `String?` because some rows may have a NULL name.
        print(name)
    }
}


// Extracting values out of a database block:

let names = try dbQueue.inDatabase { db in
    try db.fetchValues("SELECT name FROM persons", type: String.self).map { $0! }
}
// names is [String]: ["Arthur", "Barbara"]

S
Description
Mirror of github.com/groue/GRDB.swift
Readme MIT
232 MiB
0 Stars 1 Watchers 0 Forks
Languages
Swift 99.4%
Ruby 0.3%
Makefile 0.2%
C 0.1%