Constructor

BatchTransaction

new BatchTransaction(options)

Use a BatchTransaction object to create partitions and read/query against your Cloud Spanner database.

Parameter

options

Optional

TransactionOptions

Transaction options.

Extends
Transaction

Property

session

unknown

Inherited from
Transaction#session

Methods

close

close(callback) returns Promise containing BasicResponse

Closes all open resources.

When the transaction is no longer needed, you should call this method to free up resources allocated by the Batch client.

Calling this method would render the transaction unusable everywhere. In particular if this transaction object was being used across multiple machines, calling this method on any of the machine would make the transaction unusable on all the machines. This should only be called when the transaction is no longer needed anywhere

Parameter

callback

Optional

BasicCallback

Callback function.

Returns

Promise containing BasicResponse 

Example

const Spanner = require('@google-cloud/spanner');
const spanner = new Spanner();

const instance = spanner.instance('my-instance');
const database = instance.database('my-database');

database.createBatchTransaction(function(err, transaction) {
  if (err) {
    // Error handling omitted.
  }

  transaction.close(function(err, apiResponse) {});
});

//-
// If the callback is omitted, we'll return a Promise.
//-
database.createBatchTransaction().then(function(data) {
  var transaction = data[0];
  return transaction.close();
});

commit

commit(callback) returns Promise containing BasicResponse

Commit the transaction.

Wrapper around v1.SpannerClient#commit.

Parameter

callback

Optional

Callback function.

Inherited from
Transaction#commit
See also
v1.SpannerClient#commit

Commit API Documentation

Throws

If transaction has already been ended.

Returns

Example

const Spanner = require('@google-cloud/spanner');
const spanner = new Spanner();

const instance = spanner.instance('my-instance');
const database = instance.database('my-database');

database.runTransaction(function(err, transaction) {
  if (err) {
    // Error handling omitted.
  }

  // Queue a mutation (note that there is no callback passed to `insert`).
  transaction.insert('Singers', {
    SingerId: 'Id3b',
    Name: 'Joe West'
  });

  // Commit the transaction.
  transaction.commit(function(err) {
    if (!err) {
      // Mutations were committed successfully.
    }
  });
});

createQueryPartitions

createQueryPartitions(query, callback) returns Promise containing CreateQueryPartitionsResponse

Creates a set of query partitions that can be used to execute a query operation in parallel. Partitions become invalid when the transaction used to create them is closed.

Parameter

query

(string or object)

A SQL query or ExecuteSqlRequest object.

callback

Optional

CreateQueryPartitionsCallback

Callback callback function.

Returns

Promise containing CreateQueryPartitionsResponse 

Examples

// Imports the Google Cloud client library
const Spanner = require('@google-cloud/spanner');

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const projectId = 'my-project-id';
// const instanceId = 'my-instance';
// const databaseId = 'my-database';
// const identifier = {};

// Creates a client
const spanner = new Spanner({
  projectId: projectId,
});

// Gets a reference to a Cloud Spanner instance and database
const instance = spanner.instance(instanceId);
const database = instance.database(databaseId);
const transaction = database.batchTransaction(identifier);

const query = 'SELECT * FROM Singers';

transaction
  .createQueryPartitions(query)
  .then(data => {
    const partitions = data[0];
    console.log(
      `Successfully created ${partitions.length} query partitions.`
    );
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

createReadPartitions

createReadPartitions(options, callback) returns Promise containing CreateReadPartitionsResponse

Creates a set of read partitions that can be used to execute a read operation in parallel. Partitions become invalid when the transaction used to create them is closed.

Parameter

options

ReadRequestOptions

Configuration object, describing what to read from.

callback

Optional

CreateReadPartitionsCallback

Callback function.

Returns

Promise containing CreateReadPartitionsResponse 

createReadStream

createReadStream(table, query) returns ReadableStream

Create a readable object stream to receive rows from the database using key lookups and scans.

Wrapper around v1.SpannerClient#streamingRead.

Parameter

table

The table to read from.

query

Configuration object. See ReadRequest.

Inherited from
TransactionRequest#createReadStream
See also
v1.SpannerClient#streamingRead

StreamingRead API Documentation

ReadRequest API Documentation

Returns

A readable stream that emits rows.

Example

const Spanner = require('@google-cloud/spanner');
const spanner = new Spanner();

const instance = spanner.instance('my-instance');
const database = instance.database('my-database');

database.runTransaction(function(err, transaction) {
  if (err) {
    // Error handling omitted.
  }

  transaction.createReadStream('Singers', {
      keys: ['1'],
      columns: ['SingerId', 'name']
    })
    .on('error', function(err) {})
    .on('data', function(row) {
      // row = [
      //   {
      //     name: 'SingerId',
      //     value: '1'
      //   },
      //   {
      //     name: 'Name',
      //     value: 'Eddie Wilson'
      //   }
      // ]
    })
    .on('end', function() {
      // All results retrieved.
    });
});

//-
// Provide an array for `query.keys` to read with a composite key.
//-
const query = {
  keys: [
    [
      'Id1',
      'Name1'
    ],
    [
      'Id2',
      'Name2'
    ]
  ],
  // ...
};

//-
// Rows are returned as an array of object arrays. Each object has a `name`
// and `value` property. To get a serialized object, call `toJSON()`.
//-
database.runTransaction(function(err, transaction) {
  if (err) {
    // Error handling omitted.
  }

  transaction.createReadStream('Singers', {
      keys: ['1'],
      columns: ['SingerId', 'name']
    })
    .on('error', function(err) {})
    .on('data', function(row) {
      // row.toJSON() = {
      //   SingerId: '1',
      //   Name: 'Eddie Wilson'
      // }
    })
    .on('end', function() {
      // All results retrieved.
    });
});

//-
// Alternatively, set `query.json` to `true`, and this step will be performed
// automaticaly.
//-
database.runTransaction(function(err, transaction) {
  if (err) {
    // Error handling omitted.
  }

  transaction.createReadStream('Singers', {
      keys: ['1'],
      columns: ['SingerId', 'name'],
      json: true,
    })
    .on('error', function(err) {})
    .on('data', function(row) {
      // row = {
      //   SingerId: '1',
      //   Name: 'Eddie Wilson'
      // }
    })
    .on('end', function() {
      // All results retrieved.
    });
});

//-
// If you anticipate many results, you can end a stream early to prevent
// unnecessary processing and API requests.
//-
database.runTransaction(function(err, transaction) {
  if (err) {
    // Error handling omitted.
  }

  transaction.createReadStream('Singers', {
      keys: ['1'],
      columns: ['SingerId', 'name']
    })
    .on('data', function(row) {
      this.end();
    });
});

deleteRows

deleteRows(table, keys)

Delete rows from a table.

Parameter

table

The name of the table.

keys

The keys for the rows to delete. If using a composite key, provide an array within this array. See the example below.

Inherited from
TransactionRequest#deleteRows
See also

Commit API Documentation

Example

const Spanner = require('@google-cloud/spanner');
const spanner = new Spanner();

const instance = spanner.instance('my-instance');
const database = instance.database('my-database');

const keys = ['Id1', 'Id2', 'Id3'];

database.runTransaction(function(err, transaction) {
  if (err) {
    // Error handling omitted.
  }

  // Queue this mutation until later calling `commit`.
  // Note that a callback is not passed to `deleteRows`.
  transaction.deleteRows('Singers', keys);

  // Commit the transaction.
  transaction.commit(function(err) {
    if (!err) {
      // The rows were deleted successfully.
    }
  });
});

//-
// Provide an array for `keys` to delete rows with a composite key.
//-
const keys = [
  [
    'Id1',
    'Name1'
  ],
  [
    'Id2',
    'Name2'
  ]
];

end

end(callback)

Let the client know you're done with a particular transaction. This should only be called for read-only transactions.

Parameter

callback

Optional callback function to be called after transaction has ended.

Inherited from
Transaction#end
Throws

If transaction has already been ended.

Example

const Spanner = require('@google-cloud/spanner');
const spanner = new Spanner();

const instance = spanner.instance('my-instance');
const database = instance.database('my-database');

const options = {
  readOnly: true
};

database.runTransaction(options, function(err, transaction) {
  if (err) {
    // Error handling omitted.
  }

  transaction.run('SELECT * FROM Singers', function(err, rows) {
    if (err) {
      // Error handling omitted.
    }

    // End the transaction. Note that no callback is provided.
    transaction.end();
  });
});

execute

execute(partition, callback) returns (Promise containing RunResponse or Promise containing TransactionRequestReadResponse)

Executes partition.

Parameter

partition

(ReadPartition or QueryParition)

The partition object.

callback

(TransactionRequestReadCallback or RunCallback)

Callback function.

See also
Transaction#read when using ReadPartition.
Transaction#run when using QueryParition.
Returns

(Promise containing RunResponse or Promise containing TransactionRequestReadResponse) 

Examples

// Imports the Google Cloud client library
const Spanner = require('@google-cloud/spanner');

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const projectId = 'my-project-id';
// const instanceId = 'my-instance';
// const databaseId = 'my-database';
// const identifier = {};
// const partition = {};

// Creates a client
const spanner = new Spanner({
  projectId: projectId,
});

// Gets a reference to a Cloud Spanner instance and database
const instance = spanner.instance(instanceId);
const database = instance.database(databaseId);
const transaction = database.batchTransaction(identifier);

transaction
  .execute(partition)
  .then(data => {
    const rows = data[0];
    console.log(
      `Successfully received ${rows.length} from executed partition.`
    );
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

executeStream

executeStream(partition) returns ReadableStream

Executes partition in streaming mode.

Parameter

partition

(ReadPartition or QueryPartition)

The partition object.

See also
Transaction#createReadStream when using ReadPartition.
Transaction#runStream when using QueryPartition.
Returns

ReadableStream 

A readable stream that emits rows.

Example

const Spanner = require('@google-cloud/spanner');
const spanner = new Spanner();

const instance = spanner.instance('my-instance');
const database = instance.database('my-database');

database.createBatchTransaction(function(err, transaction) {
  if (err) {
    // Error handling omitted.
  }

  transaction.createReadPartitions(options, function(err, partitions) {
    const partition = partitions[0];

    transaction
      .executeStream(partition)
      .on('error', function(err) {})
      .on('data', function(row) {
        // row = [
        //   {
        //     name: 'SingerId',
        //     value: '1'
        //   },
        //   {
        //     name: 'Name',
        //     value: 'Eddie Wilson'
        //   }
        // ]
      })
      .on('end', function() {
        // All results retrieved
      });
  });
});

identifier

identifier() returns TransactionIdentifier

Creates a transaction identifier used to reference the transaction in workers.

Returns

TransactionIdentifier 

Example

const Spanner = require('@google-cloud/spanner');
const spanner = new Spanner();

const instance = spanner.instance('my-instance');
const database = instance.database('my-database');

database.createBatchTransaction(function(err, transaction) {
  const identifier = transaction.identifier();
});

insert

insert(table, keyVals)

Insert rows of data into this table.

Parameter

table

The name of the table.

keyVals

A map of names to values of data to insert into this table.

Inherited from
TransactionRequest#insert
See also

Commit API Documentation

Example

const Spanner = require('@google-cloud/spanner');
const spanner = new Spanner();

const instance = spanner.instance('my-instance');
const database = instance.database('my-database');

const row = {
  SingerId: 'Id3',
  Name: 'Eddie Wilson'
};

database.runTransaction(function(err, transaction) {
  if (err) {
    // Error handling omitted.
  }

  // Queue this mutation until later calling `commit`.
  // Note that a callback is not passed to `insert`.
  transaction.insert('Singers', row);

  // Commit the transaction.
  transaction.commit(function(err) {
    if (!err) {
      // The row was inserted successfully.
    }
  });
});

//-
// Multiple rows can be inserted at once.
//-
const row2 = {
  SingerId: 'Id3b',
  Name: 'Joe West'
};

database.runTransaction(function(err, transaction) {
  if (err) {
    // Error handling omitted.
  }

  // Queue multiple mutations until later calling `commit`.
  // Note that a callback is not passed to `insert`.
  transaction.insert('Singers', [
    row,
    row2
  ]);

  // Commit the transaction.
  transaction.commit(function(err) {
    if (!err) {
      // The rows were inserted successfully.
    }
  });
});

read

read(table, query, callback) returns Promise containing TransactionRequestReadResponse

Performs a read request against the specified Table.

Wrapper around v1.SpannerClient#read.

Parameter

table

The table to read from.

query

Configuration object, describing what to read from the table.

callback

Optional

Callback function.

Inherited from
TransactionRequest#read
See also
v1.SpannerClient#read
Returns

Example

const Spanner = require('@google-cloud/spanner');
const spanner = new Spanner();

const instance = spanner.instance('my-instance');
const database = instance.database('my-database');

const query = {
  keys: ['1'],
  columns: ['SingerId', 'name']
};

database.runTransaction(function(err, transaction) {
  if (err) {
    // Error handling omitted.
  }

  transaction.read('Singers', query, function(err, rows) {
    if (err) {
      // Error handling omitted.
    }

    const firstRow = rows[0];

    // firstRow = [
    //   {
    //     name: 'SingerId',
    //     value: '1'
    //   },
    //   {
    //     name: 'Name',
    //     value: 'Eddie Wilson'
    //   }
    // ]

    // End the transaction. Note that no callback is provided.
    transaction.end();
  });
});

//-
// Provide an array for `query.keys` to read with a composite key.
//-
const query = {
  keys: [
    [
      'Id1',
      'Name1'
    ],
    [
      'Id2',
      'Name2'
    ]
  ],
  // ...
};

//-
// Rows are returned as an array of object arrays. Each object has a `name`
// and `value` property. To get a serialized object, call `toJSON()`.
//-
database.runTransaction(function(err, transaction) {
  if (err) {
    // Error handling omitted.
  }

  transaction.read('Singers', query, function(err, rows) {
    if (err) {
      // Error handling omitted.
    }

    const firstRow = rows[0];

    // firstRow.toJSON() = {
    //   SingerId: '1',
    //   Name: 'Eddie Wilson'
    // }

    // End the transaction. Note that no callback is provided.
    transaction.end();
  });
});

//-
// Alternatively, set `query.json` to `true`, and this step will be performed
// automaticaly.
//-
database.runTransaction(function(err, transaction) {
  if (err) {
    // Error handling omitted.
  }

  query.json = true;

  transaction.read('Singers', query, function(err, rows) {
    if (err) {
      // Error handling omitted.
    }

    const firstRow = rows[0];

    // firstRow = {
    //   SingerId: '1',
    //   Name: 'Eddie Wilson'
    // }

    // End the transaction. Note that no callback is provided.
    transaction.end();
  });
});

replace

replace(table, keyVals)

Replace rows of data within a table.

Parameter

table

The table to read from.

keyVals

A map of names to values of data to insert into this table.

Inherited from
TransactionRequest#replace
See also

Commit API Documentation

Example

const Spanner = require('@google-cloud/spanner');
const spanner = new Spanner();

const instance = spanner.instance('my-instance');
const database = instance.database('my-database');

const row = {
  SingerId: 'Id3',
  Name: 'Joe West'
};

database.runTransaction(function(err, transaction) {
  if (err) {
    // Error handling omitted.
  }

  // Queue this mutation until later calling `commit`.
  // Note that a callback is not passed to `replace`.
  transaction.replace('Singers', row);

  // Commit the transaction.
  transaction.commit(function(err) {
    if (!err) {
      // The row was replaced successfully.
    }
  });
});

rollback

rollback(callback) returns Promise containing BasicResponse

Roll back a transaction, releasing any locks it holds. It is a good idea to call this for any transaction that includes one or more queries that you decide not to commit.

Wrapper around v1.SpannerClient#rollback.

Parameter

callback

Optional

Callback function.

Inherited from
Transaction#rollback
See also
v1.SpannerClient#rollback

Rollback API Documentation

Returns

Example

const Spanner = require('@google-cloud/spanner');
const spanner = new Spanner();

const instance = spanner.instance('my-instance');
const database = instance.database('my-database');

database.runTransaction(function(err, transaction) {
  if (err) {
    // Error handling omitted.
  }

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

run

run(query, callback) returns Promise containing RunResponse

Execute a SQL statement on this database inside of a transaction.

Performance Considerations:

This method wraps the streaming method, Transaction#run for your convenience. All rows will be stored in memory before being released to your callback. If you intend on receiving a lot of results from your query, consider using the streaming method, so you can free each result from memory after consuming it.

Wrapper around v1.SpannerClient#executeStreamingSql.

Parameter

query

A SQL query or ExecuteSqlRequest object.

callback

Optional

Callback function.

Inherited from
Transaction#run
See also
v1.SpannerClient#executeStreamingSql

ExecuteStreamingSql API Documentation

ExecuteSqlRequest API Documentation

Returns

Example

const Spanner = require('@google-cloud/spanner');
const spanner = new Spanner();

const instance = spanner.instance('my-instance');
const database = instance.database('my-database');

const query = 'SELECT * FROM Singers';

database.runTransaction(function(err, transaction) {
  if (err) {
    // Error handling omitted.
  }

  transaction.run(query, function(err, rows) {
    if (err) {
      // Error handling omitted.
    }

    // rows = [
    //   {
    //     SingerId: '1',
    //     Name: 'Eddie Wilson'
    //   }
    // ]
  });
});

//-
// The SQL query string can contain parameter placeholders. A parameter
// placeholder consists of '@' followed by the parameter name.
//-
database.runTransaction(function(err, transaction) {
  if (err) {
    // Error handling omitted.
  }

  const query = {
    sql: 'SELECT * FROM Singers WHERE name = @name',
    params: {
      name: 'Eddie Wilson'
    }
  };

  transaction.run(query, function(err, rows) {});
});

//-
// If you need to enforce a specific param type, a types map can be provided.
// This is typically useful if your param value can be null.
//-
database.runTransaction(function(err, transaction) {
  if (err) {
    // Error handling omitted.
  }

  const query = {
    sql: 'SELECT * FROM Singers WHERE name = @name AND id = @id',
    params: {
      id: spanner.int(8),
      name: null
    },
    types: {
      id: 'int64',
      name: 'string'
    }
  };

  transaction.run(query, function(err, rows) {});
});

runStream

runStream(query) returns ReadableStream

Create a readable object stream to receive resulting rows from a SQL statement.

Wrapper around v1.SpannerClient#executeStreamingSql.

Parameter

query

A SQL query or ExecuteSqlRequest object.

Inherited from
Transaction#runStream
See also
v1.SpannerClient#executeStreamingSql

ExecuteStreamingSql API Documentation

ExecuteSqlRequest API Documentation

Returns

Example

const Spanner = require('@google-cloud/spanner');
const spanner = new Spanner();

const instance = spanner.instance('my-instance');
const database = instance.database('my-database');

const query = 'SELECT * FROM Singers';

database.runTransaction(function(err, transaction) {
  if (err) {
    // Error handling omitted.
  }

  transaction.runStream(query)
    .on('error', function(err) {})
    .on('data', function(row) {
      // row = {
      //   SingerId: '1',
      //   Name: 'Eddie Wilson'
      // }
    })
    .on('end', function() {
      // All results retrieved.
    });
});

//-
// The SQL query string can contain parameter placeholders. A parameter
// placeholder consists of '@' followed by the parameter name.
//-
database.runTransaction(function(err, transaction) {
  if (err) {
    // Error handling omitted.
  }

  const query = {
    sql: 'SELECT * FROM Singers WHERE name = @name',
    params: {
      name: 'Eddie Wilson'
    }
  };

  transaction.runStream(query)
    .on('error', function(err) {})
    .on('data', function(row) {})
    .on('end', function() {});
});

//-
// If you anticipate many results, you can end a stream early to prevent
// unnecessary processing and API requests.
//-
database.runTransaction(function(err, transaction) {
  if (err) {
    // Error handling omitted.
  }

  transaction.runStream(query)
    .on('data', function(row) {
      this.end();
    })
    .on('end', function() {});
});

shouldRetry_

shouldRetry_(err) returns boolean

Determines whether or not this Transaction should be retried in the event of an ABORTED error.

Parameter

err

The request error.

Inherited from
Transaction#shouldRetry_
Returns

update

update(table, keyVals)

Update rows of data within a table.

Parameter

table

The table to read from.

keyVals

A map of names to values of data to insert into this table.

Inherited from
TransactionRequest#update
See also

Commit API Documentation

Example

const Spanner = require('@google-cloud/spanner');
const spanner = new Spanner();

const instance = spanner.instance('my-instance');
const database = instance.database('my-database');

const row = {
  SingerId: 'Id3',
  Name: 'Joe West'
};

database.runTransaction(function(err, transaction) {
  if (err) {
    // Error handling omitted.
  }

  // Queue this mutation until later calling `commit`.
  // Note that a callback is not passed to `update`.
  transaction.update('Singers', row);

  // Commit the transaction.
  transaction.commit(function(err) {
    if (!err) {
      // The row was updated successfully.
    }
  });
});

upsert

upsert(table, keyVals)

Insert or update rows of data within a table.

Parameter

table

The table to read from.

keyVals

A map of names to values of data to insert into this table.

Inherited from
TransactionRequest#upsert
See also

Commit API Documentation

Example

const Spanner = require('@google-cloud/spanner');
const spanner = new Spanner();

const instance = spanner.instance('my-instance');
const database = instance.database('my-database');

const row = {
  SingerId: 'Id3',
  Name: 'Joe West'
};

database.runTransaction(function(err, transaction) {
  if (err) {
    // Error handling omitted.
  }

  // Queue this mutation until later calling `commit`.
  // Note that a callback is not passed to `upsert`.
  transaction.upsert('Singers', row);

  // Commit the transaction.
  transaction.commit(function(err) {
    if (!err) {
      // The row was updated or inserted successfully.
    }
  });
});