Transactions and batched mutations

The crud module supports atomic CRUD operations. In a set of atomic operations, either all of the operations succeed, or none of them are applied. There are two types of atomic operations in the crud module of Space Cloud:

  • Transactions (coming soon): A set of read, insert, update and delete operations on snapshot of a database.
  • Batched Mutations: A set of inserts, updates and deletes on one or more documents.

Batched mutations

A batch operation is used to batch multiple insert, update and delete operations in a single request. Either all of them succeed or none of them. You should use it when you don't want to read data between any of the mutations in the batch.

Here's a code snippet to batch multiple mutations in your app:

      
import { API } from "space-api";

// Initialize api with the project name and url of the space cloud
const api = new API("todo-app", "http://localhost:8080");

// Initialize database(s) you intend to use
const db = api.Mongo();

// Start a batch operation
const batch = db.beginBatch()

// Add operations to be batched
batch.add(db.insert('todos').doc({ _id: 1, text: "Star Space Cloud on Github!" }))
batch.add(db.update('todos').where(cond('id', ==, '1')).set({ text: "Fork Space Cloud on Github!" }))
batch.add(db.delete('some-other-collection').where(cond('id', ==, '1')))

// Trigger the batch request
batch.apply()
  .then(res => {
    if (res.status === 200) {
      // Batch operation was successful

    }
  })
  .catch(ex => {
    // Exception occured while processing request
  });
    
      
// Coming soon!   
      
    
      
from space_api import API, COND

api = API('grpc', 'localhost:8081')
db = api.my_sql()

b = db.begin_batch()
b.add(db.insert('books').doc({"name": "MyBook", "author": "John Doe"}))
b.add(db.insert('books').docs([{"name": "BookName"}, {"name": "BookName"}]))
b.add(db.delete('books').where(COND('name', '!=', 'Book_name')))
response = b.apply()
if response.status == 200:
  print("Success")
else:
  print(response.error)

api.close()

      
    

The add method is used to add multiple db operations to a batch request. It can be called n number of times to add n number of operations to the batch. As you would have noticed, the batch is triggered by calling batch.apply after adding all the mutations.

Note: apply is not to be used on individual operation in a batch request.

Response

On response from the server, the callback passed to the then method is called with the response object as described below:

{
  "status": "number" // Status of the operation
}

Next steps

Now you know all the operations of CRUD module. So let's take a deeper dive into configuring the database module of Space Cloud.

Have a technical question?

Edit docs!