Skip to content

Repository files navigation

SQLiteAdapter

SwiftPlatform

A simple wrapper around SQLite3.

Installation

Swift Package Manager

To install SQLiteAdapter using Swift Package Manager, add the following in your Package.swift:

dependencies:[.package(url:"https://github.com/denissimon/SQLiteAdapter.git", from:"0.8.1")]

Or through Xcode:

File -> Add Package Dependencies
Enter Package URL: https://github.com/denissimon/SQLiteAdapter

CocoaPods

To install SQLiteAdapter using CocoaPods, add this line to your Podfile:

pod'SQLiteAdapter','~> 0.8'

Carthage

To install SQLiteAdapter using Carthage, add this line to your Cartfile:

github"denissimon/SQLiteAdapter"

Manually

Copy folder SQLiteAdapter into your project.

Usage

Open the database

import SQLiteAdapter
// The sqlite file will be created if it does not already exist
guardlet dbPath =try?(FileManager.default.url(for:.documentDirectory, in:.userDomainMask, appropriateFor:nil, create:false).appendingPathComponent("db.sqlite")).path else{return}guardlet sqlite =try?SQLite(path: dbPath)else{return}print(sqlite.dbPath) // -> path of the sqlite file

When initializing SQLite with recreate: true, the sqlite file will be deleted and recreated.

Model and create a table

letsqlTable=SQLTable(
name:"ExampleTable",
columns:[("id",.INT),("json",.TEXT),("isDeleted",.BOOL),("updated",.DATE)],
primaryKey:"id" // "id" by default
)letstatementCreateTable=""" CREATE TABLE IF NOT EXISTS "\(sqlTable.name)"("\(sqlTable.primaryKey)" INTEGER NOT NULL,"json" TEXT NULL,"isDeleted" BOOLEAN DEFAULT 0 NOT NULL CHECK (isDeleted IN (0, 1)),"updated" DATETIME NOT NULL, PRIMARY KEY("\(sqlTable.primaryKey)" AUTOINCREMENT) );"""try? sqlite.createTable(sql: statementCreateTable)

SQL operations

Some examples of SQL operations:

do{varsql="INSERT INTO \(sqlTable.name) (json, updated) VALUES (?, ?);"try sqlite.insertRow(sql: sql, params:["someJson",Date()])
sql ="INSERT INTO \(sqlTable.name) (json, updated) VALUES (?, ?), (?, ?), (?, ?);"letdate=Date()let(changes, lastInsertID)=try sqlite.insertRow(sql: sql, params:[nil, date,nil, date,nil, date])assert((changes, lastInsertID)==(3,4))
sql ="UPDATE \(sqlTable.name) SET isDeleted = ?, updated = ? WHERE \(sqlTable.primaryKey) IN (2, 3)"try sqlite.updateRow(sql: sql, params:[true,Date()])assert(sqlite.changes ==2)
sql ="SELECT * FROM \(sqlTable.name) WHERE isDeleted = ?"iflet rows =try sqlite.getRow(from: sqlTable, sql: sql, params:[true]){assert(rows.count ==2)}try sqlite.deleteByID(in: sqlTable, id:2)try sqlite.deleteByID(in: sqlTable, id:3)letrowCount=try sqlite.getRowCount(in: sqlTable)assert(rowCount ==2)iflet row =try sqlite.getFirstRow(from: sqlTable){assert(row[0].value as!Int==1) // "id"
assert(row[1].value as?String=="someJson") // "json"
assert(row[2].value as!Bool==false) // "isDeleted"
}iflet row =try sqlite.getLastRow(from: sqlTable){assert(row[0].value as!Int==4) // "id"
assert(row[1].value as?String==nil) // "json"
assert(row[2].value as!Bool==false) // "isDeleted"
}}catch{print(error.localizedDescription)}

Read methods return nil if no rows have been read:

letrow=try sqlite.getByID(from: sqlTable, id:10) // -> nil

Insert, update, and delete methods return the number of changes made:

letchanges=try sqlite.deleteAllRows(in: sqlTable) // -> 2

Optional settings

sqlite.dateFormatter.locale =Locale(identifier:"en_US_POSIX")
sqlite.dateFormatter.timeZone =TimeZone(secondsFromGMT:0)
sqlite.dateFormatter.dateFormat ="yyyy-MM-dd HH:mm:ss"

More usage examples can be found in tests and iOS-MVVM-Clean-Architecture where this adapter was used.

Supported SQLite types

INT // Includes INT, INTEGER, INT2, INT8, BIGINT, MEDIUMINT, SMALLINT, TINYINT
BOOL // Includes BOOL, BOOLEAN, BIT
TEXT // Includes TEXT, CHAR, CHARACTER, VARCHAR, CLOB, VARIANT, VARYING_CHARACTER, NATIONAL_VARYING_CHARACTER, NATIVE_CHARACTER, NCHAR, NVARCHAR
REAL // Includes REAL, DOUBLE, FLOAT, NUMERIC, DECIMAL, DOUBLE_PRECISION
BLOB // Includes BLOB, BINARY, VARBINARY
DATE // Includes DATE, DATETIME, TIME, TIMESTAMP

Public methods

func createTable(sql:String)throwsfunc checkIfTableExists(_ table:SQLTable)throws-> Bool
func dropTable(_ table:SQLTable, vacuum:Bool)throwsfunc addIndex(to table:SQLTable, forColumn columnName:String, unique:Bool, order:SQLOrder)throwsfunc checkIfIndexExists(in table:SQLTable, indexName:String)throws-> Bool
func dropIndex(in table:SQLTable, forColumn columnName:String)throwsfunc beginTransaction()throwsfunc endTransaction()throwsfunc insertRow(sql:String, params:[Any]?)throws->(changes:Int, lastInsertID:Int)func updateRow(sql:String, params:[Any]?)throws->Intfunc deleteRow(sql:String, params:[Any]?)throws->Intfunc deleteByID(in table:SQLTable, id:Int)throws->Intfunc deleteAllRows(in table:SQLTable, vacuum:Bool, resetAutoincrement:Bool)throws->Intfunc getRowCount(in table:SQLTable)throws->Intfunc getRowCountWithCondition(sql:String, params:[Any]?)throws->Intfunc getRow(from table:SQLTable, sql:String, params:[Any]?)throws->[SQLValues]?func getAllRows(from table:SQLTable)throws->[SQLValues]?func getByID(from table:SQLTable, id:Int)throws->SQLValues?func getFirstRow(from table:SQLTable)throws->SQLValues?func getLastRow(from table:SQLTable)throws->SQLValues?func vacuum()throwsfunc query(sql:String, params:[Any]?)throws->Int

License

Licensed under the MIT license

Releases

Packages

Contributors

Languages