Create a Database object to interact with a Cloud Spanner database.
Inheritance
common_2 .GrpcServiceObject > DatabasePackage
@google-cloud/spannerExample
const
{
Spanner
}
=
require
(
' @google-cloud/spanner
'
);
const
spanner
=
new
Spanner
();
const
instance
=
spanner
.
instance
(
'my-instance'
);
const
database
=
instance
.
database
(
'my-database'
);
Constructors
(constructor)(instance, name, poolOptions, queryOptions)
constructor
(
instance
:
Instance
,
name
:
string
,
poolOptions
?:
SessionPoolConstructor
|
SessionPoolOptions
,
queryOptions
?:
spannerClient
.
spanner
.
v1
.
ExecuteSqlRequest
.
IQueryOptions
);
Constructs a new instance of the Database
class
instance
name
string
poolOptions
SessionPoolConstructor
| SessionPoolOptions
queryOptions
Properties
databaseRole
databaseRole
?:
string
|
null
;
formattedName_
formattedName_
:
string
;
pool_
pool_
:
SessionPoolInterface
;
queryOptions_
queryOptions_
?:
spannerClient
.
spanner
.
v1
.
ExecuteSqlRequest
.
IQueryOptions
;
request
request
:
DatabaseRequest
;
resourceHeader_
resourceHeader_
:
{
[
k
:
string
]
:
string
;
};
Methods
_runPartitionedUpdate(session, query, callback)
_runPartitionedUpdate
(
session
:
Session
,
query
:
string
|
ExecuteSqlRequest
,
callback
?:
RunUpdateCallback
)
:
void
|
Promise<number>
;
session
query
string | ExecuteSqlRequest
callback
RunUpdateCallback
void | Promise
<number>
batchCreateSessions(options)
batchCreateSessions
(
options
:
number
|
BatchCreateSessionsOptions
)
:
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 .
options
number | BatchCreateSessionsOptions
Desired session count or a configuration object.
Promise
< BatchCreateSessionsResponse
>
{Promise
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
);
batchCreateSessions(options, callback)
batchCreateSessions
(
options
:
number
|
BatchCreateSessionsOptions
,
callback
:
BatchCreateSessionsCallback
)
:
void
;
options
number | BatchCreateSessionsOptions
callback
BatchCreateSessionsCallback
void
batchTransaction(identifier, options)
batchTransaction
(
identifier
:
TransactionIdentifier
,
options
?:
TimestampBounds
)
:
BatchTransaction
;
Get a reference to a object.
identifier
TransactionIdentifier
The transaction identifier.
options
BatchTransaction
{BatchTransaction} A batch transaction object.
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(callback)
close
(
callback
:
SessionPoolCloseCallback
)
:
void
;
Close the database connection and destroy all sessions associated with it.
callback
SessionPoolCloseCallback
Callback function.
void
{Promise}
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
);
});
}
});
close()
close
()
:
Promise<DatabaseCloseResponse>
;
Promise
< DatabaseCloseResponse
>
createBatchTransaction(options)
createBatchTransaction
(
options
?:
TimestampBounds
)
:
Promise<CreateBatchTransactionResponse>
;
Create a transaction that can be used for batch querying.
options
Promise
< CreateBatchTransactionResponse
>
{Promise
createBatchTransaction(callback)
createBatchTransaction
(
callback
:
CreateBatchTransactionCallback
)
:
void
;
callback
CreateBatchTransactionCallback
void
createBatchTransaction(options, callback)
createBatchTransaction
(
options
:
TimestampBounds
,
callback
:
CreateBatchTransactionCallback
)
:
void
;
options
TimestampBounds
callback
CreateBatchTransactionCallback
void
createSession(options)
createSession
(
options
:
CreateSessionOptions
)
:
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 .
options
CreateSessionOptions
Configuration object.
Promise
< CreateSessionResponse
>
{Promise
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
];
});
createSession(callback)
createSession
(
callback
:
CreateSessionCallback
)
:
void
;
callback
CreateSessionCallback
void
createSession(options, callback)
createSession
(
options
:
CreateSessionOptions
,
callback
:
CreateSessionCallback
)
:
void
;
options
CreateSessionOptions
callback
CreateSessionCallback
void
createTable(schema, gaxOptions)
createTable
(
schema
:
Schema
,
gaxOptions
?:
CallOptions
)
:
Promise<CreateTableResponse>
;
Create a table.
Wrapper around .
schema
Schema
A DDL CREATE statement describing the table.
gaxOptions
Promise
< CreateTableResponse
>
{Promise
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.
});
createTable(schema, callback)
createTable
(
schema
:
Schema
,
callback
:
CreateTableCallback
)
:
void
;
schema
Schema
callback
CreateTableCallback
void
createTable(schema, gaxOptions, callback)
createTable
(
schema
:
Schema
,
gaxOptions
:
CallOptions
,
callback
:
CreateTableCallback
)
:
void
;
schema
Schema
gaxOptions
CallOptions
callback
CreateTableCallback
void
delete(gaxOptions)
delete
(
gaxOptions
?:
CallOptions
)
:
Promise<DatabaseDeleteResponse>
;
Delete the database.
Wrapper around .
gaxOptions
Promise
< DatabaseDeleteResponse
>
{Promise
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
];
});
delete(callback)
delete
(
callback
:
DatabaseDeleteCallback
)
:
void
;
callback
DatabaseDeleteCallback
void
delete(gaxOptions, callback)
delete
(
gaxOptions
:
CallOptions
,
callback
:
DatabaseDeleteCallback
)
:
void
;
gaxOptions
CallOptions
callback
DatabaseDeleteCallback
void
exists(gaxOptions)
exists
(
gaxOptions
?:
CallOptions
)
:
Promise
< [
boolean
]>;
Check if a database exists.
Database#exists
gaxOptions
Promise
<[boolean]>
{Promise
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
];
});
exists(callback)
exists
(
callback
:
ExistsCallback
)
:
void
;
void
exists(gaxOptions, callback)
exists
(
gaxOptions
:
CallOptions
,
callback
:
ExistsCallback
)
:
void
;
void
formatName_(instanceName, name)
static
formatName_
(
instanceName
:
string
,
name
:
string
)
:
string
;
Format the database name to include the instance name.
instanceName
string
The formatted instance name.
name
string
The table name.
string
{string}
Database
.
formatName_
(
'projects/grape-spaceship-123/instances/my-instance'
,
'my-database'
);
// 'projects/grape-spaceship-123/instances/my-instance/databases/my-database'
get(options)
get
(
options
?:
GetDatabaseConfig
)
:
Promise<DatabaseResponse>
;
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.
options
GetDatabaseConfig
Configuration object.
Promise
< DatabaseResponse
>
{Promise
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
];
});
get(callback)
get
(
callback
:
DatabaseCallback
)
:
void
;
callback
DatabaseCallback
void
get(options, callback)
get
(
options
:
GetDatabaseConfig
,
callback
:
DatabaseCallback
)
:
void
;
options
GetDatabaseConfig
callback
DatabaseCallback
void
getDatabaseRoles(gaxOptions)
getDatabaseRoles
(
gaxOptions
?:
CallOptions
)
:
Promise<GetDatabaseRolesResponse>
;
Gets a list of database roles
gaxOptions
Promise
< GetDatabaseRolesResponse
>
{Promise
const
{
Spanner
}
=
require
(
' @google-cloud/spanner
'
);
const
spanner
=
new
Spanner
();
const
instance
=
spanner
.
instance
(
'my-instance'
);
const
database
=
instance
.
database
(
'my-database'
);
database
.
getDatabaseRoles
(
function
(
err
,
roles
)
{
// `roles` is an array of `DatabaseRoles` objects.
});
//-
// To control how many API requests are made and page through the results
// manually, set `autoPaginate` to `false`.
//-
function
callback
(
err
,
roles
,
nextQuery
,
apiResponse
)
{
if
(
nextQuery
)
{
// More results exist.
database
.
getDatabaseRoles
(
nextQuery
,
callback
);
}
}
database
.
getInstances
({
gaxOptions
:
{
autoPaginate
:
false
}
},
callback
);
//-
// If the callback is omitted, we'll return a Promise.
//-
database
.
getInstances
().
then
(
function
(
data
)
{
const
roles
=
data
[
0
];
});
getDatabaseRoles(callback)
getDatabaseRoles
(
callback
:
GetDatabaseRolesCallback
)
:
void
;
callback
GetDatabaseRolesCallback
void
getDatabaseRoles(gaxOptions, callback)
getDatabaseRoles
(
gaxOptions
:
CallOptions
,
callback
:
GetDatabaseRolesCallback
)
:
void
;
gaxOptions
CallOptions
callback
GetDatabaseRolesCallback
void
getEnvironmentQueryOptions()
static
getEnvironmentQueryOptions
()
:
databaseAdmin
.
spanner
.
v1
.
ExecuteSqlRequest
.
IQueryOptions
;
getIamPolicy(options)
getIamPolicy
(
options
?:
GetIamPolicyOptions
)
:
Promise<GetIamPolicyResponse>
;
Retrieves the policy of the database.
A Policy is a collection of bindings. A binding binds one or more members, or principals, to a single role. Principals can be user accounts, service accounts, Google groups, and domains (such as G Suite). A role is a named list of permissions; each role can be an IAM predefined role or a user-created custom role.
options
GetIamPolicyOptions
requestedPolicyVersion and gax options(configuration options) See https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html for more details on gax options.
Promise
< GetIamPolicyResponse
>
{Promise<Policy | undefined>} When resolved, contains the current policy of the database.
const
{
Spanner
}
=
require
(
' @google-cloud/spanner
'
);
const
spanner
=
new
Spanner
();
const
instance
=
spanner
.
instance
(
'my-instance'
);
const
database
=
instance
.
database
(
'my-database'
);
const
policy
=
await
database
.
getIamPolicy
();
console
.
log
(
policy
.
bindings
,
policy
.
version
,
policy
.
etag
,
policy
.
auditConfigs
)
const
policyWithVersion
specified
=
await
database
.
getIamPolicy
({
requestedPolicyVersion
:
3
});
getIamPolicy(callback)
getIamPolicy
(
callback
:
GetIamPolicyCallback
)
:
void
;
callback
GetIamPolicyCallback
void
getIamPolicy(options, callback)
getIamPolicy
(
options
:
GetIamPolicyOptions
,
callback
:
GetIamPolicyCallback
)
:
void
;
options
GetIamPolicyOptions
callback
GetIamPolicyCallback
void
getMetadata(gaxOptions)
getMetadata
(
gaxOptions
?:
CallOptions
)
:
Promise<GetDatabaseMetadataResponse>
;
Get the database's metadata.
Wrapper around .
gaxOptions
Promise
< GetDatabaseMetadataResponse
>
{Promise
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
];
});
getMetadata(callback)
getMetadata
(
callback
:
GetDatabaseMetadataCallback
)
:
void
;
callback
GetDatabaseMetadataCallback
void
getMetadata(gaxOptions, callback)
getMetadata
(
gaxOptions
:
CallOptions
,
callback
:
GetDatabaseMetadataCallback
)
:
void
;
gaxOptions
CallOptions
callback
GetDatabaseMetadataCallback
void
getOperations(options)
getOperations
(
options
?:
GetDatabaseOperationsOptions
)
:
Promise<GetDatabaseOperationsResponse>
;
List pending and completed operations for the database.
options
GetDatabaseOperationsOptions
Contains query object for listing database operations and request configuration options, See CallOptions for more details.
Promise
< GetDatabaseOperationsResponse
>
{Promise
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
);
getOperations(callback)
getOperations
(
callback
:
GetDatabaseOperationsCallback
)
:
void
;
callback
GetDatabaseOperationsCallback
void
getOperations(options, callback)
getOperations
(
options
:
GetDatabaseOperationsOptions
,
callback
:
GetDatabaseOperationsCallback
)
:
void
;
options
GetDatabaseOperationsOptions
callback
GetDatabaseOperationsCallback
void
getRestoreInfo(options)
getRestoreInfo
(
options
?:
CallOptions
)
:
Promise<IRestoreInfoTranslatedEnum
|
undefined
> ;
Retrieves the restore information of the database.
options
CallOptions
Promise
< IRestoreInfoTranslatedEnum
| undefined>
{Promise<IRestoreInfoTranslatedEnum | undefined>} When resolved, contains the restore information for the database if it was restored from a backup.
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
}
`
);
getRestoreInfo(callback)
getRestoreInfo
(
callback
:
GetRestoreInfoCallback
)
:
void
;
callback
GetRestoreInfoCallback
void
getRestoreInfo(options, callback)
getRestoreInfo
(
options
:
CallOptions
,
callback
:
GetRestoreInfoCallback
)
:
void
;
options
CallOptions
callback
GetRestoreInfoCallback
void
getSchema(options)
getSchema
(
options
?:
CallOptions
)
:
Promise<GetSchemaResponse>
;
Get this database's schema as a list of formatted DDL statements.
Wrapper around .
options
CallOptions
Promise
< GetSchemaResponse
>
{Promise
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
];
});
getSchema(callback)
getSchema
(
callback
:
GetSchemaCallback
)
:
void
;
callback
GetSchemaCallback
void
getSchema(options, callback)
getSchema
(
options
:
CallOptions
,
callback
:
GetSchemaCallback
)
:
void
;
options
CallOptions
callback
GetSchemaCallback
void
getSessions(options)
getSessions
(
options
?:
GetSessionsOptions
)
:
Promise<GetSessionsResponse>
;
Gets a list of sessions.
Wrapper around
options
GetSessionsOptions
Options object for listing sessions.
Promise
< GetSessionsResponse
>
{Promise
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
];
});
getSessions(callback)
getSessions
(
callback
:
GetSessionsCallback
)
:
void
;
callback
GetSessionsCallback
void
getSessions(options, callback)
getSessions
(
options
:
GetSessionsOptions
,
callback
:
GetSessionsCallback
)
:
void
;
options
GetSessionsOptions
callback
GetSessionsCallback
void
getSessionsStream(options)
getSessionsStream
(
options
?:
GetSessionsOptions
)
:
NodeJS
.
ReadableStream
;
Get a list of sessions as a readable object stream.
Wrapper around
options
GetSessionsOptions
Options object for listing sessions.
NodeJS.ReadableStream
{ReadableStream} A readable stream that emits Session instances.
const
{
Spanner
}
=
require
(
' @google-cloud/spanner
'
);
const
spanner
=
new
Spanner
();
const
instance
=
spanner
.
instance
(
'my-instance'
);
const
database
=
instance
.
database
(
'my-database'
);
database
.
getSessionsStream
()
.
on
(
'error'
,
console
.
error
)
.
on
(
'data'
,
function
(
database
)
{
// `sessions` is a `Session` object.
})
.
on
(
'end'
,
function
()
{
// All sessions retrieved.
});
//-
// If you anticipate many results, you can end a stream early to prevent
// unnecessary processing and API requests.
//-
database
.
getSessionsStream
()
.
on
(
'data'
,
function
(
session
)
{
this
.
end
();
});
getSnapshot(options)
getSnapshot
(
options
?:
TimestampBounds
)
:
Promise
< [
Snapshot
]>;
Get a read only Snapshot transaction.
Wrapper around .
**NOTE:** When finished with the Snapshot, 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 as those parameters can only be set for single-use transactions. https://cloud.google.com/spanner/docs/reference/rest/v1/TransactionOptions#bounded-staleness
options
TimestampBounds
Timestamp bounds.
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
();
}
});
getSnapshot(callback)
getSnapshot
(
callback
:
GetSnapshotCallback
)
:
void
;
callback
GetSnapshotCallback
void
getSnapshot(options, callback)
getSnapshot
(
options
:
TimestampBounds
,
callback
:
GetSnapshotCallback
)
:
void
;
options
TimestampBounds
callback
GetSnapshotCallback
void
getState(options)
getState
(
options
?:
CallOptions
)
:
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.
options
CallOptions
Promise
< EnumKey
<typeof databaseAdmin.spanner.admin.database.v1.Database.State
> | undefined>
{Promise<EnumKey<typeof, google.spanner.admin.database.v1.Database.State> | undefined>} When resolved, contains the current state of the database if the state is defined.
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'
);
getState(callback)
getState
(
callback
:
GetStateCallback
)
:
void
;
callback
GetStateCallback
void
getState(options, callback)
getState
(
options
:
CallOptions
,
callback
:
GetStateCallback
)
:
void
;
options
CallOptions
callback
GetStateCallback
void
getTransaction()
getTransaction
()
:
Promise
< [
Transaction
]>;
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 or , then you need to call to release the underlying Session object. **Failure to do could result in a Session leak.**
Wrapper around .
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
];
});
getTransaction(callback)
getTransaction
(
callback
:
GetTransactionCallback
)
:
void
;
callback
GetTransactionCallback
void
makePooledRequest_(config)
makePooledRequest_
(
config
:
RequestConfig
)
:
Promise<Session>
;
Make an API request, first assuring an active session is used.
makePooledRequest_(config, callback)
makePooledRequest_
(
config
:
RequestConfig
,
callback
:
PoolRequestCallback
)
:
void
;
void
makePooledStreamingRequest_(config)
makePooledStreamingRequest_
(
config
:
RequestConfig
)
:
Readable
;
Make an API request as a stream, first assuring an active session is used.
Readable
{Stream}
restore(backupPath)
restore
(
backupPath
:
string
)
:
Promise<RestoreDatabaseResponse>
;
Restore a backup into this database.
When this call completes, the restore will have commenced but will not necessarily have completed.
backupPath
string
The path of the backup to restore.
Promise
< RestoreDatabaseResponse
>
{Promise
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
();
restore(backupPath, options)
restore
(
backupPath
:
string
,
options
?:
RestoreOptions
|
CallOptions
)
:
Promise<RestoreDatabaseResponse>
;
backupPath
string
options
RestoreOptions
| CallOptions
Promise
< RestoreDatabaseResponse
>
restore(backupPath, callback)
restore
(
backupPath
:
string
,
callback
:
RestoreDatabaseCallback
)
:
void
;
backupPath
string
callback
RestoreDatabaseCallback
void
restore(backupPath, options, callback)
restore
(
backupPath
:
string
,
options
:
RestoreOptions
|
CallOptions
,
callback
:
RestoreDatabaseCallback
)
:
void
;
backupPath
string
options
RestoreOptions
| CallOptions
callback
RestoreDatabaseCallback
void
run(query)
run
(
query
:
string
|
ExecuteSqlRequest
)
:
Promise<RunResponse>
;
Execute a SQL statement on this database.
Wrapper around .
query
string | ExecuteSqlRequest
A SQL query or object.
Promise
< RunResponse
>
{Promise
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
();
}
run(query, options)
run
(
query
:
string
|
ExecuteSqlRequest
,
options
?:
TimestampBounds
)
:
Promise<RunResponse>
;
query
string | ExecuteSqlRequest
options
TimestampBounds
Promise
< RunResponse
>
run(query, callback)
run
(
query
:
string
|
ExecuteSqlRequest
,
callback
:
RunCallback
)
:
void
;
query
string | ExecuteSqlRequest
callback
RunCallback
void
run(query, options, callback)
run
(
query
:
string
|
ExecuteSqlRequest
,
options
:
TimestampBounds
,
callback
:
RunCallback
)
:
void
;
query
string | ExecuteSqlRequest
options
TimestampBounds
callback
RunCallback
void
runPartitionedUpdate(query)
runPartitionedUpdate
(
query
:
string
|
ExecuteSqlRequest
)
:
Promise
< [
number
]>;
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.
query
string | ExecuteSqlRequest
A DML statement or object.
Promise
<[number]>
{Promise
runPartitionedUpdate(query, callback)
runPartitionedUpdate
(
query
:
string
|
ExecuteSqlRequest
,
callback
?:
RunUpdateCallback
)
:
void
;
query
string | ExecuteSqlRequest
callback
RunUpdateCallback
void
runStream(query, options)
runStream
(
query
:
string
|
ExecuteSqlRequest
,
options
?:
TimestampBounds
)
:
PartialResultStream
;
Create a readable object stream to receive resulting rows from a SQL statement.
Wrapper around .
query
string | ExecuteSqlRequest
A SQL query or object.
options
TimestampBounds
Snapshot timestamp bounds.
PartialResultStream
{PartialResultStream} A readable stream that emits rows.
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(runFn)
runTransaction
(
runFn
:
RunTransactionCallback
)
:
void
;
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 .
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 .
**NOTE:** In the event that you encounter an error while reading/writing, if you decide to forgo calling or , then you need to call 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]( https://cloud.google.com/spanner/docs/transactions ) from the official Cloud Spanner documentation.
If you would like to run a transaction and receive a promise or use async/await, use .
runFn
RunTransactionCallback
void
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
();
});
});
runTransaction(options, runFn)
runTransaction
(
options
:
RunTransactionOptions
,
runFn
:
RunTransactionCallback
)
:
void
;
options
RunTransactionOptions
runFn
RunTransactionCallback
void
runTransactionAsync(runFn)
runTransactionAsync<T
=
{}>(
runFn
:
AsyncRunTransactionCallback<T>
)
:
Promise<T>
;
runFn
AsyncRunTransactionCallback
<T>
Promise
<T>
T
runTransactionAsync(options, runFn)
runTransactionAsync<T
=
{}>(
options
:
RunTransactionOptions
,
runFn
:
AsyncRunTransactionCallback<T>
)
:
Promise<T>
;
options
RunTransactionOptions
runFn
AsyncRunTransactionCallback
<T>
Promise
<T>
T
session(name)
session
(
name
?:
string
)
:
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.
name
string
The name of the session. If not provided, it is assumed you are going to create it.
var
session
=
database
.
session
(
'session-name'
);
setIamPolicy(policy)
setIamPolicy
(
policy
:
SetIamPolicyRequest
)
:
Promise<SetIamPolicyResponse>
;
Sets the policy for the database.
A Policy is a collection of bindings. A binding binds one or more members, or principals, to a single role. Principals can be user accounts, service accounts, Google groups, and domains (such as G Suite). A role is a named list of permissions; each role can be an IAM predefined role or a user-created custom role.
policy
SetIamPolicyRequest
requestedPolicyVersion and gax options(configuration options) See https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html for more details on gax options.
Promise
< SetIamPolicyResponse
>
{Promise<Policy | undefined>} When resolved, contains the current policy of the database.
const
{
Spanner
}
=
require
(
' @google-cloud/spanner
'
);
const
spanner
=
new
Spanner
();
const
instance
=
spanner
.
instance
(
'my-instance'
);
const
database
=
instance
.
database
(
'my-database'
);
const
binding
=
{
role
:
'roles/spanner.fineGrainedAccessUser'
,
members
:
[
'user:asthamohta@google.com'
],
condition
:
{
title
:
'new condition'
,
expression
:
'resource.name.endsWith("/databaseRoles/parent")'
,
},
};
const
policy
=
{
bindings
:
[
newBinding
],
version
:
3
,
};
const
policy
=
await
database
.
setIamPolicy
({
policy
:
policy
});
setIamPolicy(policy, options)
setIamPolicy
(
policy
:
SetIamPolicyRequest
,
options
?:
CallOptions
)
:
Promise<SetIamPolicyResponse>
;
policy
SetIamPolicyRequest
options
CallOptions
Promise
< SetIamPolicyResponse
>
setIamPolicy(policy, callback)
setIamPolicy
(
policy
:
SetIamPolicyRequest
,
callback
:
SetIamPolicyCallback
)
:
void
;
policy
SetIamPolicyRequest
callback
SetIamPolicyCallback
void
setIamPolicy(policy, options, callback)
setIamPolicy
(
policy
:
SetIamPolicyRequest
,
options
:
CallOptions
,
callback
:
SetIamPolicyCallback
)
:
void
;
policy
SetIamPolicyRequest
options
CallOptions
callback
SetIamPolicyCallback
void
setMetadata(metadata, gaxOptions)
setMetadata
(
metadata
:
IDatabase
,
gaxOptions
?:
CallOptions
)
:
Promise<SetDatabaseMetadataResponse>
;
Update the metadata for this database. Note that this method follows PATCH semantics, so previously-configured settings will persist.
Wrapper around .
metadata
gaxOptions
Promise
< SetDatabaseMetadataResponse
>
{Promise
const
{
Spanner
}
=
require
(
' @google-cloud/spanner
'
);
const
spanner
=
new
Spanner
();
const
instance
=
spanner
.
instance
(
'my-instance'
);
const
database
=
instance
.
database
(
'my-database'
);
const
metadata
=
{
enableDropProtection
:
true
};
database
.
setMetadata
(
metadata
,
function
(
err
,
operation
,
apiResponse
)
{
if
(
err
)
{
// Error handling omitted.
}
operation
.
on
(
'error'
,
function
(
err
)
{})
.
on
(
'complete'
,
function
()
{
// Metadata updated successfully.
});
});
//-
// If the callback is omitted, we'll return a Promise.
//-
database
.
setMetadata
(
metadata
).
then
(
function
(
data
)
{
const
operation
=
data
[
0
];
const
apiResponse
=
data
[
1
];
});
setMetadata(metadata, callback)
setMetadata
(
metadata
:
IDatabase
,
callback
:
SetDatabaseMetadataCallback
)
:
void
;
void
setMetadata(metadata, gaxOptions, callback)
setMetadata
(
metadata
:
IDatabase
,
gaxOptions
:
CallOptions
,
callback
:
SetDatabaseMetadataCallback
)
:
void
;
metadata
gaxOptions
CallOptions
callback
SetDatabaseMetadataCallback
void
table(name)
table
(
name
:
string
)
:
Table
;
name
string
updateSchema(statements, gaxOptions)
updateSchema
(
statements
:
Schema
,
gaxOptions
?:
CallOptions
)
:
Promise<UpdateSchemaResponse>
;
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 .
statements
Schema
An array of database DDL statements, or an [ UpdateDatabaseDdlRequest
object](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.UpdateDatabaseDdlRequest).
gaxOptions
Promise
< UpdateSchemaResponse
>
{Promise
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
();
}
updateSchema(statements, callback)
updateSchema
(
statements
:
Schema
,
callback
:
UpdateSchemaCallback
)
:
void
;
statements
Schema
callback
UpdateSchemaCallback
void
updateSchema(statements, gaxOptions, callback)
updateSchema
(
statements
:
Schema
,
gaxOptions
:
CallOptions
,
callback
:
UpdateSchemaCallback
)
:
void
;
statements
Schema
gaxOptions
CallOptions
callback
UpdateSchemaCallback
void