Swiftpack.co - Package - VFK/SwiftyLMDB

SwiftyLMDB SPM Version

A wrapper for LMDB written in Swift for Package Manager.

Works everywhere where Swift is supported including Linux.

Usage

SwiftyLMDB works with Data types for keys and values. Let's say you have the following data:

let key = "master-key".data(using: .utf8)!
let value = "master-value".data(using: .utf8)!

You'll also need filesystem url to a file or a directory like:

let url = URL(fileURLWithPath: "/usr/local/some-database", isDirectory: true)

You can use it like this:

let lmdb = try SwiftyLMDB(url: url)
try lmdb.beginTransaction { database in
    try database.put(value: value, forKey: key)
    
    let dbValue = try database.get(key: key)
    
    try database.del(key: key)
}

Cursors are also supported:

let lmdb = try SwiftyLMDB(url: url)
try lmdb.beginTransactionWithCursor { database, cursor in
    try cursor.put(value: value, forKey: key)
    
    let dbValue = try cursor.get(.first)
    
    try cursor.del()
}
  • This library abstracts many things. You don't need to create environment, open a database and start/commit/abort transactions, this is all done for you.
  • You don't need to create intermediate directories in your path, those will be created if needed.
  • Successful transaction commits automatically and if something throws inside beginTransaction block - transaction aborts.
  • Some lmdb flags are set automatically: if url points to a file - MDB_NOSUBDIR will be set on environment. If you pass isReadOnly to SwiftyLMDB constructor - MDB_RDONLY flag will be added etc.

For named databases use beginTransaction(name: String?, flags: DatabaseFlags?) but also make sure to setMaxDbs to something >0 before this call like:

let lmdb = try SwiftyLMDB(url: url)

try lmdb.configureEnvironment { configuration in
    configuration.maxDbs = 1
}

try lmdb.beginTransaction(name: "my-database") { database in
    ...
}

Additionally direct mappings to lmdb methods are also provided

You can follow official guide and do things the way you'd them with the original lmdb library:

let url = URL(fileURLWithPath: "/usr/local/some-database", isDirectory: true)
let key = "master-key".data(using: .utf8)!
let value = "master-value".data(using: .utf8)!

let environment = try Environment(isReadOnly: false)
let transaction = Transaction(environment: environment, isReadOnly: false)
let database = Database(transaction: transaction)

try environment.setMaxDbs(10)
try environment.open(url: url, flags: [.noTls])
try database.open(name: "some-database", flags: [.dupSort])

try transaction.begin()
try database.put(value: value, forKey: key, flags: [.noDupData])
try transaction.commit()

Github

link
Stars: 0
Help us keep the lights on

Dependencies

Used By

Total: 0