DatabaseAdminClient

v1~ DatabaseAdminClient

Cloud Spanner Database Admin API

The Cloud Spanner Database Admin API can be used to create, drop, and list databases. It also enables updating the schema of pre-existing databases.

Constructor

new DatabaseAdminClient(optionsopt)

Construct an instance of DatabaseAdminClient.

Parameters:
Name Type Attributes Description
options object <optional>

The configuration object. See the subsequent parameters for more details.

Properties
Name Type Attributes Description
credentials object <optional>

Credentials object.

Properties
Name Type Attributes Description
client_email string <optional>
private_key string <optional>
email string <optional>

Account email address. Required when using a .pem or .p12 keyFilename.

keyFilename string <optional>

Full path to the a .json, .pem, or .p12 key downloaded from the Google Developers Console. If you provide a path to a JSON file, the projectId option below is not necessary. NOTE: .pem and .p12 require you to specify options.email as well.

port number <optional>

The port on which to connect to the remote host.

projectId string <optional>

The project ID from the Google Developer's Console, e.g. 'grape-spaceship-123'. We will also check the environment variable GCLOUD_PROJECT for your project ID. If your app is running in an environment which supports Application Default Credentials, your project ID will be detected automatically.

promise function <optional>

Custom promise module to use instead of native Promises.

apiEndpoint string <optional>

The domain name of the API remote host.

Source:

Members

(static) apiEndpoint

The DNS address for this API service - same as servicePath(), exists for compatibility reasons.

Source:

(static) port

The port for this API service.

Source:

(static) scopes

The scopes needed to make gRPC calls for every method defined in this service.

Source:

(static) servicePath

The DNS address for this API service.

Source:

Methods

createDatabase(request, optionsopt, callbackopt) → {Promise}

Creates a new Cloud Spanner database and starts to prepare it for serving. The returned long-running operation will have a name of the format <database_name>/operations/<operation_id> and can be used to track preparation of the database. The metadata field type is CreateDatabaseMetadata. The response field type is Database, if successful.

Parameters:
Name Type Attributes Description
request Object

The request object that will be sent.

Properties
Name Type Attributes Description
parent string

Required. The name of the instance that will serve the new database. Values are of the form projects/<project>/instances/<instance>.

createStatement string

Required. A CREATE DATABASE statement, which specifies the ID of the new database. The database ID must conform to the regular expression [a-z][a-z0-9_\-]*[a-z0-9] and be between 2 and 30 characters in length. If the database ID is a reserved word or if it contains a hyphen, the database ID must be enclosed in backticks (`).

extraStatements Array.<string> <optional>

An optional list of DDL statements to run inside the newly created database. Statements can create tables, indexes, etc. These statements execute atomically with the creation of the database: if there is an error in any statement, the database is not created.

options Object <optional>

Optional parameters. You can override the default settings for this call, e.g, timeout, retries, paginations, etc. See gax.CallOptions for the details.

callback function <optional>

The function which will be called with the result of the API call.

The second parameter to the callback is a gax.Operation object.

Source:
Example
const spanner = require('@google-cloud/spanner');

const client = new spanner.v1.DatabaseAdminClient({
  // optional auth parameters.
});

const formattedParent = client.instancePath('[PROJECT]', '[INSTANCE]');
const createStatement = '';
const request = {
  parent: formattedParent,
  createStatement: createStatement,
};

// Handle the operation using the promise pattern.
client.createDatabase(request)
  .then(responses => {
    const [operation, initialApiResponse] = responses;

    // Operation#promise starts polling for the completion of the LRO.
    return operation.promise();
  })
  .then(responses => {
    const result = responses[0];
    const metadata = responses[1];
    const finalApiResponse = responses[2];
  })
  .catch(err => {
    console.error(err);
  });

const formattedParent = client.instancePath('[PROJECT]', '[INSTANCE]');
const createStatement = '';
const request = {
  parent: formattedParent,
  createStatement: createStatement,
};

// Handle the operation using the event emitter pattern.
client.createDatabase(request)
  .then(responses => {
    const [operation, initialApiResponse] = responses;

    // Adding a listener for the "complete" event starts polling for the
    // completion of the operation.
    operation.on('complete', (result, metadata, finalApiResponse) => {
      // doSomethingWith(result);
    });

    // Adding a listener for the "progress" event causes the callback to be
    // called on any change in metadata when the operation is polled.
    operation.on('progress', (metadata, apiResponse) => {
      // doSomethingWith(metadata)
    });

    // Adding a listener for the "error" event handles any errors found during polling.
    operation.on('error', err => {
      // throw(err);
    });
  })
  .catch(err => {
    console.error(err);
  });

const formattedParent = client.instancePath('[PROJECT]', '[INSTANCE]');
const createStatement = '';
const request = {
  parent: formattedParent,
  createStatement: createStatement,
};

// Handle the operation using the await pattern.
const [operation] = await client.createDatabase(request);

const [response] = await operation.promise();

databasePath(project, instance, database) → {String}

Return a fully-qualified database resource name string.

Parameters:
Name Type Description
project String
instance String
database String
Source:

dropDatabase(request, optionsopt, callbackopt) → {Promise}

Drops (aka deletes) a Cloud Spanner database.

Parameters:
Name Type Attributes Description
request Object

The request object that will be sent.

Properties
Name Type Description
database string

Required. The database to be dropped.

options Object <optional>

Optional parameters. You can override the default settings for this call, e.g, timeout, retries, paginations, etc. See gax.CallOptions for the details.

callback function <optional>

The function which will be called with the result of the API call.

Source:
Example
const spanner = require('@google-cloud/spanner');

const client = new spanner.v1.DatabaseAdminClient({
  // optional auth parameters.
});

const formattedDatabase = client.databasePath('[PROJECT]', '[INSTANCE]', '[DATABASE]');
client.dropDatabase({database: formattedDatabase}).catch(err => {
  console.error(err);
});

getDatabase(request, optionsopt, callbackopt) → {Promise}

Gets the state of a Cloud Spanner database.

Parameters:
Name Type Attributes Description
request Object

The request object that will be sent.

Properties
Name Type Description
name string

Required. The name of the requested database. Values are of the form projects/<project>/instances/<instance>/databases/<database>.

options Object <optional>

Optional parameters. You can override the default settings for this call, e.g, timeout, retries, paginations, etc. See gax.CallOptions for the details.

callback function <optional>

The function which will be called with the result of the API call.

The second parameter to the callback is an object representing Database.

Source:
Example
const spanner = require('@google-cloud/spanner');

const client = new spanner.v1.DatabaseAdminClient({
  // optional auth parameters.
});

const formattedName = client.databasePath('[PROJECT]', '[INSTANCE]', '[DATABASE]');
client.getDatabase({name: formattedName})
  .then(responses => {
    const response = responses[0];
    // doThingsWith(response)
  })
  .catch(err => {
    console.error(err);
  });

getDatabaseDdl(request, optionsopt, callbackopt) → {Promise}

Returns the schema of a Cloud Spanner database as a list of formatted DDL statements. This method does not show pending schema updates, those may be queried using the Operations API.

Parameters:
Name Type Attributes Description
request Object

The request object that will be sent.

Properties
Name Type Description
database string

Required. The database whose schema we wish to get.

options Object <optional>

Optional parameters. You can override the default settings for this call, e.g, timeout, retries, paginations, etc. See gax.CallOptions for the details.

callback function <optional>

The function which will be called with the result of the API call.

The second parameter to the callback is an object representing GetDatabaseDdlResponse.

Source:
Example
const spanner = require('@google-cloud/spanner');

const client = new spanner.v1.DatabaseAdminClient({
  // optional auth parameters.
});

const formattedDatabase = client.databasePath('[PROJECT]', '[INSTANCE]', '[DATABASE]');
client.getDatabaseDdl({database: formattedDatabase})
  .then(responses => {
    const response = responses[0];
    // doThingsWith(response)
  })
  .catch(err => {
    console.error(err);
  });

getIamPolicy(request, optionsopt, callbackopt) → {Promise}

Gets the access control policy for a database resource. Returns an empty policy if a database exists but does not have a policy set.

Authorization requires spanner.databases.getIamPolicy permission on resource.

Parameters:
Name Type Attributes Description
request Object

The request object that will be sent.

Properties
Name Type Attributes Description
resource string

REQUIRED: The resource for which the policy is being requested. See the operation documentation for the appropriate value for this field.

options Object <optional>

OPTIONAL: A GetPolicyOptions object for specifying options to GetIamPolicy. This field is only used by Cloud IAM.

This object should have the same structure as GetPolicyOptions

options Object <optional>

Optional parameters. You can override the default settings for this call, e.g, timeout, retries, paginations, etc. See gax.CallOptions for the details.

callback function <optional>

The function which will be called with the result of the API call.

The second parameter to the callback is an object representing Policy.

Source:
Example
const spanner = require('@google-cloud/spanner');

const client = new spanner.v1.DatabaseAdminClient({
  // optional auth parameters.
});

const resource = '';
client.getIamPolicy({resource: resource})
  .then(responses => {
    const response = responses[0];
    // doThingsWith(response)
  })
  .catch(err => {
    console.error(err);
  });

getProjectId(callback)

Return the project ID used by this class.

Parameters:
Name Type Description
callback function

the callback to be called with the current project Id.

Source:

instancePath(project, instance) → {String}

Return a fully-qualified instance resource name string.

Parameters:
Name Type Description
project String
instance String
Source:

listDatabases(request, optionsopt, callbackopt) → {Promise}

Lists Cloud Spanner databases.

Parameters:
Name Type Attributes Description
request Object

The request object that will be sent.

Properties
Name Type Attributes Description
parent string

Required. The instance whose databases should be listed. Values are of the form projects/<project>/instances/<instance>.

pageSize number <optional>

The maximum number of resources contained in the underlying API response. If page streaming is performed per-resource, this parameter does not affect the return value. If page streaming is performed per-page, this determines the maximum number of resources in a page.

options Object <optional>

Optional parameters. You can override the default settings for this call, e.g, timeout, retries, paginations, etc. See gax.CallOptions for the details.

callback function <optional>

The function which will be called with the result of the API call.

The second parameter to the callback is Array of Database.

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

Source:
Example
const spanner = require('@google-cloud/spanner');

const client = new spanner.v1.DatabaseAdminClient({
  // optional auth parameters.
});

// Iterate over all elements.
const formattedParent = client.instancePath('[PROJECT]', '[INSTANCE]');

client.listDatabases({parent: formattedParent})
  .then(responses => {
    const resources = responses[0];
    for (const resource of resources) {
      // doThingsWith(resource)
    }
  })
  .catch(err => {
    console.error(err);
  });

// Or obtain the paged response.
const formattedParent = client.instancePath('[PROJECT]', '[INSTANCE]');


const options = {autoPaginate: false};
const callback = responses => {
  // The actual resources in a response.
  const resources = responses[0];
  // The next request if the response shows that there are more responses.
  const nextRequest = responses[1];
  // The actual response object, if necessary.
  // const rawResponse = responses[2];
  for (const resource of resources) {
    // doThingsWith(resource);
  }
  if (nextRequest) {
    // Fetch the next page.
    return client.listDatabases(nextRequest, options).then(callback);
  }
}
client.listDatabases({parent: formattedParent}, options)
  .then(callback)
  .catch(err => {
    console.error(err);
  });

listDatabasesStream(request, optionsopt) → {Stream}

Equivalent to listDatabases, but returns a NodeJS Stream object.

This fetches the paged responses for listDatabases 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.

Parameters:
Name Type Attributes Description
request Object

The request object that will be sent.

Properties
Name Type Attributes Description
parent string

Required. The instance whose databases should be listed. Values are of the form projects/<project>/instances/<instance>.

pageSize number <optional>

The maximum number of resources contained in the underlying API response. If page streaming is performed per-resource, this parameter does not affect the return value. If page streaming is performed per-page, this determines the maximum number of resources in a page.

options Object <optional>

Optional parameters. You can override the default settings for this call, e.g, timeout, retries, paginations, etc. See gax.CallOptions for the details.

Source:
See:
Example
const spanner = require('@google-cloud/spanner');

const client = new spanner.v1.DatabaseAdminClient({
  // optional auth parameters.
});

const formattedParent = client.instancePath('[PROJECT]', '[INSTANCE]');
client.listDatabasesStream({parent: formattedParent})
  .on('data', element => {
    // doThingsWith(element)
  }).on('error', err => {
    console.log(err);
  });

matchDatabaseFromDatabaseName(databaseName) → {String}

Parse the databaseName from a database resource.

Parameters:
Name Type Description
databaseName String

A fully-qualified path representing a database resources.

Source:

matchInstanceFromDatabaseName(databaseName) → {String}

Parse the databaseName from a database resource.

Parameters:
Name Type Description
databaseName String

A fully-qualified path representing a database resources.

Source:

matchInstanceFromInstanceName(instanceName) → {String}

Parse the instanceName from a instance resource.

Parameters:
Name Type Description
instanceName String

A fully-qualified path representing a instance resources.

Source:

matchProjectFromDatabaseName(databaseName) → {String}

Parse the databaseName from a database resource.

Parameters:
Name Type Description
databaseName String

A fully-qualified path representing a database resources.

Source:

matchProjectFromInstanceName(instanceName) → {String}

Parse the instanceName from a instance resource.

Parameters:
Name Type Description
instanceName String

A fully-qualified path representing a instance resources.

Source:

setIamPolicy(request, optionsopt, callbackopt) → {Promise}

Sets the access control policy on a database resource. Replaces any existing policy.

Authorization requires spanner.databases.setIamPolicy permission on resource.

Parameters:
Name Type Attributes Description
request Object

The request object that will be sent.

Properties
Name Type Description
resource string

REQUIRED: The resource for which the policy is being specified. See the operation documentation for the appropriate value for this field.

policy Object

REQUIRED: The complete policy to be applied to the resource. The size of the policy is limited to a few 10s of KB. An empty policy is a valid policy but certain Cloud Platform services (such as Projects) might reject them.

This object should have the same structure as Policy

options Object <optional>

Optional parameters. You can override the default settings for this call, e.g, timeout, retries, paginations, etc. See gax.CallOptions for the details.

callback function <optional>

The function which will be called with the result of the API call.

The second parameter to the callback is an object representing Policy.

Source:
Example
const spanner = require('@google-cloud/spanner');

const client = new spanner.v1.DatabaseAdminClient({
  // optional auth parameters.
});

const resource = '';
const policy = {};
const request = {
  resource: resource,
  policy: policy,
};
client.setIamPolicy(request)
  .then(responses => {
    const response = responses[0];
    // doThingsWith(response)
  })
  .catch(err => {
    console.error(err);
  });

testIamPermissions(request, optionsopt, callbackopt) → {Promise}

Returns permissions that the caller has on the specified database resource.

Attempting this RPC on a non-existent Cloud Spanner database will result in a NOT_FOUND error if the user has spanner.databases.list permission on the containing Cloud Spanner instance. Otherwise returns an empty set of permissions.

Parameters:
Name Type Attributes Description
request Object

The request object that will be sent.

Properties
Name Type Description
resource string

REQUIRED: The resource for which the policy detail is being requested. See the operation documentation for the appropriate value for this field.

permissions Array.<string>

The set of permissions to check for the resource. Permissions with wildcards (such as '' or 'storage.') are not allowed. For more information see IAM Overview.

options Object <optional>

Optional parameters. You can override the default settings for this call, e.g, timeout, retries, paginations, etc. See gax.CallOptions for the details.

callback function <optional>

The function which will be called with the result of the API call.

The second parameter to the callback is an object representing TestIamPermissionsResponse.

Source:
Example
const spanner = require('@google-cloud/spanner');

const client = new spanner.v1.DatabaseAdminClient({
  // optional auth parameters.
});

const resource = '';
const permissions = [];
const request = {
  resource: resource,
  permissions: permissions,
};
client.testIamPermissions(request)
  .then(responses => {
    const response = responses[0];
    // doThingsWith(response)
  })
  .catch(err => {
    console.error(err);
  });

updateDatabaseDdl(request, optionsopt, callbackopt) → {Promise}

Updates the schema of a Cloud Spanner database by creating/altering/dropping tables, columns, indexes, etc. The returned long-running operation will have a name of the format <database_name>/operations/<operation_id> and can be used to track execution of the schema change(s). The metadata field type is UpdateDatabaseDdlMetadata. The operation has no response.

Parameters:
Name Type Attributes Description
request Object

The request object that will be sent.

Properties
Name Type Attributes Description
database string

Required. The database to update.

statements Array.<string>

Required. DDL statements to be applied to the database.

operationId string <optional>

If empty, the new update request is assigned an automatically-generated operation ID. Otherwise, operation_id is used to construct the name of the resulting Operation.

Specifying an explicit operation ID simplifies determining whether the statements were executed in the event that the UpdateDatabaseDdl call is replayed, or the return value is otherwise lost: the database and operation_id fields can be combined to form the name of the resulting longrunning.Operation: <database>/operations/<operation_id>.

operation_id should be unique within the database, and must be a valid identifier: [a-z][a-z0-9_]*. Note that automatically-generated operation IDs always begin with an underscore. If the named operation already exists, UpdateDatabaseDdl returns ALREADY_EXISTS.

options Object <optional>

Optional parameters. You can override the default settings for this call, e.g, timeout, retries, paginations, etc. See gax.CallOptions for the details.

callback function <optional>

The function which will be called with the result of the API call.

The second parameter to the callback is a gax.Operation object.

Source:
Example
const spanner = require('@google-cloud/spanner');

const client = new spanner.v1.DatabaseAdminClient({
  // optional auth parameters.
});

const formattedDatabase = client.databasePath('[PROJECT]', '[INSTANCE]', '[DATABASE]');
const statements = [];
const request = {
  database: formattedDatabase,
  statements: statements,
};

// Handle the operation using the promise pattern.
client.updateDatabaseDdl(request)
  .then(responses => {
    const [operation, initialApiResponse] = responses;

    // Operation#promise starts polling for the completion of the LRO.
    return operation.promise();
  })
  .then(responses => {
    const result = responses[0];
    const metadata = responses[1];
    const finalApiResponse = responses[2];
  })
  .catch(err => {
    console.error(err);
  });

const formattedDatabase = client.databasePath('[PROJECT]', '[INSTANCE]', '[DATABASE]');
const statements = [];
const request = {
  database: formattedDatabase,
  statements: statements,
};

// Handle the operation using the event emitter pattern.
client.updateDatabaseDdl(request)
  .then(responses => {
    const [operation, initialApiResponse] = responses;

    // Adding a listener for the "complete" event starts polling for the
    // completion of the operation.
    operation.on('complete', (result, metadata, finalApiResponse) => {
      // doSomethingWith(result);
    });

    // Adding a listener for the "progress" event causes the callback to be
    // called on any change in metadata when the operation is polled.
    operation.on('progress', (metadata, apiResponse) => {
      // doSomethingWith(metadata)
    });

    // Adding a listener for the "error" event handles any errors found during polling.
    operation.on('error', err => {
      // throw(err);
    });
  })
  .catch(err => {
    console.error(err);
  });

const formattedDatabase = client.databasePath('[PROJECT]', '[INSTANCE]', '[DATABASE]');
const statements = [];
const request = {
  database: formattedDatabase,
  statements: statements,
};

// Handle the operation using the await pattern.
const [operation] = await client.updateDatabaseDdl(request);

const [response] = await operation.promise();