This is a simple library to work with CouchDB in Swift.
- The latest version supports strict concurrency:
CouchDBClient
is an actor and requires Swift 6.0 or newer. For Swift 5, you can still use version1.7.0
. - Compatible with Vapor 4.
- Version
1.0.0
can be used with Vapor 4 withoutasync/await
; Swift 5.3 is required. - You can use the old version for Vapor 3 by checking out the
vapor3
branch or using versions earlier than1.0.0
.
The only dependency for this library is async-http-client
.
Find documentation, examples, and tutorials here.
Add the following to the dependencies
section of your Package.swift
:
dependencies: [
.package(url: "https://github.com/makoni/couchdb-swift.git", from: "2.1.0"),
]
let config = CouchDBClient.Config(
couchProtocol: .http,
couchHost: "127.0.0.1",
couchPort: 5984,
userName: "admin",
userPassword: "",
requestsTimeout: 30
)
let couchDBClient = CouchDBClient(config: config)
To avoid hardcoding your password, you can pass the COUCHDB_PASS parameter via the command line. For example, you can run your server-side Swift project as follows:
COUCHDB_PASS=myPassword /path/.build/x86_64-unknown-linux-gnu/release/Run
In this case, use the initializer without the userPassword parameter:
let config = CouchDBClient.Config(
couchProtocol: .http,
couchHost: "127.0.0.1",
couchPort: 5984,
userName: "admin",
requestsTimeout: 30
)
let couchDBClient = CouchDBClient(config: config)
// Example struct
struct ExpectedDoc: CouchDBRepresentable {
var name: String
var _id: String = NSUUID().uuidString
var _rev: String?
func updateRevision(_ newRevision: String) -> Self {
return ExpectedDoc(name: name, _id: _id, _rev: newRevision)
}
}
var testDoc = ExpectedDoc(name: "My name")
testDoc = try await couchDBClient.insert(
dbName: "databaseName",
doc: testDoc
)
print(testDoc) // testDoc has _id and _rev values now
// get data from a database by document ID
var doc: ExpectedDoc = try await couchDBClient.get(fromDB: "databaseName", uri: "documentId")
print(doc)
// Update value
doc.name = "Updated name"
doc = try await couchDBClient.update(
dbName: testsDB,
doc: doc
)
print(doc) // doc will have updated name and _rev values now
let response = try await couchDBClient.delete(fromDb: "databaseName", doc: doc)
// or by uri
let response = try await couchDBClient.delete(fromDb: "databaseName", uri: doc._id,rev: doc._rev)
let dbs = try await couchDBClient.getAllDBs()
print(dbs)
// prints: ["_global_changes", "_replicator", "_users", "yourDBname"]
let selector = ["selector": ["name": "Sam"]]
let docs: [ExpectedDoc] = try await couchDBClient.find(in: "databaseName", selector: selector)
print(docs)
Here's a simple tutorial for Vapor.