Skip to content

Swift

The ParticleDB Swift SDK provides SQL queries, key-value operations, vector search, and RAG over the REST API using URLSession. Requires Swift 5.7+ with async/await support. Works on macOS 12+, iOS 15+, tvOS 15+, watchOS 8+.

Add to your Package.swift:

dependencies: [
.package(url: "https://github.com/particledb/particledb-swift.git", from: "0.1.0")
]

Or in Xcode: File > Add Packages > enter the repository URL.

import ParticleDB
let db = ParticleDB(config: ParticleDBConfig(host: "localhost", port: 8080))
// Query
let rows = try await db.query("SELECT id, name FROM users WHERE id = $1", params: [1])
for row in rows {
print(row["name"] ?? "")
}
// Execute DML
let affected = try await db.execute(
"INSERT INTO users (id, name) VALUES ($1, $2)",
params: [2, "Alice"]
)
print("Inserted \(affected) row(s)")
// Single row
if let user = try await db.queryOne("SELECT * FROM users WHERE id = $1", params: [42]) {
print(user["name"] ?? "")
}
let db = ParticleDB(config: ParticleDBConfig(
host: "localhost", // Server hostname (default: "localhost")
port: 8080, // HTTP REST API port (default: 8080)
user: "myuser", // Username for auth (default: nil)
password: "secret", // Password for auth (default: nil)
database: "mydb", // Database name (default: nil)
timeoutSeconds: 30 // HTTP timeout in seconds (default: 30)
))
// SELECT -- returns [[String: Any]]
let rows = try await db.query("SELECT * FROM products WHERE price > $1", params: [9.99])
// Full result with metadata
let result = try await db.queryResult("SELECT COUNT(*) AS cnt FROM users")
print("Columns: \(result.columns), Count: \(result.rowCount)")
// INSERT / UPDATE / DELETE -- returns affected row count
let count = try await db.execute("UPDATE products SET price = $1 WHERE id = $2", params: [19.99, 1])
// Single row lookup (returns dict or nil)
let product = try await db.queryOne("SELECT * FROM products WHERE id = $1", params: [1])
// Set / Get / Delete
try await db.kv.set("session:123", value: "{\"user\":\"alice\"}")
try await db.kv.set("temp:key", value: "value", ttl: 3600) // TTL in seconds
let value = try await db.kv.get("session:123")
let deleted = try await db.kv.delete("session:123")
// Batch operations
try await db.kv.mset(["k1": "v1", "k2": "v2"])
let values = try await db.kv.mget(["k1", "k2"])
// Atomic increment
let newVal = try await db.kv.incr("counter", amount: 5)
// Check existence / TTL
let exists = try await db.kv.exists("session:123")
let ttl = try await db.kv.ttl("temp:key")
// List keys
let keys = try await db.kv.keys("session:*")
// Search for nearest neighbors
let results = try await db.vector.search(
table: "documents",
column: "embedding",
queryVector: [0.1, 0.2, 0.3],
k: 5
)
for r in results {
print("\(r.row["title"] ?? "") -- distance: \(r.distance)")
}
// Search with filter
let filtered = try await db.vector.search(
table: "documents",
column: "embedding",
queryVector: [0.1, 0.2, 0.3],
k: 10,
filter: "category = 'science'"
)
// Insert a vector
try await db.vector.insert(
table: "documents",
data: ["id": 1, "title": "My Doc"],
vectorColumn: "embedding",
vector: [0.1, 0.2, 0.3]
)
// Create a vector index
try await db.vector.createIndex(table: "documents", column: "embedding", indexType: "hnsw", params: ["m": 16])
// Create a pipeline
try await db.rag.createPipeline(
name: "qa",
table: "documents",
vectorCol: "embedding",
textCol: "content",
k: 5,
mode: "hybrid"
)
// Query using a pipeline
let answer = try await db.rag.query("What is ParticleDB?", pipeline: "qa")
print(answer ?? "No answer")
// Query without a pipeline (inline config)
let answer2 = try await db.rag.query(
"What is ParticleDB?",
table: "documents",
vectorCol: "embedding",
textCol: "content",
k: 5
)
// Ingest a document
try await db.rag.ingest(
table: "documents",
content: "ParticleDB is a fast database.",
embedding: [0.1, 0.2, 0.3],
metadata: ["source": "docs", "page": 1]
)
do {
let rows = try await db.query("SELECT * FROM nonexistent_table")
} catch let error as ParticleDBError {
print("Error: \(error.message)")
print("Code: \(error.code ?? "none")")
print("HTTP Status: \(error.httpStatus ?? 0)")
} catch {
print("Unexpected error: \(error)")
}
MethodDescription
query(_:params:)Execute SQL, return rows as [[String: Any]]
queryResult(_:params:)Execute SQL, return QueryResult with metadata
queryOne(_:params:)Execute SQL, return first row or nil
execute(_:params:)Execute DML/DDL, return affected row count
health()Server health check
tables()List all tables
kvAccess KV operations
vectorAccess vector search operations
ragAccess RAG operations