Best Practices for CRUD
Querying Dynamic Data Using $args
let query = "color == $args.color"
let args = [ "color": "blue" ]
let documents = ditto.store
.collection("your_collection_name")
.find(query, args)
.exec()Batching Multiple Operations
The following snippet demonstrates a batch operation in which two write transactions are contained in a single transaction enclosure:
val results = ditto.store.write { transaction ->
val cars = transaction.scoped("cars")
val people = transaction.scoped("people")
val docId = "abc123"
people.upsert(mapOf("_id" to docId, "name" to "Susan"))
cars.upsert(mapOf("make" to "Hyundai", "color" to "red", "owner" to docId))
cars.upsert(mapOf("make" to "Jeep", "color" to "pink", "owner" to docId))
people.findById(DittoDocumentId(docId)).evict()
}Using ISO-8601 for Date Strings
Implementing Write Strategies
Insert if Absent
let initialDocument : [String: Any] = [
"_id": "123456",
"color": "blue"
]
let documentId = ditto.store
.collection("cars")
.upsert(initialDocument, writeStrategy: .insertIfAbsent)Insert Default if Absent
The following snippet shows an example of the writeStrategy: insertDefaultIfAbsent parameter passed as an argument to theupsert method:
do {
let docID = try ditto.store["people"].upsert([
"name": "Susan",
"age": 31
], writeStrategy: .insertDefaultIfAbsent)
} catch {
//handle error
print(error)
}Example Use Case: Upserting Initial Data
Implementing Global Async Transactions
For example, use DispatchQueue.global, as follows:
DispatchQueue.global(qos: .default).async {
ditto.store.write { transaction in
let scope = transaction.scoped(toCollectionNamed: "passengers-\(thisFlight)")
// Loop inside the transaction to avoid writing to database too frequently
self.passengers.forEach {
scope.upsert($0.dict)
}
}
}Avoiding Deadlocks
Example of a Deadlock
The following snippet demonstrates a queued write transaction that has the potential to create a deadlock situation. This is because the write transaction initiated on the "people" collection, along with its nested write transaction on the "settings" collection both attempt to acquire resources held by the other:
// Start a write transaction:
ditto.store["people"].findByID(docID).update { mutableDoc in
// Start a write transaction _within_ a write transacton.
// !! Deadlocks !!
let docID = try! ditto.store["settings"].upsert([
"_id": "abc123",
"preference": 31,
])
// ...
}