AgileDB

CocoaPods

安装选项

入门指南

DBObject 协议

协议定义

public protocol DBObject: Codable {
    static var table: DBTable { get }
    var key: String { get set }
}

协议方法

/**
 Instantiate object and populate with values from the database, recursively if necessary. If instantiation fails, nil is returned.

 - parameter db: Database object holding the data.
 - parameter key: Key of the data entry.
*/
public init?(db: AgileDB, key: String) async

/**
 Save the object's encoded values to the database.

 - parameter db: Database object to hold the data.
 - parameter expiration: Optional Date specifying when the data is to be automatically deleted. Default value is nil specifying no automatic deletion.

 - returns: Discardable Bool value of a successful save.
*/
@discardableResult
public func save(to db: AgileDB, autoDeleteAfter expiration: Date? = nil) async -> Bool

/**
 Remove the object from the database

 - parameter db: Database object that holds the data. This does not delete nested objects.
 - returns: Discardable Bool value of a successful deletion.
*/
public func delete(from db: AgileDB) async -> Bool

/**
 Asynchronously instantiate object and populate with values from the database, recursively if necessary.

 - parameter db: Database object to hold the data.
 - parameter key: Key of the data entry.

 - returns: DBObject
 - throws: DBError
*/
public static func load(from db: AgileDB, for key: String) async throws -> Self

示例结构体

import AgileDB

enum Table: String {
    static let categories: DBTable = "Categories"
    static let accounts: DBTable = "Accounts"
    static let people: DBTable = "People"
}

struct Category: DBObject {
    static var table: DBTable { return Table.categories }
    var key = UUID().uuidString
    var accountKey = ""
    var name = ""
    var inSummary = true
}

// save to database
category.save(to: db)

// save to database, automatically delete after designated date
category.save(to: db, autoDeleteAfter: deletionDate)

// instantiate and pull from DB asynchronously
guard let category = await Category(db: db, key: categoryKey) else { return }

// delete from DB
category.delete(from: db)

DBResults 类

用法

guard let keys = db.keysInTable(Category.table) else { return }

let categories = DBResults<Category>(db: db, keys: keys)
    
for category in categories {
    // use category object
}
    
for index in 0..<categories.count {
    let category = categories[index]
    // use category object
}

发布者

用法

/**
Returns a  Publisher for generic DBResults. Uses the table of the DBObject for results.

- parameter sortOrder: Optional string that gives a comma delimited list of properties to sort by.
- parameter conditions: Optional array of DBConditions that specify what conditions must be met.
- parameter validateObjects: Optional bool that condition sets will be validated against the table. Any set that refers to json objects that do not exist in the table will be ignored. Default value is false.

- returns: DBResultssPublisher
*/

let publisher: DBResultsPublisher<Transaction> = db.publisher()
let _ = publisher.sink(receiveCompletion: { _ in }) { ( results) in
// assign to AnyCancellable property
}

底层方法

查看给定的表是否包含给定的键。

let table: DBTable = "categories"
if let hasKey = AgileDB.shared.tableHasKey(table:table, key:"category1") {
    // process here
    if hasKey {
        // table has key
    } else {
        // table didn't have key
    }
} else {
    // handle error
}

查看给定的表是否包含所有给定的键。

let table: DBTable = "categories"
if let hasKeys = AgileDB.shared.tableHasAllKeys(table:table, keys:["category1","category2","category3"]) {
    // process here
    if hasKeys {
        // table has all keys
    } else {
        // table didn't have key
    }
} else {
    // handle error
}

返回给定表中键的数组。 可以选择基于根级别的值指定排序顺序

let table: DBTable = "categories"
if let tableKeys = AgileDB.shared.keysInTable(table, sortOrder:"name, date desc") }
    // process keys
} else {
    // handle error
}

从给定表中返回按指定方式排序的与给定条件匹配的键的数组。

/**
All conditions in the same set are ANDed together. Separate sets are ORed against each other.  (set:0 AND set:0 AND set:0) OR (set:1 AND set:1 AND set:1) OR (set:2)

Unsorted Example:

let accountCondition = DBCondition(set:0,objectKey:"account",conditionOperator:.equal, value:"ACCT1")
if let keys = AgileDB.keysInTable("table1", sortOrder:nil, conditions:accountCondition) {
	// use keys
} else {
	// handle error
}

- parameter table: The DBTable to return keys from.
- parameter sortOrder: Optional string that gives a comma delimited list of properties to sort by.
- parameter conditions: Optional array of DBConditions that specify what conditions must be met.
- parameter validateObjects: Optional bool that condition sets will be validated against the table. Any set that refers to json objects that do not exist in the table will be ignored. Default value is false.

- returns: [String]? Returns an array of keys from the table. Is nil when database could not be opened or other error occured.

public func keysInTable(_ table: DBTable, sortOrder: String? = nil, conditions: [DBCondition]? = nil, validateObjects: Bool = false) -> [String]?
*/


let table: DBTable = "accounts"
let accountCondition = DBCondition(set:0,objectKey:"account", conditionOperator:.equal, value:"ACCT1")
if let keys = AgileDB.shared.keysInTable(table, sortOrder: nil, conditions: [accountCondition]) {
    // process keys
} else {
    // handle error
}

可以手动设置或检索数据,如此处所示,或者你的类/结构体可以遵循 DBObject 协议(如上所述),并使用内置的 init 和 save 方法,以获得更高的易用性和灵活性。

在表中设置值

let table: DBTable = "Transactions"
let key = UUID().uuidString
let dict = [
    "key": key
    , "accountKey": "Checking"
    , "locationKey" :"Kroger"
    , "categoryKey": "Food"
]

let data = try! JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)
let json = String(data: data, encoding: .utf8)!
// the key object in the json value is ignored in the setValue method
if AgileDB.shared.setValueInTable(table, for: key, to: json)
    // success
} else {
    // handle error
}

检索给定键的值

let table: DBTable = "categories"
if let jsonValue = AgileDB.shared.valueFromTable(table, for:"category1") {
    // process value
} else {
    // handle error
}

if let dictValue = AgileDB.shared.dictValueFromTable(table, for:"category1") {
    // process dictionary value
} else {
    // handle error
}

删除给定键的值

let table: DBTable = "categories"
if AgileDB.shared.deleteFromTable(table, for:"category1") {
    // value was deleted
} else {
    // handle error
}

异步检索数据

从 6.3 版本开始,AgileDB 允许使用 await 异步检索数据。

let db = AgileDB.shared
let table: DBTable = "categories"

do {
   let value = try await db.valueFromTable(table, for: key)
	
} catch {
}

可用的异步方法

SQL 查询

AgileDB 允许你执行标准 SQL select 以进行更复杂的查询。 由于给定的值实际上被分解为表中的单独列,因此可以传入标准 SQL 语句,并且可以选择返回行数组(值数组)。

let db = AgileDB.shared
let sql = "select name from accounts a inner join categories c on c.accountKey = a.key order by a.name"
if let results = db.sqlSelect(sql) {
    // process results
} else {
    // handle error
}

同步

通过在处理任何数据之前启用同步,然后共享同步日志,AgileDB 可以与其他自身的实例同步。

/**
Enables syncing. Once enabled, a log is created for all current values in the tables.

- returns: Bool If syncing was successfully enabled.
*/
public func enableSyncing() -> Bool


/**
Disables syncing.

- returns: Bool If syncing was successfully disabled.
*/
public func disableSyncing() -> Bool
    

/**
Read-only array of unsynced tables. Any tables not in this array will be synced.
*/
var unsyncedTables: [String]

/**
Sets the tables that are not to be synced.

- parameter tables: Array of tables that are not to be synced.

- returns: Bool If list was set successfully.
*/
public func setUnsyncedTables(_ tables: [String]) -> Bool


/**
Creates a sync file that can be used on another AgileDB instance to sync data. This is a synchronous call.

- parameter filePath: The full path, including the file itself, to be used for the log file.
- parameter lastSequence: The last sequence used for the given target  Initial sequence is 0.
- parameter targetDBInstanceKey: The dbInstanceKey of the target database. Use the dbInstanceKey method to get the DB's instanceKey.

- returns: (Bool,Int) If the file was successfully created and the lastSequence that should be used in subsequent calls to this instance for the given targetDBInstanceKey.
*/
public func createSyncFileAtURL(_ localURL: URL!, lastSequence: Int, targetDBInstanceKey: String) -> (Bool, Int)


/**
Processes a sync file created by another instance of AgileDB This is a synchronous call.

- parameter filePath: The path to the sync file.
- parameter syncProgress: Optional function that will be called periodically giving the percent complete.

- returns: (Bool,String,Int)  If the sync file was successfully processed,the instanceKey of the submiting DB, and the lastSequence that should be used in subsequent calls to the createSyncFile method of the instance that was used to create this file. If the database couldn't be opened or syncing hasn't been enabled, then the instanceKey will be empty and the lastSequence will be equal to zero.
*/
public typealias syncProgressUpdate = (_ percentComplete: Double) -> Void
public func processSyncFileAtURL(_ localURL: URL!, syncProgress: syncProgressUpdate?) -> (Bool, String, Int)

修订历史

6.5

6.4

6.3

6.2

6.1

6.0

5.1

5.0