When passing nil as the path, the SQLContext will reside entirely in memory, and will not persist once the context is closed. This can be useful for unit testing and performing in-memory calculations, or as a temporary engine for calculations and sorting.
import SkipSQLCore
import SkipSQL
let ctx =trySQLContext(path: nil, configuration: .platform)
defer { ctx.close() }
let rows: [[SQLValue]] = ctx.selectAll(sql: "SELECT 1, 1.1+2.2, 'AB'||'C'")
Performing multiple operations in the context of a transaction will ensure that either all the operations succeed (COMMIT) or fail (ROLLBACK) together.
try ctx.transaction {
try ctx.exec(sql: "INSERT INTO TABLE_NAME VALUES(1)")
try ctx.exec(sql: "INSERT INTO TABLE_NAME VALUES(2)")
}
The default transaction type is .deferred, but it can be specified as a parameter to transaction to override the default, or nil to perform the operation without a transaction.
SkipSQL provides built-in support for version-based schema migrations using SQLite’s userVersion pragma. The migrate() method accepts an array of migration closures, each representing a schema version. Only migrations that haven’t been applied yet will run, each within its own transaction:
try ctx.migrate(migrations: [
// Version 1: initial schema
{ ctx in
try ctx.exec(sql: "CREATE TABLE DATA_ITEM (ID INTEGER PRIMARY KEY AUTOINCREMENT)")
Each migration runs in a transaction and increments userVersion upon success. If a migration fails, it rolls back without affecting subsequent migrations. You can safely add new closures to the end of the array as your schema evolves — previously applied migrations are skipped.
As a thin layer over a SQLite connection, SkipSQL itself performs no locking or manages threads in any way. It is up to the application layer to set up reader/writer locks, or else just perform all the operations in an isolated context (e.g., using an actor).
SkipSQL includes a simple mechanism for mapping Swift types to tables through the SQLCodable protocol and SQLTable and SQLColumn types. An example of a type that implements this is:
/// A struct that can read and write its values to the `DEMO_TABLE` table.
publicstruct DemoTable : SQLCodable, Equatable {
publicvar id: Int64
staticlet id =SQLColumn(name: "ID", type: .long, primaryKey: true, autoincrement: true)
/// Encode the current instance into the given `SQLRow` dictionary.
publicfuncencode(row: inout SQLRow)throws {
row[Self.id] =SQLValue(self.id)
row[Self.txt] =SQLValue(self.txt)
row[Self.num] =SQLValue(self.num)
row[Self.int] =SQLValue(self.int)
row[Self.dbl] =SQLValue(self.dbl)
row[Self.blb] =SQLValue(self.blb)
}
}
The init and encode implementations can be used to coerce the primitive SQLite value types into other Swift types. For example, to have a UUID property, you might implement it like:
SkipSQL supports primary keys that work with SQLite’s ROWID mechanism,
such that when an INTEGER column (i.e., SQLValue.long) is the primary
key, the same storage is used as the underlying ROWID that all tables
automatically have (see
ROWIDs and the INTEGER PRIMARY KEY ↗).
The property should be either an optional Int64?, or if it marked with
autoincrement: true and the type is a non-optional Int64, then inserting
a value with the id property set to 0 will automatically assign the
primary key when .insert(ob) is called. This enables a table to
have a required primary key (which is useful when implementing Identifiable)
with the special sentinal value of 0 that indicates that it is a new instance.
publicvar id: Int64
staticlet id =SQLColumn(name: "ID", type: .long, primaryKey: true, autoincrement: true)
If the primary key is not marked with autoincrement: true and the
property is not optional, then it is assumed that the primary key
is manually assigned by the developer and care must be taken to
ensure that duplicate values are not inserted.
SQLite does not have any dedicated column type that handles date fields
(see Date And Time Functions ↗),
but it can handle dates encoded either as a ISO-8601 string in a column
of type TEXT, or in a numeric column containing the number of seconds since January 1, 1970.
SkipSQL is not a complete object-relational mapping (ORM) package,
but it does contain the ability to perform joins across multiple
SQLCodable tables when one of the SQLColumn definitions
includes a SQLForeignKey.
/// A struct that can read and write its values to the `DEMO_TABLE` table.
publicstruct DemoParent : SQLCodable {
publicvar id: Int64
staticlet id =SQLColumn(name: "ID", type: .long, primaryKey: true, autoincrement: true)
// perform a join between all the parents and children
let joined2: [(DemoParent?, DemoChild?)] =try sqlite.query(DemoParent.self, alias: "t0")
.join(DemoChild.self, "t1", kind: .inner, on: DemoChild.parentID)
.eval()
.load()
This operation will perform a one-to-many inner join from the DemoParent
to the DemoChild tables, and return a list of tuples between the matching
instances. Note that the tuple values are types as optionals, because for
outer join types, it is possible to have empty rows, which would map to
nil values.
SkipSQL speaks directly to the low-level SQLite3 C library that is pre-installed on all iOS and Android devices.
On Darwin/iOS, and with SkipFuse on Android, it communicates directly through Swift’s C integration.
With transpiled SkipLite on Android, it uses the SkipFFI module to interact directly with the underlying sqlite installation on Android for SkipSQL, or with the locally-built SQLite that is packages and bundled with the application as a shared object file.
Note that for performance and a consistent API, SkipSQL eschews Android’s android.database.sqlite Java wrapper, and instead uses the same SQLite C API on both Android and Darwin platforms.
Because SkipSQL uses the version of SQLite that is shipped with the platform, care should be taken when using recent SQLite features, such as the json ↗ function, which is new in SQLite 3.38. This would raise an error on Android versions below 14.0 (API 34) and iOS versions below 16.0.
Be aware that some very useful SQL features may only have been added to more recent versions of SQLite, such as strict tables (added in 3.37). This may impact the Android API version you can deploy back to, so be sure to test your code on the oldest available Android emulator and iOS simulator for your project.
Also be aware that the availability of some SQL features are contingent on the compile flags used to build the vendored sqlite implementation provided as part of the OS, such as SQLITE_ENABLE_JSON1 enabling the various json_ ↗ operations. In the case of Android, be aware that local Robolectric testing will be insufficient to identify any limitations resulting from sqlite compile flags, since local testing will use the local (i.e., macOS-vendored) version of SQLite. Testing against an Android emulator (or device) should be performed when developing new SQL operations.
OS Version
SQLite Version
Android 9 (API 28)
3.22
iOS 13
3.28
Android 10 (API 30)
3.28
iOS 14
3.32
Android 11 (API 31)
3.32
Android 12 (API 32)
3.32
Android 13 (API 33)
3.32
iOS 15
3.36
iOS 16
3.39
Android 14 (API 34)
3.39
Android 15 (API 35)
3.44
SQLPlus
3.50
Android 16 (API 36)
3.50
Note that as cautioned in the Android documentation ↗, some Android device manufacturers include different versions of SQLite on their devices, so if your app depends on a SQLite version that may not be available on a device that your app supports, you may want to consider using SQLPlus instead.
The skip-sql framework includes an additional SQLPlus module,
which creates a local build with the following extensions enabled:
Full Text Search (FTS)
Encryption (sqlcipher)
The SQLPlus module uses sqlite version 3.50.4, which means
that it will be safe to use newer sqlite features like
the json ↗ function,
RIGHT and FULL outer joins, and full text search,
regardless of the Android API and iOS versions of the
deployment platform.
This comes at the cost of additional build time for the native libraries,
as well as a larger artifact size (around 1MB on iOS and 4MB on Android),
but has the benefit that every device you deploy your app to — on iOS and Android —
will be using the exact same build of SQLite.
let j1 =try sqlplus.selectAll(sql: #"SELECT json_extract(profile, '$.name') as name FROM users WHERE id = ?"#, parameters: [.integer(1)]).first
assert j1 == [.text("Alice")]
let j2 =try sqlplus.selectAll(sql: #"SELECT json_extract(profile, '$.name') as name, json_extract(profile, '$.age') as age FROM users WHERE id = ?"#, parameters: [.integer(2)]).first
SQLPlus contains the SQLCipher extension, which adds 256 bit AES encryption of database files and other security features like:
On-the-fly encryption
Tamper detection
Memory sanitization
Strong key derivation
SQLCipher is based on SQLite and stable upstream release features are periodically integrated. The extension is documented at the official SQLCipher site ↗. It is used by many mobile applications like the Signal ↗ iOS and Android app to secure local database files. Cryptographic algorithms are provided by the LibTomCrypt ↗ C library, which is included alongside the sqlcipher sources.
An example of creating an encryped database:
import SkipSQLCore
import SkipSQLPlus
let dbpath = URL.applicationSupportDirectory.appendingPathComponent("encrypted.sqlite")
let db =trySQLContext(path: dbpath.path, flags: [.create, .readWrite], configuration: .plus)
try db.exec(sql: "PRAGMA key = 'password'")
try db.exec(sql: "CREATE TABLE SOME_TABLE(col)")
try db.exec(sql: "INSERT INTO SOME_TABLE(col) VALUES(?)", parameters: [.text("SOME SECRET STRING")])
Note that setting the key on the database must be the first operation that is performed after the database is opened, before any other SQL is executed. To encrypt an unencryped database that has already been created, the database must be exported with the export(path, key) function and then re-opened with the key. An example utility extension to do this is:
extension SQLContext {
/// Takes an unencrypted database and encrypts it with the given key
let tmpDBURL = dbPath.appendingPathExtension("rekey")
// create a new temporary location to encrypt the database
tryself.export(tmpDBURL.path, key: key)
tryself.close() // disconnect the current DB so we can safely delete and overwrite it
// move the encrypted database to the new path
try FileManager.default.removeItem(at: dbPath)
try FileManager.default.moveItem(at: tmpDBURL, to: dbPath)
// reconnect to the newly converted database
let ctx =trySQLContext(path: dbPath.path, flags: .readWrite, configuration: .plus)
try ctx.key(key) // set the key on the database
// re-set the userVersion, which is not copied by pragma sqlcipher_export:
// “sqlcipher_export does not alter the user_version of the target database. Applications are free to do this themselves.” – https://www.zetetic.net/sqlcipher/sqlcipher-api/#notes-export
The module can be tested using the standard swift test command
or by running the test target for the macOS destination in Xcode,
which will run the Swift tests as well as the transpiled
Kotlin JUnit tests in the Robolectric Android simulation environment.
Parity testing can be performed with skip test,
which will output a table of the test results for both platforms.
You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.