v1. SpannerClient
Cloud Spanner API
The Cloud Spanner API can be used to manage sessions and execute transactions on data stored in Cloud Spanner databases.
Constructor
SpannerClient
new SpannerClient(options)
Construct an instance of SpannerClient.
Parameter |
|||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Optional object The configuration object. See the subsequent parameters for more details. Values in
|
Properties
port
The port for this API service.
scopes
The scopes needed to make gRPC calls for every method defined in this service.
servicePath
The DNS address for this API service.
Methods
beginTransaction
beginTransaction(request, options, callback) returns Promise
Begins a new transaction. This step can often be skipped: Read, ExecuteSql and Commit can begin a new transaction as a side-effect.
Parameter |
|||||||
---|---|---|---|---|---|---|---|
request |
Object The request object that will be sent. Values in
|
||||||
options |
Optional Object Optional parameters. You can override the default settings for this call, e.g, timeout, retries, paginations, etc. See gax.CallOptions for the details. |
||||||
callback |
Optional function(nullable Error, nullable Object) The function which will be called with the result of the API call. The second parameter to the callback is an object representing Transaction. |
- Returns
-
Promise
- The promise which resolves to an array. The first element of the array is an object representing Transaction. The promise has a method named "cancel" which cancels the ongoing API call.
Example
const spanner = require('@google-cloud/spanner');
var client = new spanner.v1.SpannerClient({
// optional auth parameters.
});
var formattedSession = client.sessionPath('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]');
var options = {};
var request = {
session: formattedSession,
options: options,
};
client.beginTransaction(request)
.then(responses => {
var response = responses[0];
// doThingsWith(response)
})
.catch(err => {
console.error(err);
});
commit
commit(request, options, callback) returns Promise
Commits a transaction. The request includes the mutations to be applied to rows in the database.
Commit
might return an ABORTED
error. This can occur at any time; commonly, the cause is conflicts with concurrent transactions. However, it can also happen for a variety of other reasons. If Commit
returns ABORTED
, the caller should re-attempt the transaction from the beginning, re-using the same session.
Parameter |
|||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
request |
Object The request object that will be sent. Values in
|
||||||||||
options |
Optional Object Optional parameters. You can override the default settings for this call, e.g, timeout, retries, paginations, etc. See gax.CallOptions for the details. |
||||||||||
callback |
Optional function(nullable Error, nullable Object) The function which will be called with the result of the API call. The second parameter to the callback is an object representing CommitResponse. |
- Returns
-
Promise
- The promise which resolves to an array. The first element of the array is an object representing CommitResponse. The promise has a method named "cancel" which cancels the ongoing API call.
Example
const spanner = require('@google-cloud/spanner');
var client = new spanner.v1.SpannerClient({
// optional auth parameters.
});
var formattedSession = client.sessionPath('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]');
var mutations = [];
var request = {
session: formattedSession,
mutations: mutations,
};
client.commit(request)
.then(responses => {
var response = responses[0];
// doThingsWith(response)
})
.catch(err => {
console.error(err);
});
createSession
createSession(request, options, callback) returns Promise
Creates a new session. A session can be used to perform transactions that read and/or modify data in a Cloud Spanner database. Sessions are meant to be reused for many consecutive transactions.
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.
Cloud Spanner limits the number of sessions that can exist at any given time; thus, it is a good idea to delete idle and/or unneeded sessions. Aside from explicit deletes, Cloud Spanner can delete sessions for which no operations are sent
for more than an hour. If a session is deleted, requests to it return NOT_FOUND
.
Idle sessions can be kept alive by sending a trivial SQL query periodically, e.g., "SELECT 1"
.
Parameter |
|||||||
---|---|---|---|---|---|---|---|
request |
Object The request object that will be sent. Values in
|
||||||
options |
Optional Object Optional parameters. You can override the default settings for this call, e.g, timeout, retries, paginations, etc. See gax.CallOptions for the details. |
||||||
callback |
Optional function(nullable Error, nullable Object) The function which will be called with the result of the API call. The second parameter to the callback is an object representing Session. |
- Returns
-
Promise
- The promise which resolves to an array. The first element of the array is an object representing Session. The promise has a method named "cancel" which cancels the ongoing API call.
Example
const spanner = require('@google-cloud/spanner');
var client = new spanner.v1.SpannerClient({
// optional auth parameters.
});
var formattedDatabase = client.databasePath('[PROJECT]', '[INSTANCE]', '[DATABASE]');
client.createSession({database: formattedDatabase})
.then(responses => {
var response = responses[0];
// doThingsWith(response)
})
.catch(err => {
console.error(err);
});
databasePath
databasePath(project, instance, database) returns String
Return a fully-qualified database resource name string.
Parameter |
|
---|---|
project |
String |
instance |
String |
database |
String |
- Returns
-
String
deleteSession
deleteSession(request, options, callback) returns Promise
Ends a session, releasing server resources associated with it.
Parameter |
|||||
---|---|---|---|---|---|
request |
Object The request object that will be sent. Values in
|
||||
options |
Optional Object Optional parameters. You can override the default settings for this call, e.g, timeout, retries, paginations, etc. See gax.CallOptions for the details. |
||||
callback |
Optional function(nullable Error) The function which will be called with the result of the API call. |
- Returns
-
Promise
- The promise which resolves when API call finishes. The promise has a method named "cancel" which cancels the ongoing API call.
Example
const spanner = require('@google-cloud/spanner');
var client = new spanner.v1.SpannerClient({
// optional auth parameters.
});
var formattedName = client.sessionPath('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]');
client.deleteSession({name: formattedName}).catch(err => {
console.error(err);
});
executeSql
executeSql(request, options, callback) returns Promise
Executes an SQL query, returning all rows in a single reply. This method cannot be used to return a result set larger than 10 MiB; if the query yields more data than that, the query fails with a FAILED_PRECONDITION
error.
Queries inside read-write transactions might return ABORTED
. If this occurs, the application should restart the transaction from the beginning. See Transaction for more details.
Larger result sets can be fetched in streaming fashion by calling ExecuteStreamingSql instead.
Parameter |
|||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
request |
Object The request object that will be sent. Values in
|
||||||||||||||||
options |
Optional Object Optional parameters. You can override the default settings for this call, e.g, timeout, retries, paginations, etc. See gax.CallOptions for the details. |
||||||||||||||||
callback |
Optional function(nullable Error, nullable Object) The function which will be called with the result of the API call. The second parameter to the callback is an object representing ResultSet. |
- Returns
-
Promise
- The promise which resolves to an array. The first element of the array is an object representing ResultSet. The promise has a method named "cancel" which cancels the ongoing API call.
Example
const spanner = require('@google-cloud/spanner');
var client = new spanner.v1.SpannerClient({
// optional auth parameters.
});
var formattedSession = client.sessionPath('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]');
var sql = '';
var request = {
session: formattedSession,
sql: sql,
};
client.executeSql(request)
.then(responses => {
var response = responses[0];
// doThingsWith(response)
})
.catch(err => {
console.error(err);
});
executeStreamingSql
executeStreamingSql(request, options) returns Stream
Like ExecuteSql, except returns the result set as a stream. Unlike ExecuteSql, there is no limit on the size of the returned result set. However, no individual row in the result set can exceed 100 MiB, and no column value can exceed 10 MiB.
Parameter |
|||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
request |
Object The request object that will be sent. Values in
|
||||||||||||||||
options |
Optional Object Optional parameters. You can override the default settings for this call, e.g, timeout, retries, paginations, etc. See gax.CallOptions for the details. |
- Returns
-
Stream
An object stream which emits PartialResultSet on 'data' event.
Example
const spanner = require('@google-cloud/spanner');
var client = new spanner.v1.SpannerClient({
// optional auth parameters.
});
var formattedSession = client.sessionPath('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]');
var sql = '';
var request = {
session: formattedSession,
sql: sql,
};
client.executeStreamingSql(request).on('data', response => {
// doThingsWith(response)
});
getProjectId
getProjectId(callback)
Return the project ID used by this class.
Parameter |
|
---|---|
callback |
function(Error, string) the callback to be called with the current project Id. |
getSession
getSession(request, options, callback) returns Promise
Gets a session. Returns NOT_FOUND
if the session does not exist. This is mainly useful for determining whether a session is still alive.
Parameter |
|||||
---|---|---|---|---|---|
request |
Object The request object that will be sent. Values in
|
||||
options |
Optional Object Optional parameters. You can override the default settings for this call, e.g, timeout, retries, paginations, etc. See gax.CallOptions for the details. |
||||
callback |
Optional function(nullable Error, nullable Object) The function which will be called with the result of the API call. The second parameter to the callback is an object representing Session. |
- Returns
-
Promise
- The promise which resolves to an array. The first element of the array is an object representing Session. The promise has a method named "cancel" which cancels the ongoing API call.
Example
const spanner = require('@google-cloud/spanner');
var client = new spanner.v1.SpannerClient({
// optional auth parameters.
});
var formattedName = client.sessionPath('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]');
client.getSession({name: formattedName})
.then(responses => {
var response = responses[0];
// doThingsWith(response)
})
.catch(err => {
console.error(err);
});
listSessions
listSessions(request, options, callback) returns Promise
Lists all sessions in a given database.
Parameter |
|||||||||
---|---|---|---|---|---|---|---|---|---|
request |
Object The request object that will be sent. Values in
|
||||||||
options |
Optional Object Optional parameters. You can override the default settings for this call, e.g, timeout, retries, paginations, etc. See gax.CallOptions for the details. |
||||||||
callback |
Optional function(nullable Error, nullable Array, nullable Object, nullable Object) The function which will be called with the result of the API call. The second parameter to the callback is Array of Session. When autoPaginate: false is specified through options, it contains the result in a single response. If the response indicates the next page exists, the third parameter is set to be used for the next request object. The fourth parameter keeps the raw response object of an object representing ListSessionsResponse. |
- Returns
-
Promise
-
The promise which resolves to an array. The first element of the array is Array of Session.
When autoPaginate: false is specified through options, the array has three elements. The first element is Array of Session in a single response. The second element is the next request object if the response indicates the next page exists, or null. The third element is an object representing ListSessionsResponse.
The promise has a method named "cancel" which cancels the ongoing API call.
-
Example
const spanner = require('@google-cloud/spanner');
var client = new spanner.v1.SpannerClient({
// optional auth parameters.
});
// Iterate over all elements.
var formattedDatabase = client.databasePath('[PROJECT]', '[INSTANCE]', '[DATABASE]');
client.listSessions({database: formattedDatabase})
.then(responses => {
var resources = responses[0];
for (let i = 0; i < resources.length; i += 1) {
// doThingsWith(resources[i])
}
})
.catch(err => {
console.error(err);
});
// Or obtain the paged response.
var formattedDatabase = client.databasePath('[PROJECT]', '[INSTANCE]', '[DATABASE]');
var options = {autoPaginate: false};
var callback = responses => {
// The actual resources in a response.
var resources = responses[0];
// The next request if the response shows that there are more responses.
var nextRequest = responses[1];
// The actual response object, if necessary.
// var rawResponse = responses[2];
for (let i = 0; i < resources.length; i += 1) {
// doThingsWith(resources[i]);
}
if (nextRequest) {
// Fetch the next page.
return client.listSessions(nextRequest, options).then(callback);
}
}
client.listSessions({database: formattedDatabase}, options)
.then(callback)
.catch(err => {
console.error(err);
});
listSessionsStream
listSessionsStream(request, options) returns Stream
Equivalent to listSessions, but returns a NodeJS Stream object.
This fetches the paged responses for listSessions continuously and invokes the callback registered for 'data' event for each element in the responses.
The returned object has 'end' method when no more elements are required.
autoPaginate option will be ignored.
Parameter |
|||||||||
---|---|---|---|---|---|---|---|---|---|
request |
Object The request object that will be sent. Values in
|
||||||||
options |
Optional Object Optional parameters. You can override the default settings for this call, e.g, timeout, retries, paginations, etc. See gax.CallOptions for the details. |
- See also
- https://nodejs.org/api/stream.html
- Returns
-
Stream
An object stream which emits an object representing Session on 'data' event.
Example
const spanner = require('@google-cloud/spanner');
var client = new spanner.v1.SpannerClient({
// optional auth parameters.
});
var formattedDatabase = client.databasePath('[PROJECT]', '[INSTANCE]', '[DATABASE]');
client.listSessionsStream({database: formattedDatabase})
.on('data', element => {
// doThingsWith(element)
}).on('error', err => {
console.log(err);
});
matchDatabaseFromDatabaseName
matchDatabaseFromDatabaseName(databaseName) returns String
Parse the databaseName from a database resource.
Parameter |
|
---|---|
databaseName |
String A fully-qualified path representing a database resources. |
- Returns
-
String
- A string representing the database.
matchDatabaseFromSessionName
matchDatabaseFromSessionName(sessionName) returns String
Parse the sessionName from a session resource.
Parameter |
|
---|---|
sessionName |
String A fully-qualified path representing a session resources. |
- Returns
-
String
- A string representing the database.
matchInstanceFromDatabaseName
matchInstanceFromDatabaseName(databaseName) returns String
Parse the databaseName from a database resource.
Parameter |
|
---|---|
databaseName |
String A fully-qualified path representing a database resources. |
- Returns
-
String
- A string representing the instance.
matchInstanceFromSessionName
matchInstanceFromSessionName(sessionName) returns String
Parse the sessionName from a session resource.
Parameter |
|
---|---|
sessionName |
String A fully-qualified path representing a session resources. |
- Returns
-
String
- A string representing the instance.
matchProjectFromDatabaseName
matchProjectFromDatabaseName(databaseName) returns String
Parse the databaseName from a database resource.
Parameter |
|
---|---|
databaseName |
String A fully-qualified path representing a database resources. |
- Returns
-
String
- A string representing the project.
matchProjectFromSessionName
matchProjectFromSessionName(sessionName) returns String
Parse the sessionName from a session resource.
Parameter |
|
---|---|
sessionName |
String A fully-qualified path representing a session resources. |
- Returns
-
String
- A string representing the project.
matchSessionFromSessionName
matchSessionFromSessionName(sessionName) returns String
Parse the sessionName from a session resource.
Parameter |
|
---|---|
sessionName |
String A fully-qualified path representing a session resources. |
- Returns
-
String
- A string representing the session.
read
read(request, options, callback) returns Promise
Reads rows from the database using key lookups and scans, as a simple key/value style alternative to ExecuteSql. This method cannot be used to return a result set larger than 10 MiB; if the read matches more data than that, the read fails
with a FAILED_PRECONDITION
error.
Reads inside read-write transactions might return ABORTED
. If this occurs, the application should restart the transaction from the beginning. See Transaction for more details.
Larger result sets can be yielded in streaming fashion by calling StreamingRead instead.
Parameter |
|||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
request |
Object The request object that will be sent. Values in
|
||||||||||||||||||
options |
Optional Object Optional parameters. You can override the default settings for this call, e.g, timeout, retries, paginations, etc. See gax.CallOptions for the details. |
||||||||||||||||||
callback |
Optional function(nullable Error, nullable Object) The function which will be called with the result of the API call. The second parameter to the callback is an object representing ResultSet. |
- Returns
-
Promise
- The promise which resolves to an array. The first element of the array is an object representing ResultSet. The promise has a method named "cancel" which cancels the ongoing API call.
Example
const spanner = require('@google-cloud/spanner');
var client = new spanner.v1.SpannerClient({
// optional auth parameters.
});
var formattedSession = client.sessionPath('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]');
var table = '';
var columns = [];
var keySet = {};
var request = {
session: formattedSession,
table: table,
columns: columns,
keySet: keySet,
};
client.read(request)
.then(responses => {
var response = responses[0];
// doThingsWith(response)
})
.catch(err => {
console.error(err);
});
rollback
rollback(request, options, callback) returns Promise
Rolls back a transaction, releasing any locks it holds. It is a good idea to call this for any transaction that includes one or more Read or ExecuteSql requests and ultimately decides not to commit.
Rollback
returns OK
if it successfully aborts the transaction, the transaction was already aborted, or the transaction is not found. Rollback
never returns ABORTED
.
Parameter |
|||||||
---|---|---|---|---|---|---|---|
request |
Object The request object that will be sent. Values in
|
||||||
options |
Optional Object Optional parameters. You can override the default settings for this call, e.g, timeout, retries, paginations, etc. See gax.CallOptions for the details. |
||||||
callback |
Optional function(nullable Error) The function which will be called with the result of the API call. |
- Returns
-
Promise
- The promise which resolves when API call finishes. The promise has a method named "cancel" which cancels the ongoing API call.
Example
const spanner = require('@google-cloud/spanner');
var client = new spanner.v1.SpannerClient({
// optional auth parameters.
});
var formattedSession = client.sessionPath('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]');
var transactionId = '';
var request = {
session: formattedSession,
transactionId: transactionId,
};
client.rollback(request).catch(err => {
console.error(err);
});
sessionPath
sessionPath(project, instance, database, session) returns String
Return a fully-qualified session resource name string.
Parameter |
|
---|---|
project |
String |
instance |
String |
database |
String |
session |
String |
- Returns
-
String
streamingRead
streamingRead(request, options) returns Stream
Like Read, except returns the result set as a stream. Unlike Read, there is no limit on the size of the returned result set. However, no individual row in the result set can exceed 100 MiB, and no column value can exceed 10 MiB.
Parameter |
|||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
request |
Object The request object that will be sent. Values in
|
||||||||||||||||||
options |
Optional Object Optional parameters. You can override the default settings for this call, e.g, timeout, retries, paginations, etc. See gax.CallOptions for the details. |
- Returns
-
Stream
An object stream which emits PartialResultSet on 'data' event.
Example
const spanner = require('@google-cloud/spanner');
var client = new spanner.v1.SpannerClient({
// optional auth parameters.
});
var formattedSession = client.sessionPath('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]');
var table = '';
var columns = [];
var keySet = {};
var request = {
session: formattedSession,
table: table,
columns: columns,
keySet: keySet,
};
client.streamingRead(request).on('data', response => {
// doThingsWith(response)
});