Class 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.

See

Transactions Reference

Param

A Datastore instance.

Mixes

module:datastore/request

Example

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

Hierarchy

  • DatastoreRequest
    • Transaction

Constructors

  • Parameters

    • datastore: Datastore
    • Optional options: TransactionOptions

    Returns Transaction

Properties

datastore: Datastore
id: undefined | string
modifiedEntities_: ModifiedEntities
namespace?: string
readOnly: boolean
request: Function
requestCallbacks_: any
requests_: any
skipCommit?: boolean

Methods

  • Generate IDs without creating entities.

    Parameters

    • key: Key

      The key object to complete.

    • options: number | AllocateIdsOptions

      Either the number of IDs to allocate or an options object for further customization of the request.

    Returns Promise<AllocateIdsResponse>

    Example

    const incompleteKey = datastore.key(['Company']);

    //-
    // The following call will create 100 new IDs from the Company kind, which
    // exists under the default namespace.
    //-
    datastore.allocateIds(incompleteKey, 100, (err, keys) => {});

    //-
    // Or, if you're using a transaction object.
    //-
    const transaction = datastore.transaction();

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

    transaction.allocateIds(incompleteKey, 100, (err, keys) => {
    if (err) {
    // Error handling omitted.
    }

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

    //-
    // You may prefer to create IDs from a non-default namespace by providing
    an
    // incomplete key with a namespace. Similar to the previous example, the
    call
    // below will create 100 new IDs, but from the Company kind that exists
    under
    // the "ns-test" namespace.
    //-
    const incompleteKey = datastore.key({
    namespace: 'ns-test',
    path: ['Company']
    });

    function callback(err, keys, apiResponse) {}

    datastore.allocateIds(incompleteKey, 100, callback);

    //-
    // Returns a Promise if callback is omitted.
    //-
    datastore.allocateIds(incompleteKey, 100).then((data) => {
    const keys = data[0];
    const apiResponse = data[1];
    });
  • Parameters

    • key: Key
    • options: number | AllocateIdsOptions
    • callback: AllocateIdsCallback

    Returns void

  • Commit the remote transaction and finalize the current transaction instance.

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

    Parameters

    Returns Promise<CommitResponse>

    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];
    });
  • Parameters

    • callback: CommitCallback

    Returns void

  • Parameters

    • gaxOptions: CallOptions
    • callback: CommitCallback

    Returns void

  • Create an aggregation query from the query specified. See {module:datastore/query} for all of the available methods.

    Parameters

    Returns AggregateQuery

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

    Parameters

    • Optional kind: string

      The kind to query.

    Returns 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.
    }
    });
    });
    });
  • Parameters

    • Optional kind: string[]

    Returns Query

  • Parameters

    • namespace: string
    • kind: string

    Returns Query

  • Parameters

    • namespace: string
    • kind: string[]

    Returns Query

  • Retrieve the entities as a readable object stream.

    Parameters

    • keys: any

      Datastore key object(s).

    • Optional options: RunQueryOptions

      Optional configuration. See get for a complete list of options.

    Returns Transform

    Throws

    If at least one Key object is not provided.

    Example

    const keys = [
    datastore.key(['Company', 123]),
    datastore.key(['Product', 'Computer'])
    ];

    datastore.createReadStream(keys)
    .on('error', (err) => {})
    .on('data', (entity) => {
    // entity is an entity object.
    })
    .on('end', () => {
    // All entities retrieved.
    });
  • Delete all entities identified with the specified key(s) in the current transaction.

    Parameters

    • Optional entities: any

    Returns any

    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.
    }
    });
    });
  • Retrieve the entities identified with the specified key(s) in the current transaction. Get operations require a valid key to retrieve the key-identified entity from Datastore.

    Parameters

    • keys: Key | Key[]

      Datastore key object(s).

    • Optional options: RunQueryOptions

      Optional configuration.

    Returns Promise<GetResponse>

    Throws

    If at least one Key object is not provided.

    Example

    //-
    // Get a single entity.
    //-
    const key = datastore.key(['Company', 123]);

    datastore.get(key, (err, entity) => {});

    //-
    // Or, if you're using a transaction object.
    //-
    const transaction = datastore.transaction();

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

    transaction.get(key, (err, entity) => {
    if (err) {
    // Error handling omitted.
    }

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

    //-
    // Get multiple entities at once with a callback.
    //-
    const keys = [
    datastore.key(['Company', 123]),
    datastore.key(['Product', 'Computer'])
    ];

    datastore.get(keys, (err, entities) => {});

    //-
    // Below is how to update the value of an entity with the help of the
    // `save` method.
    //-
    datastore.get(key, (err, entity) => {
    if (err) {
    // Error handling omitted.
    }

    entity.newValue = true;

    datastore.save({
    key: key,
    data: entity
    }, (err) => {});
    });

    //-
    // Returns a Promise if callback is omitted.
    //-
    datastore.get(keys).then((data) => {
    const entities = data[0];
    });
  • Parameters

    • keys: Key | Key[]
    • callback: GetCallback

    Returns void

  • Parameters

    • keys: Key | Key[]
    • options: RunQueryOptions
    • callback: GetCallback

    Returns void

  • Maps to save, forcing the method to be insert.

    Parameters

    • entities: any

      Datastore key object(s).

    Returns void

  • Merge the specified object(s). If a key is incomplete, its associated object is inserted and the original Key object is updated to contain the generated ID. 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 get the data from datastore and merge 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.

    Maps to save, forcing the method to be upsert.

    Parameters

    • entities: any

      Datastore key object(s).

    Returns Promise<CommitResponse>

  • Parameters

    • entities: any
    • callback: CommitCallback

    Returns void

  • Private

    Parameters

    • config: RequestConfig
    • callback: Function

    Returns void

  • Make a request as a stream.

    Parameters

    • config: RequestConfig

      Configuration object.

    Returns AbortableDuplex

  • Private

    Make a request to the API endpoint. Properties to indicate a transactional or non-transactional operation are added automatically.

    Parameters

    • config: RequestConfig

      Configuration object.

    • callback: RequestCallback

      The callback function.

    Returns void

  • Reverse a transaction remotely and finalize the current transaction instance.

    Parameters

    • callback: RollbackCallback

      The callback function.

    Returns void

    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];
    });
  • Parameters

    • Optional gaxOptions: CallOptions

    Returns Promise<RollbackResponse>

  • Parameters

    • gaxOptions: CallOptions
    • callback: RollbackCallback

    Returns void

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

    Parameters

    • Optional options: RunOptions

      Configuration object.

    Returns Promise<RunResponse>

    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];
    });
  • Parameters

    • callback: RunCallback

    Returns void

  • Parameters

    • options: RunOptions
    • callback: RunCallback

    Returns void

  • Parameters

    • query: AggregateQuery
    • Optional options: RunQueryOptions

    Returns Promise<RunQueryResponse>

  • Parameters

    • query: AggregateQuery
    • options: RunQueryOptions
    • callback: RequestCallback

    Returns void

  • Parameters

    • query: AggregateQuery
    • callback: RequestCallback

    Returns void

  • Datastore allows you to query entities by kind, filter them by property filters, and sort them by a property name. Projection and pagination are also supported.

    The query is run, and the results are returned as the second argument to your callback. A third argument may also exist, which is a query object that uses the end cursor from the previous query as the starting cursor for the next query. You can pass that object back to this method to see if more results exist.

    Parameters

    • query: Query

      Query object.

    • Optional options: RunQueryOptions

      Optional configuration.

    Returns Promise<RunQueryResponse>

    Example

    //-
    // Where you see `transaction`, assume this is the context that's relevant
    to
    // your use, whether that be a Datastore or a Transaction object.
    //-
    const query = datastore.createQuery('Lion');

    datastore.runQuery(query, (err, entities, info) => {
    // entities = An array of records.

    // Access the Key object for an entity.
    const firstEntityKey = entities[0][datastore.KEY];
    });

    //-
    // Or, if you're using a transaction object.
    //-
    const transaction = datastore.transaction();

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

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

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

    //-
    // A keys-only query returns just the keys of the result entities instead
    of
    // the entities themselves, at lower latency and cost.
    //-
    const keysOnlyQuery = datastore.createQuery('Lion').select('__key__');

    datastore.runQuery(keysOnlyQuery, (err, entities) => {
    const keys = entities.map((entity) => {
    return entity[datastore.KEY];
    });
    });

    //-
    // Returns a Promise if callback is omitted.
    //-
    datastore.runQuery(query).then((data) => {
    const entities = data[0];
    });
  • Parameters

    • query: Query
    • options: RunQueryOptions
    • callback: RunQueryCallback

    Returns void

  • Parameters

    • query: Query
    • callback: RunQueryCallback

    Returns void

  • Get a list of entities as a readable object stream.

    See runQuery for a list of all available options.

    Parameters

    • query: Query

      Query object.

    • Optional options: RunQueryOptions

      Optional configuration.

    Returns Transform

    Example

    datastore.runQueryStream(query)
    .on('error', console.error)
    .on('data', (entity) => {
    // Access the Key object for this entity.
    const key = entity[datastore.KEY];
    })
    .on('info', (info) => {})
    .on('end', () => {
    // All entities retrieved.
    });

    //-
    // If you anticipate many results, you can end a stream early to prevent
    // unnecessary processing and API requests.
    //-
    datastore.runQueryStream(query)
    .on('data', (entity) => {
    this.end();
    });
  • 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

    • entities: any

      Datastore key object(s).

    Returns void

    Example

    <caption>Save a single entity.</caption>
    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.
    }
    });
    });

    Example

    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.
    }
    });
    });

    Example

    <caption>Save multiple entities at once.</caption>
    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.
    }
    });
    });
  • Maps to save, forcing the method to be update.

    Parameters

    • entities: any

      Datastore key object(s).

    Returns void

  • Maps to save, forcing the method to be upsert.

    Parameters

    • entities: any

      Datastore key object(s).

    Returns void

  • Internal

    Format a user's input to mutation methods. This will create a deep clone of the input, as well as allow users to pass an object in the format of an entity.

    Both of the following formats can be supplied supported:

    datastore.save({
    key: datastore.key('Kind'),
    data: { foo: 'bar' }
    }, (err) => {})

    const entity = { foo: 'bar' }
    entity[datastore.KEY] = datastore.key('Kind')
    datastore.save(entity, (err) => {})

    Parameters

    • obj: any

      The user's input object.

    Returns PrepareEntityObjectResponse

Generated using TypeDoc