Create a Table object to interact with a table in a Cloud Spanner database.
Package
@google-cloud/spannerExample
const{Spanner}=require('@google-cloud/spanner');constspanner=newSpanner();constinstance=spanner.instance('my-instance');constdatabase=instance.database('my-database');consttable=database.table('my-table');
Constructors
(constructor)(database, name)
constructor(database:Database,name:string);
Constructs a new instance of theTable class
| Parameters |
|---|
| Name | Description |
database | Database
|
name | string
|
Properties
database
name
Methods
create(schema, gaxOptions)
create(schema:Schema,gaxOptions?:CallOptions):Promise<CreateTableResponse>;
| Parameters |
|---|
| Name | Description |
schema | Schema
See . |
gaxOptions | CallOptions
Call options. SeeCallOptions for more details. |
| Returns |
|---|
| Type | Description |
Promise<CreateTableResponse> | {Promise |
Exampleconst{Spanner}=require('@google-cloud/spanner');constspanner=newSpanner();constinstance=spanner.instance('my-instance');constdatabase=instance.database('my-database');consttable=database.table('Singers');constschema='CREATE TABLE Singers ('+' SingerId INT64 NOT NULL,'+' FirstName STRING(1024),'+' LastName STRING(1024),'+' SingerInfo BYTES(MAX),'+') PRIMARY KEY(SingerId)';table.create(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.//-table.create(schema).then(function(data){consttable=data[0];constoperation=data[1];returnoperation.promise();}).then(function(){// Table created successfully.});
create(schema, callback)
create(schema:Schema,callback:CreateTableCallback):void;
| Parameters |
|---|
| Name | Description |
schema | Schema
|
callback | CreateTableCallback
|
| Returns |
|---|
| Type | Description |
void | |
create(schema, gaxOptions, callback)
create(schema:Schema,gaxOptions:CallOptions,callback:CreateTableCallback):void;
| Parameters |
|---|
| Name | Description |
schema | Schema
|
gaxOptions | CallOptions
|
callback | CreateTableCallback
|
| Returns |
|---|
| Type | Description |
void | |
createReadStream(request, options)
createReadStream(request:ReadRequest,options?:TimestampBounds):PartialResultStream;
Create a readable object stream to receive rows from the database using key lookups and scans.
| Returns |
|---|
| Type | Description |
PartialResultStream | {PartialResultStream} A readable stream that emits rows. |
Exampleconst{Spanner}=require('@google-cloud/spanner');constspanner=newSpanner();constinstance=spanner.instance('my-instance');constdatabase=instance.database('my-database');consttable=database.table('Singers');table.createReadStream({keys:['1'],columns:['SingerId','name']}).on('error',function(err){}).on('data',function(row){// row = {// SingerId: '1',// Name: 'Eddie Wilson'// }}).on('end',function(){// All results retrieved.});//-// Provide an array for `query.keys` to read with a composite key.//-constquery={keys:[['Id1','Name1'],['Id2','Name2']],// ...};//-// If you anticipate many results, you can end a stream early to prevent// unnecessary processing and API requests.//-table.createReadStream({keys:['1'],columns:['SingerId','name']}).on('data',function(row){this.end();});
delete(gaxOptions)
delete(gaxOptions?:CallOptions):Promise<DropTableResponse>;
Delete the table. Not to be confused with .
Wrapper around .
| Parameter |
|---|
| Name | Description |
gaxOptions | CallOptions
Call options. SeeCallOptions for more details. |
| Returns |
|---|
| Type | Description |
Promise<DropTableResponse> | {Promise |
Exampleconst{Spanner}=require('@google-cloud/spanner');constspanner=newSpanner();constinstance=spanner.instance('my-instance');constdatabase=instance.database('my-database');consttable=database.table('Singers');table.delete(function(err,operation,apiResponse){if(err){// Error handling omitted.}operation.on('error',function(err){}).on('complete',function(){// Table deleted successfully.});});//-// If the callback is omitted, we'll return a Promise.//-table.delete().then(function(data){constoperation=data[0];returnoperation.promise();}).then(function(){// Table deleted successfully.});
delete(callback)
delete(callback:DropTableCallback):void;
| Parameter |
|---|
| Name | Description |
callback | DropTableCallback
|
| Returns |
|---|
| Type | Description |
void | |
delete(gaxOptions, callback)
delete(gaxOptions:CallOptions,callback:DropTableCallback):void;
| Parameters |
|---|
| Name | Description |
gaxOptions | CallOptions
|
callback | DropTableCallback
|
| Returns |
|---|
| Type | Description |
void | |
deleteRows(keys, options)
deleteRows(keys:Key[],options?:DeleteRowsOptions|CallOptions):Promise<DeleteRowsResponse>;
Delete rows from this table.
| Parameters |
|---|
| Name | Description |
keys | Key[]
The keys for the rows to delete. If using a composite key, provide an array within this array. See the example below. |
options | DeleteRowsOptions |CallOptions
Options for configuring the request. SeeCallOptions for more details. |
| Returns |
|---|
| Type | Description |
Promise<DeleteRowsResponse> | {Promise |
Exampleconst{Spanner}=require('@google-cloud/spanner');constspanner=newSpanner();constinstance=spanner.instance('my-instance');constdatabase=instance.database('my-database');consttable=database.table('Singers');constkeys=['Id1','Id2','Id3'];table.deleteRows(keys,function(err,apiResponse){});//-// Provide an array for `keys` to delete rows with a composite key.//-constkeys=[['Id1','Name1'],['Id2','Name2']];//-// If the callback is omitted, we'll return a Promise.//-table.deleteRows(keys).then(function(data){constapiResponse=data[0];});
deleteRows(keys, callback)
deleteRows(keys:Key[],callback:DeleteRowsCallback):void;
| Parameters |
|---|
| Name | Description |
keys | Key[]
|
callback | DeleteRowsCallback
|
| Returns |
|---|
| Type | Description |
void | |
deleteRows(keys, options, callback)
deleteRows(keys:Key[],options:DeleteRowsOptions|CallOptions,callback:DeleteRowsCallback):void;
| Parameters |
|---|
| Name | Description |
keys | Key[]
|
options | DeleteRowsOptions |CallOptions
|
callback | DeleteRowsCallback
|
| Returns |
|---|
| Type | Description |
void | |
drop(gaxOptions)
drop(gaxOptions?:CallOptions):Promise<DropTableResponse>;
| Parameter |
|---|
| Name | Description |
gaxOptions | CallOptions
Request configuration options. SeeCallOptions for more details. |
| Returns |
|---|
| Type | Description |
Promise<DropTableResponse> | {Promise |
Exampleconst{Spanner}=require('@google-cloud/spanner');constspanner=newSpanner();constinstance=spanner.instance('my-instance');constdatabase=instance.database('my-database');consttable=database.table('Singers');table.drop(function(err,operation,apiResponse){if(err){// Error handling omitted.}operation.on('error',function(err){}).on('complete',function(){// Table dropped successfully.});});//-// If the callback is omitted, we'll return a Promise.//-table.drop().then(function(data){constoperation=data[0];returnoperation.promise();}).then(function(){// Table dropped successfully.});
drop(callback)
drop(callback:DropTableCallback):void;
| Parameter |
|---|
| Name | Description |
callback | DropTableCallback
|
| Returns |
|---|
| Type | Description |
void | |
drop(gaxOptions, callback)
drop(gaxOptions:CallOptions,callback:DropTableCallback):void;
| Parameters |
|---|
| Name | Description |
gaxOptions | CallOptions
|
callback | DropTableCallback
|
| Returns |
|---|
| Type | Description |
void | |
insert(rows, options)
insert(rows:object|object[],options?:InsertRowsOptions|CallOptions):Promise<InsertRowsResponse>;
Insert rows of data into this table.
| Parameters |
|---|
| Name | Description |
rows | object | object[]
A map of names to values of data to insert into this table. |
options | InsertRowsOptions |CallOptions
Options for configuring the request. SeeCallOptions for more details. |
| Returns |
|---|
| Type | Description |
Promise<InsertRowsResponse> | {Promise |
Examplesconst{Spanner}=require('@google-cloud/spanner');constspanner=newSpanner();constinstance=spanner.instance('my-instance');constdatabase=instance.database('my-database');consttable=database.table('Singers');constrow={SingerId:'Id3',Name:'Eddie Wilson'};table.insert(row,function(err,apiResponse){if(err){// Error handling omitted.}// Rows inserted successfully.});//-// Multiple rows can be inserted at once.//-constrow2={SingerId:'Id3b',Name:'Joe West'};table.insert([row,row2],function(err,apiResponse){});//-// If the callback is omitted, we'll return a Promise.//-table.insert(row).then(function(data){constapiResponse=data[0];});
Full example:
// Imports the Google Cloud client libraryconst{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 clientconstspanner=newSpanner({projectId:projectId,});// Gets a reference to a Cloud Spanner instance and databaseconstinstance=spanner.instance(instanceId);constdatabase=instance.database(databaseId);// Instantiate Spanner table objectsconstsingersTable=database.table('Singers');constalbumsTable=database.table('Albums');// Inserts rows into the Singers table// Note: Cloud Spanner interprets Node.js numbers as FLOAT64s, so// they must be converted to strings before being inserted as INT64stry{awaitsingersTable.insert([{SingerId:'1',FirstName:'Marc',LastName:'Richards'},{SingerId:'2',FirstName:'Catalina',LastName:'Smith'},{SingerId:'3',FirstName:'Alice',LastName:'Trentor'},{SingerId:'4',FirstName:'Lea',LastName:'Martin'},{SingerId:'5',FirstName:'David',LastName:'Lomond'},]);awaitalbumsTable.insert([{SingerId:'1',AlbumId:'1',AlbumTitle:'Total Junk'},{SingerId:'1',AlbumId:'2',AlbumTitle:'Go, Go, Go'},{SingerId:'2',AlbumId:'1',AlbumTitle:'Green'},{SingerId:'2',AlbumId:'2',AlbumTitle:'Forever Hold your Peace'},{SingerId:'2',AlbumId:'3',AlbumTitle:'Terrified'},]);console.log('Inserted data.');}catch(err){console.error('ERROR:',err);}finally{awaitdatabase.close();}
insert(rows, callback)
insert(rows:object|object[],callback:InsertRowsCallback):void;
| Parameters |
|---|
| Name | Description |
rows | object | object[]
|
callback | InsertRowsCallback
|
| Returns |
|---|
| Type | Description |
void | |
insert(rows, options, callback)
insert(rows:object|object[],options:InsertRowsOptions|CallOptions,callback:InsertRowsCallback):void;
| Parameters |
|---|
| Name | Description |
rows | object | object[]
|
options | InsertRowsOptions |CallOptions
|
callback | InsertRowsCallback
|
| Returns |
|---|
| Type | Description |
void | |
read(request, options)
read(request:ReadRequest,options?:TimestampBounds):Promise<ReadResponse>;
Receive rows from the database using key lookups and scans.
**Performance Considerations:**
This method wraps the streaming method, for your convenience. All rows will be stored in memory before being released to your callback. If you intend on receiving a lot of results from your query, consider using the streaming method, so you can free each result from memory after consuming it.
| Returns |
|---|
| Type | Description |
Promise<ReadResponse> | {Promise |
Examplesconst{Spanner}=require('@google-cloud/spanner');constspanner=newSpanner();constinstance=spanner.instance('my-instance');constdatabase=instance.database('my-database');consttable=database.table('Singers');constquery={keys:['1'],columns:['SingerId','name']};table.read(query,function(err,rows){if(err){// Error handling omitted.}constfirstRow=rows[0];// firstRow = [// {// name: 'SingerId',// value: '1'// },// {// name: 'Name',// value: 'Eddie Wilson'// }// ]});//-// Provide an array for `query.keys` to read with a composite key.//-constquery={keys:[['Id1','Name1'],['Id2','Name2']],// ...};//-// Rows are returned as an array of object arrays. Each object has a `name`// and `value` property. To get a serialized object, call `toJSON()`.//// Alternatively, set `query.json` to `true`, and this step will beperformed// automatically.//-table.read(query,function(err,rows){if(err){// Error handling omitted.}constfirstRow=rows[0];// firstRow.toJSON() = {// SingerId: '1',// Name: 'Eddie Wilson'// }});//-// If the callback is omitted, we'll return a Promise.//-table.read(query).then(function(data){constrows=data[0];});
Full example:
// Imports the Google Cloud client libraryconst{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 clientconstspanner=newSpanner({projectId:projectId,});// Gets a reference to a Cloud Spanner instance and databaseconstinstance=spanner.instance(instanceId);constdatabase=instance.database(databaseId);// Reads rows from the Albums tableconstalbumsTable=database.table('Albums');constquery={columns:['SingerId','AlbumId','AlbumTitle'],keySet:{all:true,},};try{const[rows]=awaitalbumsTable.read(query);rows.forEach(row=>{constjson=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.awaitdatabase.close();}
Reading stale data:
// Imports the Google Cloud client libraryconst{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 clientconstspanner=newSpanner({projectId:projectId,});// Gets a reference to a Cloud Spanner instance and databaseconstinstance=spanner.instance(instanceId);constdatabase=instance.database(databaseId);// Reads rows from the Albums tableconstalbumsTable=database.table('Albums');constquery={columns:['SingerId','AlbumId','AlbumTitle','MarketingBudget'],keySet:{all:true,},};constoptions={// Guarantees that all writes committed more than 15 seconds ago are visibleexactStaleness:15,};try{const[rows]=awaitalbumsTable.read(query,options);rows.forEach(row=>{constjson=row.toJSON();constid=json.SingerId;constalbum=json.AlbumId;consttitle=json.AlbumTitle;constbudget=json.MarketingBudget?json.MarketingBudget:'';console.log(`SingerId:${id}, AlbumId:${album}, AlbumTitle:${title}, MarketingBudget:${budget}`);});}catch(err){console.error('ERROR:',err);}finally{// Close the database when finished.awaitdatabase.close();}
Reading data using an index:
// Imports the Google Cloud client libraryconst{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 clientconstspanner=newSpanner({projectId:projectId,});// Gets a reference to a Cloud Spanner instance and databaseconstinstance=spanner.instance(instanceId);constdatabase=instance.database(databaseId);constalbumsTable=database.table('Albums');constquery={columns:['AlbumId','AlbumTitle'],keySet:{all:true,},index:'AlbumsByAlbumTitle',};// Reads the Albums table using an indextry{const[rows]=awaitalbumsTable.read(query);rows.forEach(row=>{constjson=row.toJSON();console.log(`AlbumId:${json.AlbumId}, AlbumTitle:${json.AlbumTitle}`);});}catch(err){console.error('ERROR:',err);}finally{// Close the database when finished.database.close();}
Reading data using 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 libraryconst{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 clientconstspanner=newSpanner({projectId:projectId,});// Gets a reference to a Cloud Spanner instance and databaseconstinstance=spanner.instance(instanceId);constdatabase=instance.database(databaseId);constalbumsTable=database.table('Albums');constquery={columns:['AlbumId','AlbumTitle','MarketingBudget'],keySet:{all:true,},index:'AlbumsByAlbumTitle2',};// Reads the Albums table using a storing indextry{const[rows]=awaitalbumsTable.read(query);rows.forEach(row=>{constjson=row.toJSON();letrowString=`AlbumId:${json.AlbumId}`;rowString+=`, AlbumTitle:${json.AlbumTitle}`;if(json.MarketingBudget){rowString+=`, MarketingBudget:${json.MarketingBudget}`;}console.log(rowString);});}catch(err){console.error('ERROR:',err);}finally{// Close the database when finished.database.close();}
read(request, callback)
read(request:ReadRequest,callback:ReadCallback):void;
| Parameters |
|---|
| Name | Description |
request | ReadRequest
|
callback | ReadCallback
|
| Returns |
|---|
| Type | Description |
void | |
read(request, options, callback)
read(request:ReadRequest,options:TimestampBounds,callback:ReadCallback):void;
| Parameters |
|---|
| Name | Description |
request | ReadRequest
|
options | TimestampBounds
|
callback | ReadCallback
|
| Returns |
|---|
| Type | Description |
void | |
replace(rows, options)
replace(rows:object|object[],options?:ReplaceRowsOptions|CallOptions):Promise<ReplaceRowsResponse>;
Replace rows of data within this table.
| Parameters |
|---|
| Name | Description |
rows | object | object[]
A map of names to values of data to insert into this table. |
options | ReplaceRowsOptions |CallOptions
Options for configuring the request. SeeCallOptions for more details. |
| Returns |
|---|
| Type | Description |
Promise<ReplaceRowsResponse> | {Promise |
Exampleconst{Spanner}=require('@google-cloud/spanner');constspanner=newSpanner();constinstance=spanner.instance('my-instance');constdatabase=instance.database('my-database');consttable=database.table('Singers');constrow={SingerId:'Id3',Name:'Joe West'};table.replace(row,function(err,apiResponse){if(err){// Error handling omitted.}// Row replaced successfully.});//-// If the callback is omitted, we'll return a Promise.//-table.replace(row).then(function(data){constapiResponse=data[0];});
replace(rows, callback)
replace(rows:object|object[],callback:ReplaceRowsCallback):void;
| Parameters |
|---|
| Name | Description |
rows | object | object[]
|
callback | ReplaceRowsCallback
|
| Returns |
|---|
| Type | Description |
void | |
replace(rows, options, callback)
replace(rows:object|object[],options:ReplaceRowsOptions|CallOptions,callback:ReplaceRowsCallback):void;
| Parameters |
|---|
| Name | Description |
rows | object | object[]
|
options | ReplaceRowsOptions |CallOptions
|
callback | ReplaceRowsCallback
|
| Returns |
|---|
| Type | Description |
void | |
update(rows, options)
update(rows:object|object[],options?:UpdateRowsOptions|CallOptions):Promise<UpdateRowsResponse>;
Update rows of data within this table.
| Parameters |
|---|
| Name | Description |
rows | object | object[]
A map of names to values of data to insert into this table. |
options | UpdateRowsOptions |CallOptions
Options for configuring the request. SeeCallOptions for more details. |
| Returns |
|---|
| Type | Description |
Promise<UpdateRowsResponse> | {Promise |
Examplesconst{Spanner}=require('@google-cloud/spanner');constspanner=newSpanner();constinstance=spanner.instance('my-instance');constdatabase=instance.database('my-database');consttable=database.table('Singers');constrow={SingerId:'Id3',Name:'Joe West'};table.update(row,function(err,apiResponse){if(err){// Error handling omitted.}// Row updated successfully.});//-// If the callback is omitted, we'll return a Promise.//-table.update(row).then(function(data){constapiResponse=data[0];});
Full example:
// Imports the Google Cloud client libraryconst{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 clientconstspanner=newSpanner({projectId:projectId,});// Gets a reference to a Cloud Spanner instance and databaseconstinstance=spanner.instance(instanceId);constdatabase=instance.database(databaseId);// Update a row in the Albums table// Note: Cloud Spanner interprets Node.js numbers as FLOAT64s, so they// must be converted to strings before being inserted as INT64sconstalbumsTable=database.table('Albums');try{awaitalbumsTable.update([{SingerId:'1',AlbumId:'1',MarketingBudget:'100000'},{SingerId:'2',AlbumId:'2',MarketingBudget:'500000'},]);console.log('Updated data.');}catch(err){console.error('ERROR:',err);}finally{// Close the database when finished.database.close();}
update(rows, callback)
update(rows:object|object[],callback:UpdateRowsCallback):void;
| Parameters |
|---|
| Name | Description |
rows | object | object[]
|
callback | UpdateRowsCallback
|
| Returns |
|---|
| Type | Description |
void | |
update(rows, options, callback)
update(rows:object|object[],options:UpdateRowsOptions|CallOptions,callback:UpdateRowsCallback):void;
| Parameters |
|---|
| Name | Description |
rows | object | object[]
|
options | UpdateRowsOptions |CallOptions
|
callback | UpdateRowsCallback
|
| Returns |
|---|
| Type | Description |
void | |
upsert(rows, options)
upsert(rows:object|object[],options?:UpsertRowsOptions|CallOptions):Promise<UpsertRowsResponse>;
Insert or update rows of data within this table.
| Parameters |
|---|
| Name | Description |
rows | object | object[]
A map of names to values of data to insert into this table. |
options | UpsertRowsOptions |CallOptions
Options for configuring the request. SeeCallOptions for more details. |
| Returns |
|---|
| Type | Description |
Promise<UpsertRowsResponse> | {Promise |
Exampleconst{Spanner}=require('@google-cloud/spanner');constspanner=newSpanner();constinstance=spanner.instance('my-instance');constdatabase=instance.database('my-database');consttable=database.table('Singers');constrow={SingerId:'Id3',Name:'Joe West'};table.upsert(row,function(err,apiResponse){if(err){// Error handling omitted.}// Row inserted or updated successfully.});//-// If the callback is omitted, we'll return a Promise.//-table.upsert(row).then(function(data){constapiResponse=data[0];});
upsert(rows, callback)
upsert(rows:object|object[],callback:UpsertRowsCallback):void;
| Parameters |
|---|
| Name | Description |
rows | object | object[]
|
callback | UpsertRowsCallback
|
| Returns |
|---|
| Type | Description |
void | |
upsert(rows, options, callback)
upsert(rows:object|object[],options:UpsertRowsOptions|CallOptions,callback:UpsertRowsCallback):void;
| Parameters |
|---|
| Name | Description |
rows | object | object[]
|
options | UpsertRowsOptions |CallOptions
|
callback | UpsertRowsCallback
|
| Returns |
|---|
| Type | Description |
void | |