Quickstart for Swift
Python · Node · Go · Rust · Swift · Dart · JVM · .NET · C++ · Objective-C
This program shows two devices synchronizing through one remote. It resolves a conflict so both devices finish with the same row. See Concepts for the database and synchronization terms.
| Term | Meaning in this program |
|---|---|
| Local store | The database files on one device. |
| Remote | The shared copy of a database that devices synchronize with. |
| Revision | One published database state that does not change. |
| Head | The remote’s newest published revision. |
| Push | Send local writes to the remote. |
| Pull | Receive writes from the remote. |
| Pending | Local writes that the device has not confirmed as published. |
| Replay | Run local statements again on the remote revision. |
| Quarantine | Preserve a transaction that cannot replay safely, for the application to handle. |
The two databases represent a laptop and a phone. Both change the same row before receiving the other’s change. The remote uses a temporary directory that the program removes when it exits.
- Complete the installation.
- Save this program as
main.swiftin an executable target that depends onpotluckdb. - Run
swift run.
The program prints two lines:
| Output | Meaning |
|---|---|
Use query for this statement. | The program passes a read statement to execute on purpose. The call fails with read_in_execute, and the program prints the error’s action. |
quickstart: ok | The program completed all checks, including checking that both devices contain the same row. |
Without an accepted license key, a trial notice on standard error is expected. See license notices for the text. If the program fails or omits these lines, check the installation and any changes to the program.
// Two devices, one remote, one conflict, and its resolution.
import Foundationimport potluckdb
/// Every sync attempt reports an outcome, upToDate included; wait for the requested one.final class Mailbox { private var outcomes: [SyncResult] = [] private let arrived = DispatchSemaphore(value: 0) private let lock = NSLock()
func deliver(_ outcome: SyncResult) { lock.lock(); outcomes.append(outcome); lock.unlock() arrived.signal() }
func wait(for wanted: (SyncResult) -> Bool) throws -> SyncResult { while true { guard arrived.wait(timeout: .now() + 10) == .success else { fatalError("no sync outcome within ten seconds") } lock.lock(); let outcome = outcomes.removeFirst(); lock.unlock() if case .failed(let error) = outcome { throw error } if wanted(outcome) { return outcome } } }}
/// One pushed is one automatic cycle's work, not proof that everything written/// so far is published; a device is finished when it has nothing pending.func waitUntilPublished(_ device: Database, _ events: Mailbox) throws { while try device.status().pendingWrites > 0 { _ = try events.wait { if case .pushed = $0 { true } else { false } } }}
let scratch = FileManager.default.temporaryDirectory .appendingPathComponent("potluckdb-\(ProcessInfo.processInfo.processIdentifier)")try FileManager.default.createDirectory(at: scratch, withIntermediateDirectories: true)let remote = try Remote.fromDirectory(scratch.appendingPathComponent("remote").path) // a bucket replaces this in production; see the installation page
// The laptop synchronizes on its own: automatic is the default policy.// onSync delivers every outcome to the program; this program stores them in a mailbox.let laptopEvents = Mailbox()let laptop = try open( scratch.appendingPathComponent("laptop").path, remote: remote, options: OpenOptions(onSync: { outcome in laptopEvents.deliver(outcome) }))try laptop.transaction { setup in // one transaction: both statements travel in one push _ = try setup.execute("CREATE TABLE note(id INTEGER PRIMARY KEY, body TEXT NOT NULL)") _ = try setup.execute("INSERT INTO note(body) VALUES(?)", .positional([.text("buy milk")]))}try waitUntilPublished(laptop, laptopEvents)
// The phone synchronizes only when instructed: a manual policy, and sync()// calls that return the outcome as a value. It starts from the revision the// laptop published.let phone = try open( scratch.appendingPathComponent("phone").path, remote: remote, options: OpenOptions(syncPolicy: .manual()))let rows = try phone.query("SELECT id, body FROM note ORDER BY id")precondition(rows.columns == ["id", "body"], "columns are reported with the rows")precondition(rows[0]["body"] == .text("buy milk") && rows[0][0] == .integer(1), "a row is read by column name or position")
// Both devices modify the same row before either has seen the other's write._ = try laptop.execute("UPDATE note SET body = ? WHERE id = ?", .positional([.text("buy oat milk"), .integer(1)]))_ = try phone.execute("UPDATE note SET body = ? WHERE id = ?", .positional([.text("buy milk and eggs"), .integer(1)]))try waitUntilPublished(laptop, laptopEvents)
// The phone's push finds a remote head it has not seen:// a conflict, returned rather than thrown.guard case .conflict = try phone.sync() else { fatalError("expected a conflict") }let resolution = try phone.resolveConflict() // adopt the laptop's revision, replay the phone's statement on itprecondition(resolution.quarantined.isEmpty, "no statement was quarantined")guard case .pushed = try phone.sync() else { fatalError("expected a push") }
// The laptop pulls the resolved revision on its own. Both devices hold the same row._ = try laptopEvents.wait { if case .pulled = $0 { true } else { false } }for db in [laptop, phone] { let current = try db.query("SELECT body FROM note WHERE id = ?", .positional([.integer(1)])) precondition(current[0]["body"] == .text("buy milk and eggs"), "both devices hold the same row")}
// query reads, execute writes. The wrong call is refused before execution.do { _ = try laptop.execute("SELECT count(*) FROM note") fatalError("execute refuses a read")} catch let error as PotluckDBError { precondition(error.code == "read_in_execute", "the refusal names the code") print(error.action) // Use query for this statement.}
try laptop.close()try phone.close()try remote.close()try FileManager.default.removeItem(at: scratch)print("quickstart: ok")What the program demonstrates
Section titled “What the program demonstrates”The remote uses a directory. No server runs. Remote.fromDirectory uses a directory that stands in for a bucket in a storage service. The installation page shows the constructor for a storage service. These constructors support S3, Google Cloud Storage, and Azure Blob Storage. The rest of the program stays the same.
The laptop synchronizes automatically. Automatic synchronization is the default policy, which decides when to synchronize. The laptop never calls sync(). Its onSync hook, a function that receives synchronization results, reports every attempt. A failed result carries the error.
The hook runs on the synchronization thread. Transfer the outcome to your own thread, as shown with a mailbox and a semaphore.
| Result | Meaning |
|---|---|
.upToDate | The attempt found no pending writes and no remote revision to pull. |
.pushed | The attempt published its pending writes as a remote revision. |
.pulled | The attempt adopted a remote revision. It can also report replayed and quarantined transactions. |
.conflict | The device’s push met a remote revision that the device had not seen. |
.failed | An automatic attempt failed and carries the error. |
An automatic result covers one attempt. .pushed confirms the writes that the attempt published. Writes made after the attempt began can still be pending. If an earlier attempt failed, an explicit sync() first publishes that attempt’s writes and leaves later writes pending. A program that must know its own writes are published reads status().pendingWrites. waitUntilPublished does that here before the second device opens.
Rows include their column names. rows.columns lists the names. You can read a row by column name or position.
The phone receives a conflict result. sync() returns .conflict when the remote has an unseen revision. This result is not an error. resolveConflict() adopts the laptop’s revision and replays the phone’s statement. The phone’s text then appears on both devices. The resolution lists any transactions that cannot replay safely as quarantined.
query reads and execute writes. Each accepts exactly one statement of its own kind. Each refuses the other kind before execution, with PotluckDBError whose action names the required call.
These calls promise different things. query returns rows and uses the connection’s maximumRows to bound the result. A different SQL engine can answer a read. execute changes data that a revision publishes and other devices receive.
This execution-intent policy separates reads from writes. SQLite preparation can have effects, including under EXPLAIN.
Neither call accepts SQL transaction control, which starts, commits, or rolls back a transaction.
Use transaction for transaction control, as the setup shows.
Reference
Section titled “Reference”Open and construct and Database describe every call. Options and policies describes the automatic policy and its parameters. The examples provide longer programs that the test suite runs.