SQLiteDB is a simple and lightweight SQLite wrapper for Swift

Overview

SQLiteDB

SQLiteDB is a simple and lightweight SQLite wrapper for Swift. It allows all basic SQLite functionality including being able to bind values to parameters in an SQL statement. You can either include an SQLite database file with your project (in case you want to pre-load data) and have it be copied over automatically in to your documents folder, or have the necessary database and the relevant table structures created automatically for you via SQLiteDB.

SQLiteDB also provides an SQLTable class which allows you to use SQLiteDB as an ORM so that you can define your table structures via SQLTable sub-classes and be able to access the underlying data directly instead of having to deal with SQL queries, parameters, etc.

Update: (28 Mar 2018) The latest version of SQLiteDB changes the openDB() method to open() and changes the parameters for the method as well. Please be aware of this change when updating an existing project. The open method parameters have default values which should work for most general cases - so you probably will not need to modify existing code except to change the method name.

The row(number:filter:order:type:) method now takes 0-based row numbers instead of 1-based. This change was made to be in line with how the row number is used in all the use cases I've seen up to now.

Also do not try to use the cloud database functionality available with the latest code since that is not yet ready for prime time - that code is still a work in progress. However, the rest of SQLiteDB code will function as it should without any issues.

Adding to Your Project

  • If you want to pre-load data or have the table structures and indexes pre-created, or, if you are not using SQLTable sub-classes but are instead using SQLiteDB directly, then you need to create an SQLite database file to be included in your project.

    Create your SQLite database however you like, but name it data.db and then add the data.db file to your Xcode project. (If you want to name the database file something other than data.db, then set the DB_NAME property in the SQLiteDB class accordingly.)

    Note: Remember to add the database file above to your application target when you add it to the project. If you don't add the database file to a project target, it will not be copied to the device along with the other project resources.

    If you do not want to pre-load data and are using SQLTable sub-classes to access your tables, you can skip the above step since SQLiteDB will automatically create your table structures for you if the database file is not included in the project. However, in order for this to work, you need to pass false as the parameter for the open method when you invoke it, like this:

    swift db.open(copyFile: false) ​

  • Add all of the included source files (except for README.md, of course) to your project.

  • If you don't have a bridging header file, use the included Bridging-Header.h file. If you already have a bridging header file, then copy the contents from the included Bridging-Header.h file to your own bridging header file.

  • If you didn't have a bridging header file, make sure that you modify your project settings to point to the new bridging header file. This will be under Build Settings for your target and will be named Objective-C Bridging Header.

  • Add the SQLite library (libsqlite3.dylib or libsqlite3.tbd, depending on your Xcode version) to your project under Build Phases - Link Binary With Libraries section.

That's it. You're set!

Usage

There are several ways you can use SQLiteDB in your project:

Basic - Direct

You can use the SQLiteBase class to open one or more SQLite databases directly by passing the path to the database file to the open method like this:

let db = SQLiteBase()
_ = db.open(dbPath: path)

You can then use the db instance to query the database. You can have multiple instances of SQLiteBase be in existence at the same time and point to different databases without any issues.

Basic - Singleton

You can use the SQLiteDB class, which is a singleton, to get a reference to one central database. Similar to the `SQLiteBase, instance above, you can then run queries (or execute statements) on the database using this reference.

Unlike with a SQLiteBase class instance, you cannot open multiple databases with SQLiteDB - it will only work with the database file specified via the DB_NAME property for the class.

  • You can gain access to the shared database instance as follows:
let db = SQLiteDB.shared
  • Before you make any SQL queries, or execute commands, you should open the SQLite database. In most cases, this needs to be done only once per application and so you can do it in your AppDelegate, for example:
db.open()
  • You can make SQL queries using the query method (the results are returned as an array of dictionaries where the key is a String and the value is of type Any):
let data = db.query(sql:"SELECT * FROM customers WHERE name='John'")
let row = data[0]
if let name = row["name"] {
	textLabel.text = name as! String
}

In the above, db is a reference to the shared SQLite database instance. You can access a column from your query results by subscripting a row of the returned results (the rows are dictionaries) based on the column name. That returns an optional Any value which you can cast to the relevant data type.

  • If you'd prefer to bind values to your query instead of creating the full SQL statement, then you can execute the above SQL also like this:
let name = "John"
let data = db.query(sql:"SELECT * FROM customers WHERE name=?", parameters:[name])
  • Of course, you can also construct the above SQL query by using Swift's string interpolation functionality as well (without using the SQLite bind functionality):
let name = "John"
let data = db.query(sql:"SELECT * FROM customers WHERE name='\(name)'")
  • You can execute all non-query SQL commands (INSERT, DELETE, UPDATE etc.) using the execute method:
let result = db.execute(sql:"DELETE FROM customers WHERE last_name='Smith'")
// If the result is 0 then the operation failed, for inserts the result gives the newly inserted record ID

Note: If you need to escape strings with embedded quotes, or other special strings which might not work with Swift string interpolation, you should use the SQLite parameter binding functionality as shown above.

Using SQLTable

If you would prefer to model your database tables as classes and do any data access via class instances instead of using SQL statements, SQLiteDB also provides an SQLTable class which does most of the heavy lifting for you.

If you create a sub-class of SQLTable, define properties where the names match the column names in your SQLite table, then you can use the sub-class to save to/update the database without having to write all the necessary boilerplate code yourself.

Additionally, with this approach, you don't need to include an SQLite database project with your app (unless you need/want to). Each SQLTable instance in your app will infer the structure for the underlying tables based on your SQLTable sub-classes and automatically create the necessary tables for you, if they aren't present.

In fact, while you develop your app, if you add new properties to your SQLTable sub-class instance, the necessary underlying SQLite columns will be added automatically to the database the next time the code is run. Again, SQLiteDB does all the work for you.

For example, say that you have a Categories table with just two columns - id and name. Then, the SQLTable sub-class definition for the table would look something like this:

class Category:SQLTable {
	var id = -1
	var name = ""
}

It's as simple as that! You don't have to write any insert, update, or delete methods since SQLTable handles all of that for you behind the scenese :) And on top of that, if you were to later add another property to the Category class later, say some sort of a usage count called count, that column would be added to the underlying table when you next run your code.

Note: Do note that for a table named Categories, the class has to be named Category - the table name has to be plural, and the class name has to be singular. The table names are plural while the classes are singular. Again, if you let SQLTable create the table structure for you, then it would all be handled correctly for you automatically. But if you create the tables yourself, do make sure that the table names are correct.

The only additional thing you need to do when you use SQLTable sub-classes and want the table structures to be automatically created for you is that you have to specify that you don't want to create a copy of a database in your project resources when you invoke open. So you have to have your open call be something like this:

db.open(copyFile:false)

Once you do that, you can run any SQL queries or execute commands on the database without any issues.

Here are some quick examples of how you use the Category class from the above example:

  • Add a new Category item to the table:
let category = Category()
category.name = "My New Category"
_ = category.save()

The save method returns a non-zero value if the save was successful. In the case of a new record, the return value is the id of the newly inserted row. You can check the return value to see if the save was sucessful or not since a 0 value means that the save failed for some reason.

  • Get a Category by id:
if let category = Category.rowBy(id: 10) {
	NSLog("Found category with ID = 10")
}
  • Query the Category table:
10") ">
let array = Category.rows(filter: "id > 10")
  • Get a specific Category row (to display categories via a UITableView, for example) by row number. The row numbers start at 0, the same as UITableView row indexes:
if let category = row(number: 0) {
	NSLog("Got first un-ordered category row")
}
  • Delete a Category:
if let category = Category.rowBy(id: 10) {
	category.delete()
	NSLog("Deleted category with ID = 10")
}

You can refer to the sample iOS and macOS projects for more examples of how to implement data access using SQLTable.

Questions?

SQLiteDB is under DWYWPL - Do What You Will Public License :) Do whatever you want either personally or commercially with the code but if you'd like, feel free to attribute in your app.

Comments
  • Dates

    Dates

    I notice that you're writing dates using NSDateFormatter. I'd really encourage you to specify a timezone for your formatter in case the timezone of the device changes at any point. As you've implemented the date logic, dates are stored in the device's then local time zone which can be problematic.

    I'd suggest

    • using a date formatter that specifies time zone (e.g. store date strings as Zulu/GMT/UTC, NSTimeZone(forSecondsFromGMT: 0) and include the timezone in the date string, e.g. Z; and
    • locale (e.g. the one used for RFC 3339/ISO8601 dates is NSLocale(localeIdentifier: "en_US_POSIX"); see Q&A 1480).

    You might even want to follow one of the established standards, such as ISO8601 format, e.g. 2015-02-03T15:29:00.000Z, in which the format is sortable and unambiguous.

    opened by robertmryan 7
  • Summer time zone

    Summer time zone

    Hi, I think there's a problem with datetime fields. I store a summer date (+3 in my country) 2017-06-15 02:00:00 +0000 and if i read it in winter (+2), i get 2017-06-15 01:00:00 +0000. If i store a winter date i get it back correctly, so somewhere at reading or writing i lose 1hr. I don't fully understand timezones but working with coredata i didn't had this problem. Do you know what might be the problem? Thanks.

    opened by cristibaluta 5
  • SQL don't found table Xcode 9

    SQL don't found table Xcode 9

    Hello. I have an issue,

    when I try to make a query, I got a response that has no such table found for example:

    SQLiteDB opened! 2017-08-08 09:40:02.072893-0300 AJ3[73215:8322823] SQLiteDB - failed to prepare SQL: SELECT * from servers, Error: no such table: servers

    but the data.db file is present and has the table servers. Could you help me with it?

    opened by jmanoel 5
  • Error handling while not initializing database

    Error handling while not initializing database

    If I didn't call OpenDB() before and want to execute a query, my app fails and it says "assertion failed: Database has not been opened! Use the openDB() method before any DB queries". I used do-catch and inside "do" I call db.execute(sql) but it failed again. How can I use d-catch to handle errors?

    opened by Rickrk 4
  • string primaryKey

    string primaryKey

    Hi, in the save method i noticed that the primary key is not unwrapped, so the query fails for optional string key.

    func save() -> Int { let db = SQLiteDB.shared! let key = primaryKey() let data = values() var insert = true if let rid = data[key] { var val = "(rid)" if let _rid = rid as? String { val = "'(_rid)'" }

    opened by cristibaluta 3
  • update affected rows bug

    update affected rows bug

    1. create table mytable(mykey INTEGER,myvalue INTEGER)
    2. insert into mytable("mykey","myvalue") values(100,10)
    3. update mytable set myvalue=20 where mykey=500 nothing is changed in the table (as expected), but the return value is 1 instead of 0 see SQLiteDB.swift: var cnt = sqlite3_changes(self.db)
    opened by amicwall 3
  • Is it possible? or how do I use a Decodable object with SQLTable?

    Is it possible? or how do I use a Decodable object with SQLTable?

    Hi,

    I like this wrapper it is very simple and lightweight but I am wondering about the following:

    I have the follwong decodable object so how can I use SQLTable with it? or do I need to create a seperate model for SQLTable?:-

    struct Chapter: Decodable { let chapter: Int }

    Thanks

    Wael

    opened by waelsaad 2
  • About migrating to Swift 3 or Swift 4

    About migrating to Swift 3 or Swift 4

    Hello Fahim!,

    First of all thank you very much for your fantastic library.. it helps me a lot. Right now I am developing an app that was made using phonegap and now I have the work to migrate the app to Swift 3.

    The app has this "migrationStore" where before launching the app it gathers all the information that was on the local database and uses it to generate a new CoreData model database..

    Until now was working just fine.

    This was the init process and an example of a method (previously working fine):

    private init(){
            if PHONEGAP_MIGRATION {
                db = SQLiteDB.sharedInstance("file__0.localstorage")
                //   db = SQLiteDB.openRO(path: "file__0.localstorage")
            }
        }
    
    public func getLocalStorageUrl() -> String{
            if PHONEGAP_MIGRATION {
                var url = [SQLRow]()
                url = db!.query("SELECT value FROM itemtable WHERE key = ?", parameters: [URL_FIELD])
                for v in url{
                    if let value = v["value"]{
                        return value.asString().stringByReplacingOccurrencesOfString("\"", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil).stringByReplacingOccurrencesOfString("\0", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
                    }
                }
                return NTXConfiguration.sharedInstance.serverUrl
            return ""
        }
    

    I am having problems to use the init() method using swift 3

    How can I open a database using a file name (string)?

    Thank you so much

    Regards

    opened by josmanperez 2
  • Error in Ipad IOS 10.1

    Error in Ipad IOS 10.1

    When I test my app on Ipad with the version IOS 10.1 shows an error

    let data = db.query(sql: "SELECT * FROM Catalog WHERE id=(id)") <--this line is null , in ihpone work fine

    func query(sql:String, parameters:[Any]?=nil)->[[String:Any]] { var rows = [String:Any] queue.sync() { if let stmt = self.prepare(sql:sql, params:parameters) { rows = self.query(stmt:stmt, sql:sql) } } return rows }

    my db file is on my folder path

    help me pleasee thank for your attention

    opened by gian123 2
  • Its not working with swift 2.0

    Its not working with swift 2.0

    "Cannot invoke initializer for type 'sqlite3_destructor_type'with an argument list of type '(COparquePointer)'

    for lines private let SQLITE_STATIC = sqlite3_destructor_type(COpaquePointer(bitPattern:0)) private let SQLITE_TRANSIENT = sqlite3_destructor_type(COpaquePointer(bitPattern:-1))

    on SQLiteDB.swift

    opened by yanctrindade 2
  • Close and Reopen Database

    Close and Reopen Database

    Hi Fahim, i've adapted your code for a new iOS project. Everything goes OK, but I have a problem when I want to reopen the database in another View.

    The first time it opens with no problem. I´m getting the data this way:

        let db = SQLiteDB.sharedInstance()
        let cursor = db.query("SELECT * FROM DATOS")
        db.closeDatabase()
    

    The I Close the View, and when I Try to reopen it, then it throws this error:

    SQLiteDB - failed to prepare SQL: SELECT * FROM DATOS, Error: library routine called out of sequence SQLiteDB - Launch count 482

    How can I do so I can open and close the database multiple times?

    opened by eamedina87 2
  • SQLTable (upgrading from Swift 3 to Swift 4)

    SQLTable (upgrading from Swift 3 to Swift 4)

    Using SQLTable to create the database in the app, I committed out the line // if copyFile { in SQLiteBase.swift such that the database would appear in the Documents directory (to view in SQLite Manager) and data would remain after first launch from Xcode. It was previously working correctly with the Swift 3 builds. Please advise.

    opened by ndgwv 0
Owner
Fahim Farook
Fahim Farook
GRDB - A toolkit for SQLite databases, with a focus on application development

A toolkit for SQLite databases, with a focus on application development Latest release: May 16, 2021 • version 5.8.0 • CHANGELOG • Migrating From GRDB

Gwendal Roué 5.6k Dec 30, 2022
Perfect - a Swift wrapper around the MySQL client library, enabling access to MySQL database servers.

Perfect - MySQL Connector This project provides a Swift wrapper around the MySQL client library, enabling access to MySQL database servers. This packa

PerfectlySoft Inc. 119 Dec 16, 2022
A stand-alone Swift wrapper around the libpq client library, enabling access to PostgreSQL servers.

Perfect - PostgreSQL Connector This project provides a Swift wrapper around the libpq client library, enabling access to PostgreSQL servers. This pack

PerfectlySoft Inc. 51 Nov 19, 2022
MySQL client library for Swift. This is inspired by Node.js' mysql.

mysql-swift MySQL client library for Swift. This is inspired by Node.js' mysql. Based on libmysqlclient Raw SQL query Simple query formatting and esca

Yusuke Ito 155 Nov 19, 2022
A Swift wrapper for SQLite databases

Squeal, a Swift interface to SQLite Squeal provides access to SQLite databases in Swift. Its goal is to provide a simple and straight-forward base API

Christian Niles 297 Aug 6, 2022
A stand-alone Swift wrapper around the SQLite 3 client library.

Perfect - SQLite Connector This project provides a Swift wrapper around the SQLite 3 library. This package builds with Swift Package Manager and is pa

PerfectlySoft Inc. 47 Nov 19, 2022
A Cocoa / Objective-C wrapper around SQLite

FMDB v2.7 This is an Objective-C wrapper around SQLite. The FMDB Mailing List: https://groups.google.com/group/fmdb Read the SQLite FAQ: https://www.s

August 13.7k Dec 28, 2022
SQLite.swift provides compile-time confidence in SQL statement syntax and intent.

SQLite.swift A type-safe, Swift-language layer over SQLite3. SQLite.swift provides compile-time confidence in SQL statement syntax and intent. Feature

Stephen Celis 8.7k Jan 8, 2023
SQLite.swift - A type-safe, Swift-language layer over SQLite3.

SQLite.swift provides compile-time confidence in SQL statement syntax and intent.

Stephen Celis 8.7k Jan 3, 2023
YapDB is a collection/key/value store with a plugin architecture. It's built atop sqlite, for Swift & objective-c developers.

YapDatabase is a collection/key/value store and so much more. It's built atop sqlite, for Swift & Objective-C developers, targeting macOS, iOS, tvOS &

Yap Studios 3.3k Dec 29, 2022
Swift APIs for SQLite: Type-safe down to the schema. Very, very, fast. Dependency free.

Lighter Lighter is a set of technologies applying code generation to access SQLite3 databases from Swift, e.g. in iOS applications or on the server. L

Lighter.swift 330 Dec 26, 2022
Realm is a mobile database: a replacement for Core Data & SQLite

Realm is a mobile database that runs directly inside phones, tablets or wearables. This repository holds the source code for the iOS, macOS, tvOS & wa

Realm 15.7k Jan 7, 2023
GRDB - A toolkit for SQLite databases, with a focus on application development

A toolkit for SQLite databases, with a focus on application development Latest release: May 16, 2021 • version 5.8.0 • CHANGELOG • Migrating From GRDB

Gwendal Roué 5.6k Dec 30, 2022
A toolkit for SQLite databases, with a focus on application development

A toolkit for SQLite databases, with a focus on application development

Gwendal Roué 5.6k Jan 8, 2023
Realm is a mobile database: a replacement for Core Data & SQLite

Realm is a mobile database that runs directly inside phones, tablets or wearables. This repository holds the source code for the iOS, macOS, tvOS & wa

Realm 15.7k Jan 1, 2023
Implement Student Admission System using SQlite

StudentAdmissionSQLiteApp Implement Student Admission System using SQlite. #Func

Hardik 2 Apr 27, 2022
BucketServer - Small API with SQLite database that saves notes for an iOS appliction called Bucket list

BucketList Server-Side Small API with SQLite database that saves notes for an iO

null 0 Dec 30, 2021
macOS Sqlite tableView 샘플 - objective c

목적 Objective C언어를 이용하여 macOS를 개발해본다. Sqlite를 이용하여 데이터를 저장하고, 불러와본다. FMDB를 이용한다. 데이터를 NSTableView를 이용하여 불러와본다. 추가적으로 NSOutlineView 구현해본다. 추가적으로 KVOCont

HyunSu Park 0 Jan 10, 2022
MagicData - A replacement of SQlite, CoreData or Realm.

MagicData A replacement of SQlite, CoreData or Realm. It is very easy to use and is a light version. Guides MagicData We use MagicData manage all the

Underthestars-zhy 20 Jul 4, 2022
CodeMirror-Swift is a lightweight wrapper of CodeMirror for macOS and iOS

CodeMirror-Swift is a lightweight wrapper of CodeMirror for macOS and iOS. Features ?? Lightweight CodeMirror wrapper (build 5.52.2) ✅ 100% Native Swi

Proxyman 86 Dec 30, 2022