Use Minigraf from Swift. Store data in an embedded, single-file graph database and query it with bi-temporal Datalog.
This guide uses the 3.x API. To install the current stable 2.x release, use the 2.x guide.
Install the 3.x version below only once its exact tag appears on the releases page. In Xcode, select the exact version rather than a version range.
In Xcode: File → Add Package Dependencies → enter this repo URL.
Or add to Package.swift:
dependencies: [
.package(url: "https://github.com/project-minigraf/minigraf-swift", exact: "3.0.0-alpha")
]Each semver tag
v<version>points to a commit on theswift-releasesbranch. That commit holds thePackage.swiftwith the release's xcframework URL and checksum, plus the generated Swift sources. After the branch move,source-v<version>marks the matching commit onmainfor 3.x orv2.xfor 2.x. Releases up to v2.0.0 were tagged differently; see Older releases below. Thev2.0.1tag was moved to itsswift-releasescommit after the fact, so it resolves normally but has nosource-v2.0.1tag.
Before the tagging fix, the release workflow put the semver tag on the source commit, whose
Package.swift has a placeholder checksum and no generated sources. The tags v2.0.0 and
earlier do not resolve. For those versions, the working manifest is on the swift-v<version>
tag, which SPM cannot resolve by version. Pin that tag's commit instead, for example:
// swift-v2.0.0
.package(url: "https://github.com/project-minigraf/minigraf-swift", revision: "1307a095c1725d2813abbbdcf17557311d517d24")Use git ls-remote --tags https://github.com/project-minigraf/minigraf-swift 'swift-v*' to
find the commit for another version.
No release up to and including v2.0.8 compiles: its xcframework names the C module map
minigraf_ffiFFI.modulemap instead of module.modulemap, so the generated Swift cannot import
the FFI module ("cannot find type 'RustBuffer' in scope"). Use v2.0.9 or later.
Requires iOS 16+.
import MinigrafKit
let db = try MiniGrafDb.openInMemory()
let result = try db.execute(datalog: #"(transact [[:alice :name "Alice"]])"#)
print(result) // {"transacted":1}import MinigrafKit
// Read-only: shared lock, nothing written; writes throw MiniGrafError (API-014).
let src = try MiniGrafDb.openWithOptions(path: oldPath, options: OpenOptions(readOnly: true, pageCacheSize: 4096))
// A cursor's answer is fixed when it opens. Each batch is a JSON array of rows,
// encoded like execute()'s "results".
let cursor = try src.query(datalog: "(query [:find ?n :where [?e :name ?n]])")
try cursor.forEachBatch(size: 1000) { batch in /* parse rows */ }
// Copy every fact version, keeping tx and valid-time bounds, into a new file.
let out = try MiniGrafLogWriter.create(path: newPath, options: OpenOptions())
try src.factLog(filter: FactFilter()).forEachRecord { record in
if !record.attribute.hasPrefix(":secret/") { try out.append(record: record) }
}
try out.advanceTxCount(txCount: try src.currentTxCount())
try out.finish() // out.close() instead abandons the build and leaves no fileappendBatch(records:) appends many records per call. A record's value is a
MiniGrafValue (.text, .int64, .float64, .bool, .ref, .keyword, .null);
validTimeForever is the validTo of a fact valid forever. MiniGrafError.message
starts with the error's code, such as [API-015].
OpenOptions(queryMemoryLimit: bytes) limits the bytes a query counts for
retained state. The query counts entries on the build side of joins, in negation and or
tables, distinct sets, aggregate groups, window rows and rule-derived facts.
If it would exceed the limit, it releases its state and throws
MiniGrafError.Query with QRY-012. By default there is no limit; Int64.max
also means no limit. Rows returned by a cursor are not counted. Use
query(datalog:) to read a large result in batches.
Query text may override some settings with keywords such as :max-derived-facts 1000.
OpenOptions(allowOverrides:) lists the Overridable keywords it may use
(.maxDerivedFacts, .maxResults, .queryMemoryLimit, .maxIterations). Use
nil for Overridable.defaults from the core library: currently
.maxDerivedFacts, .maxResults and .maxIterations. A nonempty list replaces
the defaults, and [] disables all query-text overrides. An override not on
the allowed list throws MiniGrafError.Api with [API-025] from execute,
query and prepare.
let db = try MiniGrafDb.openWithOptions(path: path, options: OpenOptions(
allowOverrides: Overridable.defaults + [.queryMemoryLimit],
transactionChunkFacts: 16_384, // facts staged before a large transaction is chunked
maxIterations: 10_000 // rounds per stratum of a rule query, else INT-020
))maxIterations defaults to 1,000,000 and Int64.max is no limit;
transactionChunkFacts defaults to 65,536 and is clamped to 1...1,000,000. A negative
count throws [API-017].
db.prepare(datalog:) parses a query once; run it with its $slots bound (names
without the $). Each run reads the database as it is then, and a prepared query keeps
its database open until both are released.
let pq = try db.prepare(datalog: "(query [:find ?n :where [?e :age $age] [?e :name ?n]])")
let thirty = try pq.execute(["age": 30])
try pq.query(["age": 40]).forEachBatch { batch in /* JSON rows */ }Bool, Int/Int32/Int64, Double/Float, String, nil (Null) and UUID
(an entity, which also fits value slots as a ref) bind as they are: they conform to
MinigrafBindable. For the other kinds pass a MiniGrafValue (.keyword, .ref, a
whole-number .float64) or a MiniGrafBindValue (.entity, .txCount or .timestamp
for :as-of, .anyValidTime for :valid-at). A missing slot throws
MiniGrafError.Api with [API-022], a slot in an attribute position [API-023], and a
value of the wrong kind [API-024].
A Set binds a set value, for in? and the other set predicates or a set-valued
attribute: pq.execute(["ids": Set([1, 2, 3])]). Its elements conform to
MinigrafSetElement: the plain values above, with UUID as a ref, or MiniGrafValue;
mix types with Set<MiniGrafValue> ([.keyword(value: ":role/admin"), .int64(value: 1)]).
A set inside a set throws MiniGrafError.Api with [API-021]. Set values come back as
JSON arrays from execute and as MiniGrafValue.set in fact records.
MiniGrafError is .Parse, .Query, .Storage, .Api (a bad argument, a closed
object, or an invalid query binding) or .Other.
withMaxDerivedFacts(n:), withQueryMemoryLimit(bytes:) and withMaxIterations(n:)
each return a new prepared query with that limit; the one they are called on is
unchanged. allowOverrides does not restrict these setters. A permitted
override in the query text still takes precedence. Int64.max means no limit and a
negative value throws [API-017]. A derived query keeps its database open, as any
prepared query does.
let reach = try db.prepare(datalog: "(query [:find ?x ?y :where (reach ?x ?y)])")
let small = try reach.withMaxDerivedFacts(n: 10_000).withQueryMemoryLimit(bytes: 16_777_216)
_ = try small.execute([:]) // INT-020 or QRY-012 past a limit; reach is unchangedA predicate conforms to MiniGrafPredicate (test(value:) throws -> Bool) and is
called in Datalog as [(name ?v)]. An aggregate conforms to MiniGrafAggregate; its
accumulator() returns a new MiniGrafAccumulator (step(value:), finish(count:))
for each group or window partition, and it is used as (name ?v) in :find or with
:over. Values arrive as MiniGrafValue (.int64(value:), .text(value:), …), and
finish returns one. The protocols are AnyObject, Sendable: implement them with a
final class whose stored properties are immutable, or mark it @unchecked Sendable
when it keeps state of its own, as an accumulator does.
final class Adult: MiniGrafPredicate {
func test(value: MiniGrafValue) throws -> Bool {
guard case .int64(let age) = value else { throw MiniGrafUdfError.Failed(msg: "age is not an integer") }
return age >= 18
}
}
final class Product: MiniGrafAggregate {
final class Acc: MiniGrafAccumulator, @unchecked Sendable {
var product: Int64 = 1
func step(value: MiniGrafValue) throws {
if case .int64(let n) = value { product *= n }
}
func finish(count: Int64) throws -> MiniGrafValue { .int64(value: product) } // count: values stepped
}
func accumulator() throws -> MiniGrafAccumulator { Acc() }
}
try db.registerPredicate(name: "adult?", predicate: Adult())
try db.registerAggregate(name: "product", aggregate: Product())
_ = try db.execute(datalog: "(query [:find ?n :where [?e :age ?a] [(adult? ?a)] [?e :name ?n]])")
_ = try db.execute(datalog: "(query [:find ?g (product ?a) :where [?e :group ?g] [?e :age ?a]])")
_ = try db.execute(datalog: "(query [:find ?a (product ?a :over (:order-by ?a)) :where [?e :age ?a]])")- Failures. A callback that throws stops the query with
QRY-014, raised asMiniGrafError.Query; it is never read asfalseor a missing value. ThrowMiniGrafUdfError.Failed(msg:)to choose the message. Any other error also fails the call, with the first line of itsString(describing:)as the message. AMiniGrafValue.reffromfinishwhose value is not a UUID is a failing call too. - Lifecycle. The database keeps a strong reference to each registered object until
the database and every cursor and prepared query opened from it are released. There
is no unregister. Predicates and aggregates have separate names, and registering a
name twice in either is an error (
INT-040). A query sees the functions registered when it opened; a prepared query, those registered when each run starts. - Threading. A callback runs on the thread that calls
execute(of the database or a prepared query) or a cursor'snextBatch, including a prepared query's cursor. Queries on different threads may call the same object at once, so it must be thread-safe. One accumulator is used by one query on one thread at a time. Keep callbacks short: a query on the main thread blocks it for as long as they run. - Cost. Each call crosses the FFI once: one foreign call per value.
- Re-entry. A callback may query the same database, open a cursor or register another
function. Inside a write transaction, the calls listed under
Write transactions return
INT-001. Opening a cursor is a call toquery.
A write transaction stages several transact, retract and query statements, with
queries seeing what it staged, and then commits them as one transaction or rolls them
back (minigraf#824). Available in the pinned, unreleased v3 core (commit
38b10383), which also provides incoming references.
let db = try MiniGrafDb.open(path: "bank.graph")
_ = try db.execute(datalog: "(transact [[:alice :balance 100] [:bob :balance 50]])")
// The closure form rolls back when the closure throws or returns without commit().
try db.withWriteTransaction(options: TxOptions(chunkFacts: 10_000)) { tx in
_ = try tx.execute(datalog: "(transact [[:alice :balance 70] [:bob :balance 80]])")
_ = try tx.execute(datalog: "(retract [[:alice :balance 100] [:bob :balance 50]])")
try tx.commit()
}db.beginWrite()anddb.beginWrite(options: TxOptions(...))return aMiniGrafWriteTransaction. Callcommit()orrollback()yourself.withWriteTransactionruns a closure and returns its result. Aniloption uses the database default.synchronous(.fullor.normal) controls WAL sync for this commit.chunkFactssets how many facts the transaction stages before a file-backed database writes in chunks; a negative value throws API-017. Read-only databases throw API-014.tx.execute(datalog:)returns whatdb.executereturns; a staged write returns{"ok":true}. A statement that fails stages nothing and leaves the transaction open. There are no cursors or prepared queries inside a transaction.tx.commit()applies the writes as one transaction;tx.rollback()discards staged writes. Oncecommit()takes the transaction, it finishes it even if it throws. An error before the facts are applied leaves them unapplied, but automatic checkpointing can fail after application, and deleting the WAL can fail after a large transaction has committed. Check whether the facts were applied before retrying. If the failed checkpoint leaves the handle rejecting writes with STG-046, reopen it and check again. On a finished transaction,execute,incomingRefsandcommitthrow API-018, androllbackdoes nothing.- Commit is always explicit. When ARC releases the last reference to an open
transaction, it rolls back. Finish it yourself or use
withWriteTransactionso the write lock is released promptly. - On the thread that opened the transaction, database calls to
execute,query,prepare,factLog,checkpoint, anotherbeginWriteand prepared queries fail with INT-001. That also applies to those calls from user functions run by the transaction. A user function gets INT-001 if it callsexecute,incomingRefs,commitorrollbackon its own transaction. - On other threads, writes and attempts to start a transaction wait until it finishes; queries still see committed data. Use the transaction on the thread that opened it. A different thread that uses the transaction and then writes through the database can wait for that same transaction to finish.
- Rules registered inside a transaction stay registered after a rollback.
- The transaction keeps its database open until it is released.
try tx.incomingRefs(target: String, maxLinks: Int64, maxRecords: Int64) -> IncomingRefs
works directly on a transaction and inside withWriteTransaction.
try db.withWriteTransaction { tx in
switch try tx.incomingRefs(target: "82958a33-8334-5ef8-ae38-de39ce3fab69", maxLinks: 100, maxRecords: 10_000) {
case .complete(let links, let recordsExamined):
for link in links {
let source = link.source
let attribute = link.attribute
// Plan any deletes using the complete set, then stage and commit them.
}
print(recordsExamined)
case .exhausted(let budget, let recordsExamined):
// budget is IncomingRefBudget.links or .records.
print(budget, recordsExamined)
// Retry with larger budgets or abandon the delete.
}
}The lookup sees earlier writes in this transaction without changing them.
A complete result contains IncomingRef records with canonical lowercase UUID
source strings and attribute strings, in no specified order. A complete
result can contain no links; an exhausted result never contains a partial list.
Require a complete result before staging deletes. If the result is exhausted,
retry with higher limits or stop. Earlier writes remain staged and an explicit
commit still commits them.
- Both limits are required and neither has an unlimited value. A lookup can
succeed exactly at either limit. The accepted range is
0..=min(i64::MAX, usize::MAX):2^63-1on 64-bit targets and2^32-1on 32-bit targets (including Android's 32-bit ABIs). Zero is a real limit;0, 0completes empty only when no record needs inspection. Large limits do not allocate proportional memory up front. - The link limit caps distinct
(source, attribute)pairs. The record limit caps fact versions examined across all layers, including superseded versions, retractions and lookahead. The returned record count never exceeds that limit; checkpointing can change the count without changing the links. - Only stored scalar Ref values count. Keywords (even an alias of the target), UUID-looking Strings, refs inside sets and rule-derived facts are excluded. Valid time is ignored: future and expired assertions count. The newest assertion or retraction decides whether a link is live.
- Invalid UUIDs and negative or unrepresentable limits give
API-017. A finished transaction givesAPI-018before argument validation. A callback that calls back into its own transaction getsINT-001before locking or validating arguments. Storage and decoding errors remain errors. A complete result, an exhausted result orAPI-017leaves the transaction open for further statements, retry, commit or rollback.
Requires Rust stable toolchain with iOS targets and Xcode.
rustup target add aarch64-apple-ios aarch64-apple-ios-sim
cargo build --target aarch64-apple-ios --release
cargo build --target aarch64-apple-ios-sim --release
cargo run --bin uniffi-bindgen -- generate \
--library target/aarch64-apple-ios/release/libminigraf_ffi.a \
--language swift \
--out-dir Sources/MinigrafKit/The default branch's release.yml reads the full core tag from
client_payload.version on a core-release event. Since the branch move
in core #937, it builds and updates main for 3.x and v2.x for 2.x. A missing source branch stops the run; there
is no fallback. Run production retries from the default branch. Keep
swift-releases and its history.
The workflow uses the exact crates.io version of the core dependency, keeps the enabled features, and checks the lockfile and resolved features before building with that lockfile. The workflow commit supplies the release scripts. The selected source commit supplies the Rust tests, Swift wrappers, README and consumer tests. Both lines package libraries for iOS devices and a universal simulator library, then run the iOS consumer. Builds with the 3.x API also run the macOS Swift bindings test. The workflow checks that the universal simulator library contains arm64 and x86_64. The consumer runs on the simulator the runner selects.
Tags such as v3.0.0-alpha, v3.0.0-beta2 and v3.0.0-rc1 keep their suffix
in the xcframework filename and URL. source-<tag> points to the source commit
prepared and tested for that release. The SemVer tag points to a separate commit
on swift-releases. That commit contains Package.swift with the exact zip URL
and SHA-256, the generated Swift sources, and that branch's wrappers.
The workflow keeps swift-releases history and never force-pushes the branch.
Prerelease READMEs use exact: "3.0.0-alpha"; stable releases use from:.
The workflow marks prereleases on GitHub. It never marks an older stable
retry Latest; the highest released stable version stays Latest.
To recover, rerun the default workflow with the same full tag, for example:
gh workflow run release.yml --ref main -f version=v3.0.0-alphaDo not delete or move either tag. A retry uses the commit named by the original source tag even if the branch has advanced. That tag records the original Actions run ID, artifact ID and digest. The immutable Actions artifact holds the original zip and other release artifacts, source bundle, generated package, provenance and consumer results for 90 days, subject to repository retention settings. Recovery stops before any further publication if those files are missing or expired, the source and generated package do not match the saved evidence, or the public asset bytes do not match.
If the tagged package's zip was never uploaded, the workflow can upload only
the original matching zip. It leaves matching public assets in
place and restores the correct prerelease and Latest settings even if it
does not have to upload anything. Every successful retry installs and tests
the exact version with SwiftPM. Production publication and recovery failures
still use release-broken reporting.
Only one job for the same tag can run at a time. All versions share a lock
while updating the swift-releases branch, tags and release classification.
GitHub does not cancel the running job but can replace an older pending one.
Dispatch the replaced job again if it is still needed.
Set rehearsal=true for a manual rehearsal. For 3.x use version=v3.0.0-alpha
and candidate=<exact 40-character core SHA>. For 2.x use version=v2.0.12
with no candidate. Omit source_alias; earlier rehearsals used
source_alias=v3 and source_alias=main, respectively. Only explicit manual
rehearsals accept aliases or a candidate. The workflow reports the candidate's
actual crate version separately from the label used on its artifacts.
Rehearsals use the same preparation, packaging and consumer tests. The
prepared commit is saved in a Git bundle instead of a temporary remote ref.
The summary lists the workflow, source and prepared commits, selected branch,
dependency source, artifact and generated-source checksums, and test results.
Rehearsal never changes source branches, swift-releases, tags, releases,
assets, registries or issues. Before production publication, confirm that both
release lines passed rehearsal and the post-move workflow routed each to the
intended branch.
MIT OR Apache-2.0