Last active
February 27, 2023 17:17
-
-
Save rwilcox/16f0b240aa37a52017149a4eaad7baa3 to your computer and use it in GitHub Desktop.
Spanner and Typescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// I should probably write a blog post about this, but whatever | |
import { Spanner, Instance } from '@google-cloud/spanner' | |
import type { Database } from '@google-cloud/spanner' | |
/** | |
Authentication is provided by the local machine user running | |
`gcloud auth application-default login` | |
*/ | |
let gSpannerInstance: (Instance | null) = null | |
export function getSpannerInstance(instance: string): Instance { | |
if (gSpannerInstance) { return gSpannerInstance! } | |
const projectId = 'EXAMPLE_PROJECT'; | |
const instanceId = instance | |
// Creates a client | |
const spanner = new Spanner({ | |
projectId: projectId, | |
}); | |
// Gets a reference to a Cloud Spanner instance | |
gSpannerInstance = spanner.instance(instanceId); | |
return gSpannerInstance! | |
} | |
let gSpannerDatabaseInstance: (Database | null) = null | |
export function getSpannerDatabaseInstance(spannerInstance: Instance, databaseId: string): Database { | |
if (gSpannerDatabaseInstance) { return gSpannerDatabaseInstance! } | |
gSpannerDatabaseInstance = spannerInstance.database(databaseId); | |
return gSpannerDatabaseInstance! | |
} | |
class MyResult { | |
first_name: string | null | |
last_name: string | null | |
constructor() { | |
this.first_name = null | |
this.last_name = null | |
} | |
} | |
async function main() { | |
const db = getSpannerDatabaseInstance( getSpannerInstance('my-instance'), | |
'my-database' ) | |
// The query to execute | |
const query = { | |
sql: 'SELECT first_name, last_name from users', | |
}; | |
// Execute a simple SQL statement | |
const [rows] = await db.run(query); | |
rows.forEach( (row ) => { | |
// row is a Database.PartialResult, but I can't type this variable with | |
// this here. | |
// HOWEVER, row is an array of name/value objects, each | |
// field you request gets its own object | |
// so if you have a first_name field in your table | |
// and you select first_name from myTable | |
// you will get [ { name: 'first_name', value: 'ryan' }] | |
// BUT calling toJSON will get you a plain ol' Javascript object | |
// that you would expect | |
// { "first_name": "Ryan" } | |
let result = row.toJSON() as MyResult // Teccchnically this is just hope at the compiler level... | |
console.log(result) | |
}); | |
} | |
main().then( () => { | |
console.log("done!") | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment