Constructor
new Database(name, options, queryOptions)
Parameters:
Name | Type | Description |
---|---|---|
name |
string |
Name of the database. |
options |
SessionPoolOptions | SessionPoolInterface |
Session pool configuration options or custom pool interface. |
queryOptions |
spannerClient.spanner.v1.ExecuteSqlRequest.IQueryOptions |
The default query options to use for queries on the database. |
Methods
batchCreateSessions(options, callbackopt) → {Promise.<BatchCreateSessionsResponse>}
Create a batch of sessions, which can be used to perform transactions that read and/or modify data.
It is unlikely you will need to interact with sessions directly. By default, sessions are created and utilized for maximum performance automatically.
Wrapper around v1.SpannerClient#batchCreateSessions.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
options |
number | BatchCreateSessionsOptions |
Desired session count or a configuration object. |
|
callback |
BatchCreateSessionsCallback |
<optional> |
Callback function. |
Returns:
Type | Description |
---|---|
Promise.<BatchCreateSessionsResponse> |
Examples
const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();
const instance = spanner.instance('my-instance');
const database = instance.database('my-database');
const count = 5;
database.batchCreateSession(count, (err, sessions, response) => {
if (err) {
// Error handling omitted.
}
// `sessions` is an array of Session objects.
});
If the callback is omitted, we'll return a Promise.
const [sessions, response] = await database.batchCreateSessions(count);
batchTransaction(identifier, optionsopt) → {BatchTransaction}
Get a reference to a BatchTransaction object.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
identifier |
TransactionIdentifier |
The transaction identifier. |
|
options |
TransactionOptions |
<optional> |
Returns:
Type | Description |
---|---|
BatchTransaction |
A batch transaction object. |
- See:
-
- BatchTransaction#identifier to generate an identifier.
Example
const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();
const instance = spanner.instance('my-instance');
const database = instance.database('my-database');
const transaction = database.batchTransaction({
session: 'my-session',
transaction: 'my-transaction',
readTimestamp: 1518464696657
});
close(callbackopt) → {Promise}
Close the database connection and destroy all sessions associated with it.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
callback |
CloseDatabaseCallback |
<optional> |
Callback function. |
Returns:
Type | Description |
---|---|
Promise |
Example
const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();
const instance = spanner.instance('my-instance');
const database = instance.database('my-database');
database.close(function(err) {
if (err) {
// Error handling omitted.
}
});
//-
// In the event of a session leak, the error object will contain a
// `messages` field.
//-
database.close(function(err) {
if (err && err.messages) {
err.messages.forEach(function(message) {
console.error(message);
});
}
});
create(optionsopt, callbackopt) → {Promise.<CreateDatabaseResponse>}
Create a database.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
options |
CreateDatabaseRequest |
<optional> |
Configuration object. |
callback |
CreateDatabaseCallback |
<optional> |
Callback function. |
Returns:
Type | Description |
---|---|
Promise.<CreateDatabaseResponse> |
Example
const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();
const instance = spanner.instance('my-instance');
const database = instance.database('my-database');
database.create(function(err, database, operation, apiResponse) {
if (err) {
// Error handling omitted.
}
operation
.on('error', function(err) {})
.on('complete', function() {
// Database created successfully.
});
});
//-
// If the callback is omitted, we'll return a Promise.
//-
database.create()
.then(function(data) {
const operation = data[0];
const apiResponse = data[1];
return operation.promise();
})
.then(function() {
// Database created successfully.
});
createBatchTransaction(optionsopt, callbackopt) → {Promise.<CreateTransactionResponse>}
Create a transaction that can be used for batch querying.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
options |
TransactionOptions |
<optional> |
|
callback |
CreateTransactionCallback |
<optional> |
Callback function. |
Returns:
Type | Description |
---|---|
Promise.<CreateTransactionResponse> |
createSession(optionsopt, callbackopt) → {Promise.<CreateSessionResponse>}
Create a new session, which can be used to perform transactions that read and/or modify data.
Sessions can only execute one transaction at a time. To execute multiple concurrent read-write/write-only transactions, create multiple sessions. Note that standalone reads and queries use a transaction internally, and count toward the one transaction limit.
It is unlikely you will need to interact with sessions directly. By default, sessions are created and utilized for maximum performance automatically.
Wrapper around v1.SpannerClient#createSession.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
options |
object |
<optional> |
Configuration object. |
callback |
CreateSessionCallback |
<optional> |
Callback function. |
Returns:
Type | Description |
---|---|
Promise.<CreateSessionResponse> |
Example
const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();
const instance = spanner.instance('my-instance');
const database = instance.database('my-database');
database.createSession(function(err, session, apiResponse) {
if (err) {
// Error handling omitted.
}
// `session` is a Session object.
});
//-
// If the callback is omitted, we'll return a Promise.
//-
database.createSession().then(function(data) {
const session = data[0];
const apiResponse = data[1];
});
createTable(schema, gaxOptionsopt, callbackopt) → {Promise.<CreateTableResponse>}
Create a table.
Wrapper around Database#updateSchema.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
schema |
string |
A DDL CREATE statement describing the table. |
|
gaxOptions |
object |
<optional> |
Request configuration options, See CallOptions for more details. |
callback |
CreateTableCallback |
<optional> |
Callback function. |
Returns:
Type | Description |
---|---|
Promise.<CreateTableResponse> |
Example
const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();
const instance = spanner.instance('my-instance');
const database = instance.database('my-database');
const schema =
'CREATE TABLE Singers (' +
' SingerId INT64 NOT NULL,' +
' FirstName STRING(1024),' +
' LastName STRING(1024),' +
' SingerInfo BYTES(MAX),' +
') PRIMARY KEY(SingerId)';
database.createTable(schema, function(err, table, operation, apiResponse) {
if (err) {
// Error handling omitted.
}
operation
.on('error', function(err) {})
.on('complete', function() {
// Table created successfully.
});
});
//-
// If the callback is omitted, we'll return a Promise.
//-
database.createTable(schema)
.then(function(data) {
const table = data[0];
const operation = data[1];
return operation.promise();
})
.then(function() {
// Table created successfully.
});
delete(gaxOptionsopt, callbackopt) → {Promise.<DatabaseDeleteResponse>}
Delete the database.
Wrapper around v1.DatabaseAdminClient#dropDatabase.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
gaxOptions |
object |
<optional> |
Request configuration options, See CallOptions for more details. |
callback |
DatabaseDeleteCallback |
<optional> |
Callback function. |
Returns:
Type | Description |
---|---|
Promise.<DatabaseDeleteResponse> |
Example
const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();
const instance = spanner.instance('my-instance');
const database = instance.database('my-database');
database.delete(function(err, apiResponse) {
if (err) {
// Error handling omitted.
}
// Database was deleted successfully.
});
//-
// If the callback is omitted, we'll return a Promise.
//-
database.delete().then(function(data) {
const apiResponse = data[0];
});
exists(gaxOptionsopt, callbackopt) → {Promise.<DatabaseExistsResponse>}
Check if a database exists.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
gaxOptions |
object |
<optional> |
Request configuration options, See CallOptions for more details. |
callback |
DatabaseExistsCallback |
<optional> |
Callback function. |
Returns:
Type | Description |
---|---|
Promise.<DatabaseExistsResponse> |
Example
const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();
const instance = spanner.instance('my-instance');
const database = instance.database('my-database');
database.exists(function(err, exists) {});
//-
// If the callback is omitted, we'll return a Promise.
//-
database.exists().then(function(data) {
const exists = data[0];
});
get(optionsopt, callbackopt) → {Promise.<GetDatabaseResponse>}
Get a database if it exists.
You may optionally use this to "get or create" an object by providing an
object with autoCreate
set to true
. Any extra configuration that is
normally required for the create
method must be contained within this
object as well.
Parameters:
Name | Type | Attributes | Description | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
options |
<optional> |
Configuration object. Properties
|
||||||||||
callback |
GetDatabaseCallback |
<optional> |
Callback function. |
Returns:
Type | Description |
---|---|
Promise.<GetDatabaseResponse> |
Example
const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();
const instance = spanner.instance('my-instance');
const database = instance.database('my-database');
database.get(function(err, database, apiResponse) {
// `database.metadata` has been populated.
});
//-
// If the callback is omitted, we'll return a Promise.
//-
database.get().then(function(data) {
const database = data[0];
const apiResponse = data[0];
});
getMetadata(gaxOptionsopt, callbackopt) → {Promise.<GetMetadataResponse>}
Get the database's metadata.
Wrapper around v1.DatabaseAdminClient#getDatabase.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
gaxOptions |
object |
<optional> |
Request configuration options, See CallOptions for more details. |
callback |
GetMetadataCallback |
<optional> |
Callback function. |
Returns:
Type | Description |
---|---|
Promise.<GetMetadataResponse> |
Example
const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();
const instance = spanner.instance('my-instance');
const database = instance.database('my-database');
database.getMetadata(function(err, metadata) {
if (err) {
// Error handling omitted.
}
// Database was deleted successfully.
});
//-
// If the callback is omitted, we'll return a Promise.
//-
database.getMetadata().then(function(data) {
const metadata = data[0];
const apiResponse = data[1];
});
(async) getOperations(optionsopt) → {Promise.<GetDatabaseOperationsResponse>}
List pending and completed operations for the database.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
options |
GetDatabaseOperationsOptions |
<optional> |
Contains query object for listing database operations and request configuration options, See CallOptions for more details. |
Returns:
Type | Description |
---|---|
Promise.<GetDatabaseOperationsResponse> |
When resolved, contains a paged list of database operations. |
- See:
-
- Instance.getDatabaseOperations
Example
const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();
const instance = spanner.instance('my-instance');
const database = instance.database('my-database');
const [operations] = await database.getOperations();
//-
// To manually handle pagination, set autoPaginate:false in gaxOptions.
//-
let pageToken = undefined;
do {
const [operations, , response] = await database.getOperations({
pageSize: 3,
pageToken,
gaxOptions: {autoPaginate: false},
});
operations.forEach(operation => {
// Do something with operation
});
pageToken = response.nextPageToken;
} while (pageToken);
getRestoreInfo(gaxOptionsopt, callbackopt) → {Promise.<(IRestoreInfoTranslatedEnum|undefined)>}
Retrieves the restore information of the database.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
gaxOptions |
object |
<optional> |
Request configuration options, See CallOptions for more details. |
callback |
GetRestoreInfoCallback |
<optional> |
Callback function. |
Returns:
Type | Description |
---|---|
Promise.<(IRestoreInfoTranslatedEnum|undefined)> |
When resolved, contains the restore information for the database if it was restored from a backup. |
- See:
-
- #getMetadata
Example
const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();
const instance = spanner.instance('my-instance');
const database = instance.database('my-database');
const restoreInfo = await database.getRestoreInfo();
console.log(`Database restored from ${restoreInfo.backupInfo.backup}`);
getSchema(gaxOptionsopt, callbackopt) → {Promise.<GetSchemaResponse>}
Get this database's schema as a list of formatted DDL statements.
Wrapper around v1.DatabaseAdminClient#getDatabaseDdl.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
gaxOptions |
object |
<optional> |
Request configuration options, See CallOptions for more details. |
callback |
GetSchemaCallback |
<optional> |
Callback function. |
Returns:
Type | Description |
---|---|
Promise.<GetSchemaResponse> |
- See:
Example
const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();
const instance = spanner.instance('my-instance');
const database = instance.database('my-database');
database.getSchema(function(err, statements, apiResponse) {});
//-
// If the callback is omitted, we'll return a Promise.
//-
database.getSchema().then(function(data) {
const statements = data[0];
const apiResponse = data[1];
});
getSessions(optionsopt, callbackopt) → {Promise.<GetSessionsResponse>}
Gets a list of sessions.
Wrapper around v1.SpannerClient#listSessions
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
options |
GetSessionsOptions |
<optional> |
Options object for listing sessions. |
callback |
GetSessionsCallback |
<optional> |
Callback function. |
Returns:
Type | Description |
---|---|
Promise.<GetSessionsResponse> |
Example
const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();
const instance = spanner.instance('my-instance');
const database = instance.database('my-database');
database.getSessions(function(err, sessions) {
// `sessions` is an array of `Session` objects.
});
//-
// To control how many API requests are made and page through the results
// manually, set `autoPaginate` to `false`.
//-
function callback(err, sessions, nextQuery, apiResponse) {
if (nextQuery) {
// More results exist.
database.getSessions(nextQuery, callback);
}
}
database.getInstances({
gaxOptions: {autoPaginate: false}
}, callback);
//-
// If the callback is omitted, we'll return a Promise.
//-
database.getInstances().then(function(data) {
const sessions = data[0];
});
getSnapshot(optionsopt, callbackopt) → {Promise.<GetSnapshotResponse>}
Get a read only Snapshot transaction.
Wrapper around v1.SpannerClient#beginTransaction.
NOTE: When finished with the Snapshot, Snapshot#end should be called to release the underlying Session. Failure to do could result in a Session leak.
NOTE: Since the returned Snapshot transaction is not a
single-use transaction, it is invalid to set the minReadTimestamp
and
maxStaleness
parameters in TimestampBounds as those parameters
can only be set for single-use transactions.
https://cloud.google.com/spanner/docs/reference/rest/v1/TransactionOptions#bounded-staleness
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
options |
TimestampBounds |
<optional> |
Timestamp bounds. |
callback |
GetSnapshotCallback |
<optional> |
Callback function. |
Returns:
Type | Description |
---|---|
Promise.<GetSnapshotResponse> |
Examples
const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();
const instance = spanner.instance('my-instance');
const database = instance.database('my-database');
database.getSnapshot(function(err, transaction) {
if (err) {
// Error handling omitted.
}
// Should be called when finished with Snapshot.
transaction.end();
});
If the callback is omitted, we'll return a Promise.
database.getSnapshot().then(function(data) {
const transaction = data[0];
});
Read-only transaction:
// 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';
// 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);
// Gets a transaction object that captures the database state
// at a specific point in time
database.getSnapshot(async (err, transaction) => {
if (err) {
console.error(err);
return;
}
const queryOne = 'SELECT SingerId, AlbumId, AlbumTitle FROM Albums';
try {
// Read #1, using SQL
const [qOneRows] = await transaction.run(queryOne);
qOneRows.forEach(row => {
const json = row.toJSON();
console.log(
`SingerId: ${json.SingerId}, AlbumId: ${json.AlbumId}, AlbumTitle: ${json.AlbumTitle}`
);
});
const queryTwo = {
columns: ['SingerId', 'AlbumId', 'AlbumTitle'],
};
// Read #2, using the `read` method. Even if changes occur
// in-between the reads, the transaction ensures that both
// return the same data.
const [qTwoRows] = await transaction.read('Albums', queryTwo);
qTwoRows.forEach(row => {
const json = row.toJSON();
console.log(
`SingerId: ${json.SingerId}, AlbumId: ${json.AlbumId}, AlbumTitle: ${json.AlbumTitle}`
);
});
console.log('Successfully executed read-only transaction.');
} catch (err) {
console.error('ERROR:', err);
} finally {
transaction.end();
// Close the database when finished.
await database.close();
}
});
getState(gaxOptionsopt, callbackopt) → {Promise.<(EnumKey.<typeof, databaseAdmin.spanner.admin.database.v1.Database.State>|undefined)>}
Retrieves the state of the database.
The database state indicates if the database is ready after creation or after being restored from a backup.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
gaxOptions |
object |
<optional> |
Request configuration options, See CallOptions for more details. |
callback |
GetStateCallback |
<optional> |
Callback function. |
Returns:
Type | Description |
---|---|
Promise.<(EnumKey.<typeof, databaseAdmin.spanner.admin.database.v1.Database.State>|undefined)> |
When resolved, contains the current state of the database if the state is defined. |
- See:
-
- #getMetadata
Example
const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();
const instance = spanner.instance('my-instance');
const database = instance.database('my-database');
const state = await database.getState();
const isReady = (state === 'READY');
getTransaction(callbackopt) → {Promise.<GetTransactionResponse>}
Get a read/write ready Transaction object.
NOTE: In the event that you encounter an error while reading/writing, if you decide to forgo calling Transaction#commit or Transaction#rollback, then you need to call Transaction#end to release the underlying Session object. Failure to do could result in a Session leak.
Wrapper around v1.SpannerClient#beginTransaction.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
callback |
GetTransactionCallback |
<optional> |
Callback function. |
Returns:
Type | Description |
---|---|
Promise.<GetTransactionResponse> |
Examples
const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();
const instance = spanner.instance('my-instance');
const database = instance.database('my-database');
database.getTransaction(function(err, transaction) {});
If the callback is omitted, we'll return a Promise.
database.getTransaction().then(function(data) {
const transaction = data[0];
});
restore(backupPath, gaxOptionsopt)
Restore a backup into this database.
When this call completes, the restore will have commenced but will not necessarily have completed.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
backupPath |
The path of the backup to restore. |
||
gaxOptions |
object |
<optional> |
Request configuration options, See CallOptions for more details. |
Returns:
Type | Description |
---|---|
Promise |
Example
const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();
const instance = spanner.instance('my-instance');
const database = instance.database('my-database');
const backupName = 'projects/my-project/instances/my-instance/backups/my-backup';
const [, restoreOperation] = await database.restore(backupName);
// Wait for restore to complete
await restoreOperation.promise();
//-
// Restore database with a different encryption key to the one used by the
// backup.
//-
const [, restoreWithKeyOperation] = await database.restore(
backupName,
{
encryptionConfig: {
encryptionType: 'CUSTOMER_MANAGED_ENCRYPTION',
kmsKeyName: 'projects/my-project-id/my-region/keyRings/my-key-ring/cryptoKeys/my-key',
}
},
);
// Wait for restore to complete
await restoreWithKeyOperation.promise();
run(query, optionsopt, callbackopt) → {Promise.<RunResponse>}
Execute a SQL statement on this database.
Wrapper around v1.SpannerClient#executeStreamingSql.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
query |
string | ExecuteSqlRequest |
A SQL query or ExecuteSqlRequest object. |
|
options |
TimestampBounds |
<optional> |
Snapshot timestamp bounds. |
callback |
RunCallback |
<optional> |
Callback function. |
Returns:
Type | Description |
---|---|
Promise.<RunResponse> |
Examples
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.run(query, function(err, rows) {
if (err) {
// Error handling omitted.
}
const firstRow = rows[0];
// firstRow = [
// {
// name: 'SingerId',
// value: '1'
// },
// {
// name: 'Name',
// value: 'Eddie Wilson'
// }
// ]
});
//-
// 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.run(query, function(err, rows) {
if (err) {
// Error handling omitted.
}
const firstRow = rows[0];
// firstRow.toJSON() = {
// SingerId: '1',
// Name: 'Eddie Wilson'
// }
});
//-
// Alternatively, set `query.json` to `true`, and this step will be performed
// automatically.
//-
database.run(query, function(err, rows) {
if (err) {
// Error handling omitted.
}
const firstRow = rows[0];
// firstRow = {
// SingerId: '1',
// Name: 'Eddie Wilson'
// }
});
//-
// The SQL query string can contain parameter placeholders. A parameter
// placeholder consists of '@' followed by the parameter name.
//-
const query = {
sql: 'SELECT * FROM Singers WHERE name = @name',
params: {
name: 'Eddie Wilson'
}
};
database.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.
//-
const query = {
sql: 'SELECT * FROM Singers WHERE name = @name AND id = @id',
params: {
id: spanner.int(8),
name: null
},
types: {
id: 'int64',
name: 'string'
}
};
database.run(query, function(err, rows) {});
//-
// If the callback is omitted, we'll return a Promise.
//-
database.run(query).then(function(data) {
const rows = data[0];
});
Full example:
// 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';
// 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 query = {
sql: 'SELECT SingerId, AlbumId, AlbumTitle FROM Albums',
};
// Queries rows from the Albums table
try {
const [rows] = await database.run(query);
rows.forEach(row => {
const json = row.toJSON();
console.log(
`SingerId: ${json.SingerId}, AlbumId: ${json.AlbumId}, AlbumTitle: ${json.AlbumTitle}`
);
});
} catch (err) {
console.error('ERROR:', err);
} finally {
// Close the database when finished.
await database.close();
}
Querying data with an index:
// 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 startTitle = 'Ardvark';
// const endTitle = 'Goo';
// 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 query = {
sql: `SELECT AlbumId, AlbumTitle, MarketingBudget
FROM Albums@{FORCE_INDEX=AlbumsByAlbumTitle}
WHERE AlbumTitle >= @startTitle AND AlbumTitle <= @endTitle`,
params: {
startTitle: startTitle,
endTitle: endTitle,
},
};
// Queries rows from the Albums table
try {
const [rows] = await database.run(query);
rows.forEach(row => {
const json = row.toJSON();
const marketingBudget = json.MarketingBudget
? json.MarketingBudget
: null; // This value is nullable
console.log(
`AlbumId: ${json.AlbumId}, AlbumTitle: ${json.AlbumTitle}, MarketingBudget: ${marketingBudget}`
);
});
} catch (err) {
console.error('ERROR:', err);
} finally {
// Close the database when finished.
database.close();
}
runPartitionedUpdate(query, callbackopt) → {Promise.<RunUpdateResponse>}
Partitioned DML transactions are used to execute DML statements with a different execution strategy that provides different, and often better, scalability properties for large, table-wide operations than DML in a Transaction transaction. Smaller scoped statements, such as an OLTP workload, should prefer using Transaction transactions.
Parameters:
Name | Type | Attributes | Description | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
query |
string | object |
A DML statement or
Properties
|
|||||||||||||
callback |
RunUpdateCallback |
<optional> |
Callback function. |
Returns:
Type | Description |
---|---|
Promise.<RunUpdateResponse> |
runStream(query, optionsopt) → {ReadableStream}
Create a readable object stream to receive resulting rows from a SQL statement.
Wrapper around v1.SpannerClient#executeStreamingSql.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
query |
string | ExecuteSqlRequest |
A SQL query or ExecuteSqlRequest object. |
|
options |
TimestampBounds |
<optional> |
Snapshot timestamp bounds. |
Returns:
Type | Description |
---|---|
ReadableStream |
A readable stream that emits rows. |
Fires:
- PartialResultStream#event:response
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.runStream(query)
.on('error', function(err) {})
.on('data', function(row) {
// row = [
// {
// name: 'SingerId',
// value: '1'
// },
// {
// name: 'Name',
// value: 'Eddie Wilson'
// }
// ]
// ]
})
.on('end', function() {
// All results retrieved.
});
//-
// Rows are returned as an array of objects. Each object has a `name` and
// `value` property. To get a serialized object, call `toJSON()`.
//-
database.runStream(query)
.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
// automatically.
//-
query.json = true;
database.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.
//-
const query = {
sql: 'SELECT * FROM Singers WHERE name = @name',
params: {
name: 'Eddie Wilson'
}
};
database.runStream(query)
.on('error', function(err) {})
.on('data', function(row) {})
.on('end', function() {});
//-
// 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.
//-
const query = {
sql: 'SELECT * FROM Singers WHERE name = @name',
params: {
name: 'Eddie Wilson'
},
types: {
name: 'string'
}
};
database.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.runStream(query)
.on('data', function(row) {
this.end();
});
runTransaction(optionsopt, callback)
A transaction in Cloud Spanner is a set of reads and writes that execute atomically at a single logical point in time across columns, rows, and tables in a database.
Note that Cloud Spanner does not support nested transactions. If a new transaction is started inside of the run function, it will be an independent transaction.
The callback you provide to this function will become the "run function". It will be executed with either an error or a Transaction object. The Transaction object will let you run queries and queue mutations until you are ready to Transaction#commit.
In the event that an aborted error occurs, we will re-run the runFn
in its
entirety. If you prefer to handle aborted errors for yourself please refer to
Database#getTransaction.
NOTE: In the event that you encounter an error while reading/writing, if you decide to forgo calling Transaction#commit or Transaction#rollback, then you need to call Transaction#end to release the underlying Session object. Failure to do could result in a Session leak.
For a more complete listing of functionality available to a Transaction, see the Transaction API documentation. For a general overview of transactions within Cloud Spanner, see Transactions from the official Cloud Spanner documentation.
If you would like to run a transaction and receive a promise or use async/await, use Database#runTransactionAsync.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
options |
RunTransactionOptions |
<optional> |
Transaction runner options. |
callback |
RunTransactionCallback |
A function to execute in the context of a transaction. |
- See:
Examples
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.
}
// Run a transactional query.
transaction.run('SELECT * FROM Singers', function(err, rows) {
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) {
// Transaction committed successfully.
}
});
});
});
Read-write transaction:
// This sample transfers 200,000 from the MarketingBudget field
// of the second Album to the first Album, as long as the second
// Album has enough money in its budget. Make sure to run the
// addColumn and updateData samples first (in that order).
// 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';
// 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 transferAmount = 200000;
database.runTransaction(async (err, transaction) => {
if (err) {
console.error(err);
return;
}
let firstBudget, secondBudget;
const queryOne = {
columns: ['MarketingBudget'],
keys: [[2, 2]], // SingerId: 2, AlbumId: 2
};
const queryTwo = {
columns: ['MarketingBudget'],
keys: [[1, 1]], // SingerId: 1, AlbumId: 1
};
Promise.all([
// Reads the second album's budget
transaction.read('Albums', queryOne).then(results => {
// Gets second album's budget
const rows = results[0].map(row => row.toJSON());
secondBudget = rows[0].MarketingBudget;
console.log(`The second album's marketing budget: ${secondBudget}`);
// Makes sure the second album's budget is large enough
if (secondBudget < transferAmount) {
throw new Error(
`The second album's budget (${secondBudget}) is less than the transfer amount (${transferAmount}).`
);
}
}),
// Reads the first album's budget
transaction.read('Albums', queryTwo).then(results => {
// Gets first album's budget
const rows = results[0].map(row => row.toJSON());
firstBudget = rows[0].MarketingBudget;
console.log(`The first album's marketing budget: ${firstBudget}`);
}),
])
.then(() => {
console.log(firstBudget, secondBudget);
// Transfers the budgets between the albums
firstBudget += transferAmount;
secondBudget -= transferAmount;
console.log(firstBudget, secondBudget);
// Updates the database
// Note: Cloud Spanner interprets Node.js numbers as FLOAT64s, so they
// must be converted (back) to strings before being inserted as INT64s.
transaction.update('Albums', [
{
SingerId: '1',
AlbumId: '1',
MarketingBudget: firstBudget.toString(),
},
{
SingerId: '2',
AlbumId: '2',
MarketingBudget: secondBudget.toString(),
},
]);
})
.then(() => {
// Commits the transaction and send the changes to the database
return transaction.commit();
})
.then(() => {
console.log(
`Successfully executed read-write transaction to transfer ${transferAmount} from Album 2 to Album 1.`
);
})
.catch(err => {
console.error('ERROR:', err);
})
.then(() => {
transaction.end();
// Closes the database when finished
return database.close();
});
});
(async) runTransactionAsync(optionsopt, callback) → {Promise}
A transaction in Cloud Spanner is a set of reads and writes that execute atomically at a single logical point in time across columns, rows, and tables in a database.
Note that Cloud Spanner does not support nested transactions. If a new transaction is started inside of the run function, it will be an independent transaction.
The async function you provide will become the "run function". It will be executed with a Transaction object. The Transaction object will let you run queries and queue mutations until you are ready to Transaction#commit.
In the event that an aborted error occurs, we will re-run the runFn
in its
entirety. If you prefer to handle aborted errors for yourself please refer to
Database#getTransaction.
NOTE: In the event that you encounter an error while reading/writing, if you decide to forgo calling Transaction#commit or Transaction#rollback, then you need to call Transaction#end to release the underlying Session object. Failure to do could result in a Session leak.
For a more complete listing of functionality available to a Transaction, see the Transaction API documentation. For a general overview of transactions within Cloud Spanner, see Transactions from the official Cloud Spanner documentation.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
options |
RunTransactionOptions |
<optional> |
Transaction runner options. |
callback |
AsyncRunTransactionCallback |
A function to execute in the context of a transaction. |
Returns:
Type | Description |
---|---|
Promise |
- See:
Example
const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();
const instance = spanner.instance('my-instance');
const database = instance.database('my-database');
const data = await database.runTransactionAsync(async (transaction) => {
const [rows] = await transaction.run('SELECT * FROM MyTable');
const data = rows.map(row => row.thing);
await transaction.commit();
return data;
});
session(nameopt) → {Session}
Create a Session object.
It is unlikely you will need to interact with sessions directly. By default, sessions are created and utilized for maximum performance automatically.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
name |
string |
<optional> |
The name of the session. If not provided, it is assumed you are going to create it. |
Returns:
Type | Description |
---|---|
Session |
A Session object. |
table(name) → {Table}
Get a reference to a Table object.
Parameters:
Name | Type | Description |
---|---|---|
name |
string |
The name of the table. |
Returns:
Type | Description |
---|---|
Table |
A Table object. |
Throws:
-
If a name is not provided.
- Type
- Error
Example
const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();
const instance = spanner.instance('my-instance');
const database = instance.database('my-database');
const table = database.table('Singers');
updateSchema(statements, gaxOptionsopt, callbackopt) → {Promise.<LongRunningOperationResponse>}
Update the schema of the database by creating/altering/dropping tables, columns, indexes, etc.
This method immediately responds with an Operation object. Register event handlers for the "error" and "complete" events to see how the operation finishes. Follow along with the examples below.
Wrapper around v1.DatabaseAdminClient#updateDatabaseDdl.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
statements |
string | Array.<string> | object |
An array of database DDL
statements, or an
|
|
gaxOptions |
object |
<optional> |
Request configuration options, See CallOptions for more details. |
callback |
LongRunningOperationCallback |
<optional> |
Callback function. |
Returns:
Type | Description |
---|---|
Promise.<LongRunningOperationResponse> |
- See:
Examples
const {Spanner} = require('@google-cloud/spanner');
const spanner = new Spanner();
const instance = spanner.instance('my-instance');
const database = instance.database('my-database');
const statements = [
'CREATE TABLE Singers (' +
' SingerId INT64 NOT NULL,' +
' FirstName STRING(1024),' +
' LastName STRING(1024),' +
' SingerInfo BYTES(MAX),' +
') PRIMARY KEY(SingerId)'
];
database.updateSchema(statements, function(err, operation, apiResponse) {
if (err) {
// Error handling omitted.
}
operation
.on('error', function(err) {})
.on('complete', function() {
// Database schema updated successfully.
});
});
//-
// If the callback is omitted, we'll return a Promise.
//-
database.updateSchema(statements)
.then(function(data) {
const operation = data[0];
return operation.promise();
})
.then(function() {
// Database schema updated successfully.
});
Adding a column:
// 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';
// 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 request = ['ALTER TABLE Albums ADD COLUMN MarketingBudget INT64'];
// Creates a new index in the database
try {
const [operation] = await database.updateSchema(request);
console.log('Waiting for operation to complete...');
await operation.promise();
console.log('Added the MarketingBudget column.');
} catch (err) {
console.error('ERROR:', err);
} finally {
// Close the database when finished.
database.close();
}
Creating an index:
// 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';
// 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 request = ['CREATE INDEX AlbumsByAlbumTitle ON Albums(AlbumTitle)'];
// Creates a new index in the database
try {
const [operation] = await database.updateSchema(request);
console.log('Waiting for operation to complete...');
await operation.promise();
console.log('Added the AlbumsByAlbumTitle index.');
} catch (err) {
console.error('ERROR:', err);
} finally {
// Close the database when finished.
database.close();
}
Creating a storing index:
// "Storing" indexes store copies of the columns they index
// This speeds up queries, but takes more space compared to normal indexes
// See the link below for more information:
// https://cloud.google.com/spanner/docs/secondary-indexes#storing_clause
// 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';
// 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 request = [
'CREATE INDEX AlbumsByAlbumTitle2 ON Albums(AlbumTitle) STORING (MarketingBudget)',
];
// Creates a new index in the database
try {
const [operation] = await database.updateSchema(request);
console.log('Waiting for operation to complete...');
await operation.promise();
console.log('Added the AlbumsByAlbumTitle2 index.');
} catch (err) {
console.error('ERROR:', err);
} finally {
// Close the database when finished.
database.close();
}