ActiveSQLite is an helper of SQLite.Swift. It can let you use SQLite.swift easily.
There is a project named Reed downloader used ActiveSQLite.
To run the ActiveSQLiteTests target of project.
import ActiveSQLite
class Product:ASModel{
var name:String = ""
var price:NSNumber = NSNumber(value:0.0)
var desc:String?
var publish_date:NSDate?
}
//save
let product = Product()
product.name = "iPhone 7"
product.price = NSNumber(value:599)
try! product.save()
//Query
let p = Product.findFirst("name",value:"iPhone")
//or
let name = Expression<String>("name")
let p = Product.findAll(name == "iPhone").first
//id = 1, name = iPhone 7, price = 599, desc = nil, publish_date = nil, created_at = 1498616987587.237, updated_at = 1498616987587.237,
//Update
p.name = "iPad"
try! p.update()
//Delete
p.delete()
To use ActiveSQLite classes or structures in your target’s source file, first import the ActiveSQLite
module.
import ActiveSQLite
ASConfigration.setDefaultDB(path:"db file path", name: "default db name")
//If you want a other db
ASConfigration.setDB(path: "other db file path", name: "other db name")
You must set default db path.
ActiveSQLite Swift Type |
SQLite.swift Swift Type |
SQLite SQLite Type |
SQLite Default Value If not use optionl property |
---|---|---|---|
NSNumber |
Int64 |
INTEGER |
0 |
NSNumber |
Double |
REAL |
0.0 |
String |
String |
TEXT |
"" |
nil |
nil |
NULL |
NULL |
SQLite.Blob |
BLOB |
||
NSDate |
Int64 |
INTEGER |
0 |
The NSNumber Type maps with two SQLite.swift's Swift Type. they are Int64 ans Double. The default type is Int64. You can override doubleTypes() function of ASModel to mark properties are Double Type.
class Product:ASModel{
var name:String = ""
var price:NSNumber = NSNumber(value:0.0)
var desc:String?
var publish_date:NSDate?
override func doubleTypes() -> [String]{
return ["price"]
}
}
ActiviteSQLite map NSDate to Int64 of SQLite.swift. You can map NSDate to String by looking Custom Types of Documentaion of SQLite.swift
ActiveSQLite auto create table and add "id". The create code looks like below:
try db.run(products.create { t in
t.column(id, primaryKey: true)
t.column(Expression<NSDate>("created_at"), defaultValue: NSDate(timeIntervalSince1970: 0))
t.column(Expression<NSDate>("updated_at"), defaultValue: NSDate(timeIntervalSince1970: 0))
t.column(...)
})
// CREATE TABLE "Products" (
// "id" INTEGER PRIMARY KEY NOT NULL,
// created_at INTEGER DEFAULT (0),
// created_at INTEGER DEFAULT (0),
// ...
// )
The unit of "created_at" and "updated_at" columns is ms.
ActiveSQLite0.4.0 can use 3 types to define property: T, T!, T?.
ActiveSQLite0.4.1 use 2 types to define property: T, T?.
type | 0.4.0 | 0.4.1 |
---|---|---|
T |
not nil |
not nil |
T! |
not nil |
can be nil. use T? replace |
T? |
can be nil |
can be nil |
pirmary key id |
is T! type |
is T? type. |
If you want find the db column default value to see the first table in this document.
You can custom name of table, names of column and prevent save some properties into database.
If you use one db, only setDefaultDB(path:name:),, you needn't do anything. If you set you table in other db, you must override dbName.
ASConfigration.setDefaultDB(path:"db file path", name: "default db name")
ASConfigration.setDB(path: "other db file path", name: "other db name")
override class var dbName:String?{
return "other db name"
}
Default table name is same with class name, you needn't do anything. If you want use different name ,you must override nameOfTable.
// Set table name to "ProductTable"
override class var nameOfTable: String{
return "ProductTable"
}
Default column name is same with properity name, you needn't do anything. If you want use different name, you must override mapper().
override func mapper() -> [String:String]{
return ["property_name":"column_name"];
}
If you let primary key is not "id",use like this:
override class var PRIMARY_KEY:String{
return "_id"
}
override func mapper() -> [String:String]{
return ["id":"_id"]
}
Transent properitird have not been saved into database.
override class func transientTypess() -> [String]{
return ["isSelected"]
}
ActiveSQLite can only save properities in (String,NSNumber,NSDate) into database. The properities without in these types are not be saved into database, they are transent properities.
Just override isSaveDefaulttimestamp, don't do anything, the super class ASModel already define "created_at" and "updated_at" properies.
override class var isSaveDefaulttimestamp:Bool{
return true
}
If you want custom columns by yourself, you just set model implements CreateColumnsProtocol, and comfirm createColumns function. Then the ActiveSQLite will not auto create columns. Make sure the properties' names of model mapping the columns'.
class Users:ASModel,CreateColumnsProtocol{
var name:String = ""
var email:String = ""
var age:Int?
func createColumns(t: TableBuilder) {
t.column(Expression<NSNumber>("id"), primaryKey: true)
t.column(Expression<String>("name"),defaultValue:"Anonymous")
t.column(Expression<String>("email"), , check: email.like("%@%"))
}
}
find more infomations to look up table constraints document of SQLite.swift.
There are 3 functions used for insert rows. they are
Insert one.
func insert()throws ;
Insert more.
class func insertBatch(models:[ASModel])throws ;
Save method.
Insert or Update. Insert if id == nil. Update if id != nil.
func save() throws;
eg:
let u = Users()
u.name = "Kevin"
try! u.save()
var products = [Product]()
for i in 1 ..< 8 {
let p = Product()
p.name = "iPhone-\(i)"
p.price = NSNumber(value:i)
products.append(p)
}
try! Product.insertBatch(models: products)
For more to see source code or example of ActiveSQLite, also look up document Inserting Rows document of SQLite.swift.
There 3 strategies for update.
First modefiy attribute of model,and then save() or update() or updateBatch().
p.name = "zhoukai"
p.save()
//Update one
u.update("name",value:"3ds")
u.update(["name":"3ds","price":NSNumber(value:199)])
//Update more
Product.update(["name": "3ds","price":NSNumber(value:199)], where: ["id": NSNumber(1)])
Update one Product object to database.
//Update one
p.update([Product.price <- NSNumber(value:199))
//Update more
Product.update([Product.price <- NSNumber(value:199), where: Product.name == "3ds")
For more to see source code and example of ActiveSQLite, also look up document Updating Rows document , Setters document of SQLite.swift.
You can use findFirst to find one row, use findAll to find more rows.
The methods that prefix name is "find" are class method.
let p = Product.findFirst("name",value:"iWatch")
let ps = Product.findAll("name",value:"iWatch",orders:["price",false])
let id = Expression<NSNumber>("id")
let name = Expression<String>("name")
let arr = Product.findAll(name == "iWatch")
let ps = Product.findAll(id > NSNumber(value:100), orders: [Product.id.asc])
chainable query style methods are property method.
let products = Product().where(Expression<NSNumber>("code") > 3)
.order(Product.code)
.limit(5)
.run()
Don't forget excute run().
more complex queries to see source code and example of ActiveSQLite. Look documents Building Complex Queries of SQLite.swift
SQLite.swift use Expression replece 'where' SQL when you execute update and select SQLs. Complex Expression to look for filtering-rows
//1. Delete one row
try? product.delete()
//2. Delete all rows
try? Product.deleteAll()
//3. Delete by Expression and chains.
try? Product().where(Expression<NSNumber>("code") > 3)
.runDelete()
I suggest that you should put all insert, update, delete and alter tables codes into ActiveSQLite.save block. One block is a transaction.
ActiveSQLite.save({
var products = [Product]()
for i in 0 ..< 3 {
let p = Product()
p.name = "iPhone-\(i)"
p.price = NSNumber(value:i)
products.append(p)
}
try Product.insertBatch(models: products)
let u = Users()
u.name = "Kevin"
try u.save()
}, completion: { (error) in
if error != nil {
debugPrint("transtion failed \(error)")
}else{
debugPrint("transtion success")
}
})
ActiveSQLite.saveAsync also contains one transcation function.
ActiveSQLite.saveAsync({
.......
}, completion: { (error) in
......
})
class Product{
var name:String!
var newColumn:String!
override class var nameOfTable: String{
return "newTableName"
}
}
let db = DBConnection.sharedConnection.db
if db.userVersion == 0 {
ActiveSQLite.saveAsync({
try Product.renameTable(oldName:"oldTableName",newName:"newTableName")
try Product.addColumn(["newColumn"])
}, completion: { (error) in
if error == nil {
db.userVersion = 1
}
})
}
more to look Altering the Schema of SQLite.swift
let name = Expression<String>("name")
Product.createIndex(name)
Product.dropIndex(name)
more to see Indexes of SQLite.swift Document
Product.dropTable()
There are 4 log levels: debug,info,warn,error. The default log level is info. Setting log level like this:
//1. Set log level
ASConfigration.logLevel = .debug
//2. Set db path
ASConfigration.dbPath = "..."
Make sure setting log level before setting database path.
ActiveSQLite is available through CocoaPods. To install it, simply add the following line to your Podfile:
pod "ActiveSQLite"
Kevin Zhou
ActiveSQLite is available under the MIT license. See the LICENSE file for more info.