Transaction

Transaction

A transaction is a set of Datastore operations on one or more entities. Each transaction is guaranteed to be atomic, which means that transactions are never partially applied. Either all of the operations in the transaction are applied, or none of them are applied.

Constructor

new Transaction(datastore)

Parameters:
Name Type Description
datastore Datastore

A Datastore instance.

Mixes In:
  • module:datastore/request
See:
Example
const {Datastore} = require('@google-cloud/datastore');
const datastore = new Datastore();
const transaction = datastore.transaction();

Extends

  • Request

Members

datastore

namespace

Methods

commit(gaxOptionsopt, callback)

Commit the remote transaction and finalize the current transaction instance.

If the commit request fails, we will automatically rollback the transaction.

Parameters:
Name Type Attributes Description
gaxOptions object <optional>

Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.

callback function

The callback function.

Properties
Name Type Attributes Description
err error <nullable>

An error returned while making this request. If the commit fails, we automatically try to rollback the transaction (see {module:datastore/transaction#rollback}).

apiResponse object

The full API response.

Example
const {Datastore} = require('@google-cloud/datastore');
const datastore = new Datastore();
const transaction = datastore.transaction();

transaction.commit((err, apiResponse) => {
  if (err) {
    // Transaction could not be committed.
  }
});

//-
// If the callback is omitted, we'll return a Promise.
//-
transaction.commit().then((data) => {
  const apiResponse = data[0];
});

createQuery(namespaceopt, kind) → {Query}

Create a query for the specified kind. See {module:datastore/query} for all of the available methods.

Parameters:
Name Type Attributes Description
namespace string <optional>

Namespace.

kind string

The kind to query.

Returns:
Type Description
Query
See:
Example
const {Datastore} = require('@google-cloud/datastore');
const datastore = new Datastore();
const transaction = datastore.transaction();

// Run the query inside the transaction.
transaction.run((err) => {
  if (err) {
    // Error handling omitted.
  }
  const ancestorKey = datastore.key(['ParentCompany', 'Alphabet']);

  const query = transaction.createQuery('Company')
      .hasAncestor(ancestorKey);

  query.run((err, entities) => {
    if (err) {
      // Error handling omitted.
    }

    transaction.commit((err) => {
      if (!err) {
        // Transaction committed successfully.
      }
    });
  });
});

// Run the query inside the transaction.with namespace
transaction.run((err) => {
  if (err) {
    // Error handling omitted.
  }
  const ancestorKey = datastore.key(['ParentCompany', 'Alphabet']);

  const query = transaction.createQuery('CompanyNamespace', 'Company')
      .hasAncestor(ancestorKey);

  query.run((err, entities) => {
    if (err) {
      // Error handling omitted.
    }

    transaction.commit((err) => {
      if (!err) {
        // Transaction committed successfully.
      }
    });
  });
});

delete(key)

Delete all entities identified with the specified key(s) in the current transaction.

Parameters:
Name Type Description
key Key | Array.<Key>

Datastore key object(s).

Example
const {Datastore} = require('@google-cloud/datastore');
const datastore = new Datastore();
const transaction = datastore.transaction();

transaction.run((err) => {
  if (err) {
    // Error handling omitted.
  }

  // Delete a single entity.
  transaction.delete(datastore.key(['Company', 123]));

  // Delete multiple entities at once.
  transaction.delete([
    datastore.key(['Company', 123]),
    datastore.key(['Product', 'Computer'])
  ]);

  transaction.commit((err) => {
    if (!err) {
      // Transaction committed successfully.
    }
  });
});

insert(entities)

Maps to Datastore#save, forcing the method to be insert.

Parameters:
Name Type Description
entities object | Array.<object>

Datastore key object(s).

Properties
Name Type Attributes Description
key Key

Datastore key object.

excludeFromIndexes Array.<string> <optional>

Exclude properties from indexing using a simple JSON path notation. See the examples in Datastore#save to see how to target properties at different levels of nesting within your entity.

data object

Data to save with the provided key.

rollback(gaxOptionsopt, callback)

Reverse a transaction remotely and finalize the current transaction instance.

Parameters:
Name Type Attributes Description
gaxOptions object <optional>

Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.

callback function

The callback function.

Properties
Name Type Attributes Description
err error <nullable>

An error returned while making this request.

apiResponse object

The full API response.

Example
const {Datastore} = require('@google-cloud/datastore');
const datastore = new Datastore();
const transaction = datastore.transaction();

transaction.run((err) => {
  if (err) {
    // Error handling omitted.
  }

  transaction.rollback((err) => {
    if (!err) {
      // Transaction rolled back successfully.
    }
  });
});

//-
// If the callback is omitted, we'll return a Promise.
//-
transaction.rollback().then((data) => {
  const apiResponse = data[0];
});

run(optionsopt, callback)

Begin a remote transaction. In the callback provided, run your transactional commands.

Parameters:
Name Type Attributes Description
options object <optional>

Configuration object.

Properties
Name Type Attributes Default Description
gaxOptions object <optional>

Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.

readOnly boolean <optional>
false

A read-only transaction cannot modify entities.

transactionId string <optional>

The ID of a previous transaction.

callback function

The function to execute within the context of a transaction.

Properties
Name Type Attributes Description
err error <nullable>

An error returned while making this request.

transaction Transaction

This transaction instance.

apiResponse object

The full API response.

Example
const {Datastore} = require('@google-cloud/datastore');
const datastore = new Datastore();
const transaction = datastore.transaction();

transaction.run((err, transaction) => {
  // Perform Datastore transactional operations.
  const key = datastore.key(['Company', 123]);

  transaction.get(key, (err, entity) => {
    entity.name = 'Google';

    transaction.save({
      key: key,
      data: entity
    });

    transaction.commit((err) => {
      if (!err) {
        // Data saved successfully.
      }
    });
  });
});

//-
// If the callback is omitted, we'll return a Promise.
//-
transaction.run().then((data) => {
  const transaction = data[0];
  const apiResponse = data[1];
});

save(entities)

Insert or update the specified object(s) in the current transaction. If a key is incomplete, its associated object is inserted and the original Key object is updated to contain the generated ID.

This method will determine the correct Datastore method to execute (upsert, insert, or update) by using the key(s) provided. For example, if you provide an incomplete key (one without an ID), the request will create a new entity and have its ID automatically assigned. If you provide a complete key, the entity will be updated with the data specified.

By default, all properties are indexed. To prevent a property from being included in all indexes, you must supply an excludeFromIndexes array. See below for an example.

Parameters:
Name Type Description
entities object | Array.<object>

Datastore key object(s).

Properties
Name Type Attributes Description
key Key

Datastore key object.

excludeFromIndexes Array.<string> <optional>

Exclude properties from indexing using a simple JSON path notation. See the example below to see how to target properties at different levels of nesting within your entity.

data object

Data to save with the provided key.

Examples

Save a single entity.

const {Datastore} = require('@google-cloud/datastore');
const datastore = new Datastore();
const transaction = datastore.transaction();

// Notice that we are providing an incomplete key. After the transaction is
// committed, the Key object held by the `key` variable will be populated
// with a path containing its generated ID.
//-
const key = datastore.key('Company');

transaction.run((err) => {
  if (err) {
    // Error handling omitted.
  }

  transaction.save({
    key: key,
    data: {
      rating: '10'
    }
  });

  transaction.commit((err) => {
    if (!err) {
      // Data saved successfully.
    }
  });
});
const {Datastore} = require('@google-cloud/datastore');
const datastore = new Datastore();
const transaction = datastore.transaction();

// Use an array, `excludeFromIndexes`, to exclude properties from indexing.
// This will allow storing string values larger than 1500 bytes.

transaction.run((err) => {
  if (err) {
    // Error handling omitted.
  }

  transaction.save({
    key: key,
    excludeFromIndexes: [
      'description',
      'embeddedEntity.description',
      'arrayValue[].description'
    ],
    data: {
      description: 'Long string (...)',
      embeddedEntity: {
        description: 'Long string (...)'
      },
      arrayValue: [
        {
          description: 'Long string (...)'
        }
      ]
    }
  });

  transaction.commit((err) => {
    if (!err) {
      // Data saved successfully.
    }
  });
});

Save multiple entities at once.

const {Datastore} = require('@google-cloud/datastore');
const datastore = new Datastore();
const transaction = datastore.transaction();
const companyKey = datastore.key(['Company', 123]);
const productKey = datastore.key(['Product', 'Computer']);

transaction.run((err) => {
  if (err) {
    // Error handling omitted.
  }

  transaction.save([
    {
      key: companyKey,
      data: {
        HQ: 'Dallas, TX'
      }
    },
    {
      key: productKey,
      data: {
        vendor: 'Dell'
      }
    }
  ]);

  transaction.commit((err) => {
    if (!err) {
      // Data saved successfully.
    }
  });
});

update(entities)

Maps to Datastore#save, forcing the method to be update.

Parameters:
Name Type Description
entities object | Array.<object>

Datastore key object(s).

Properties
Name Type Attributes Description
key Key

Datastore key object.

excludeFromIndexes Array.<string> <optional>

Exclude properties from indexing using a simple JSON path notation. See the examples in Datastore#save to see how to target properties at different levels of nesting within your entity.

data object

Data to save with the provided key.

upsert(entities)

Maps to Datastore#save, forcing the method to be upsert.

Parameters:
Name Type Description
entities object | Array.<object>

Datastore key object(s).

Properties
Name Type Attributes Description
key Key

Datastore key object.

excludeFromIndexes Array.<string> <optional>

Exclude properties from indexing using a simple JSON path notation. See the examples in Datastore#save to see how to target properties at different levels of nesting within your entity.

data object

Data to save with the provided key.