Skip to content
ParticleDB
Release candidateParticleDB 1.1.19-rc.17 is not yet GA or ready for production data.Release status →

Swift

Use the configured address for your client. See connection addresses and security. The examples use the SQL client address unless they explicitly select the HTTP API or ParticleDB JDBC driver.

Use PostgresNIO over the SQL client interface (port 5432) from server-side Swift (macOS or Linux). Interpolated values are sent as bind parameters.

5.9
import PackageDescription
let package = Package(
name: "Demo",
platforms: [.macOS(.v13)],
dependencies: [
.package(url: "https://github.com/vapor/postgres-nio.git", from: "1.33.0"),
],
targets: [
.executableTarget(name: "Demo", dependencies: [
.product(name: "PostgresNIO", package: "postgres-nio"),
]),
]
)

The example connects as postgres with the password secret, for a server started with particledb start --auth-method scram-sha-256 --pg-password secret. With the server’s default --auth-method password, connect with TLS (tls: .require(...)); see TLS and authentication.

import PostgresNIO
import Logging
let config = PostgresClient.Configuration(
host: "localhost",
port: 5432,
username: "postgres",
password: "secret",
database: "particledb",
tls: .disable
)
let client = PostgresClient(configuration: config)
try await withThrowingTaskGroup(of: Void.self) { group in
group.addTask { await client.run() } // drives the connection pool
try await client.query("CREATE TABLE users (id BIGINT PRIMARY KEY, name TEXT)")
let id: Int64 = 1
let name = "Alice"
// Interpolated values are sent as bind parameters, not spliced into the SQL text
try await client.query("INSERT INTO users (id, name) VALUES (\(id), \(name))")
let rows = try await client.query("SELECT id, name FROM users WHERE id = \(id)")
for try await (rowID, rowName) in rows.decode((Int64, String).self) {
print(rowID, rowName)
}
// Transaction: commits if the closure returns, rolls back if it throws
let logger = Logger(label: "app")
try await client.withTransaction(logger: logger) { conn in
try await conn.query("INSERT INTO users (id, name) VALUES (\(Int64(2)), \("Bob"))",
logger: logger)
}
let count = try await client.query("SELECT count(*) FROM users")
for try await n in count.decode(Int64.self) { print("count", n) }
group.cancelAll()
}

Output:

1 Alice
count 2

An app installed on users’ devices should not hold database credentials. Call your own backend service from the app, and let that service talk to ParticleDB.