ios - Creating custom sqlite functions in Swift alone -
how can custom sqlite function added in swift?
the following question addresses issue of using functions acos , cos in sqlite query involving coordinates: ios sqlite no such function: acos error
the suggestion add custom function. example given in objective-c. other bridging objective-c there native swift function or library allows creation of custom functions?
sqlite.swift provides type-safe swift interface creating custom sql functions (disclaimer: wrote , maintain sqlite.swift). current version bridges objective-c internally, though implementation detail can ignore. future version use swift 2's function pointer api. , while can use c function pointers in swift 1.x @objc_block
, unsafebitcast
, it's quite bit worse read , maintain.
the basic way create cos
function:
import sqlite import darwin // opens database connection let db = database() // defines "cos" function on connection db.create(function: "cos", argc: 1, deterministic: true) { args in if let x = args[0] as? double { return darwin.cos(x) } return nil } println(db.scalar("select cos(1.0)")) // optional(0.54030230586813977)
a more complex, safer example wherein sqlite.swift generates type-safe interface database given contract:
import sqlite import darwin // opens database connection let db = database() // defines "cos" function on connection let cos: expression<double> -> expression<double> = ( db.create(function: "cos", deterministic: true, darwin.cos) ) // builds sql expression column, "x" let x = expression<double>("x") // creates query reference table, "table" let table = db["table"] // creates table db.create(table: table) { t in t.column(x) } // create table "table" ("x" real) // inserts row "x" 1.0 table.insert(x <- 1.0) // insert "table" ("x") values (1.0) // executes query row in db.select(cos(x)) { println(row[cos(x)]) } // select "cos"("x") "table"
Comments
Post a Comment