Golang’s database/sql driver support for Cloud Spanner is now Generally Available
Rahul Yadav
Software Engineer, Google Cloud
Golang’s database/sql driver support for Cloud Spanner is now Generally Available
Overview
Go SQL Spanner Driver is an implementation of Go's database/sql/driver interface. Add the driver to your application to enable the use of the database/sql API with Cloud Spanner. Use spanner as driverName and a valid Connection String as dataSourceName:
Installation
Simple install the package to your $GOPATH with the go tool from shell:
Make sure Git is installed on your machine and in your system's PATH.
Architecture
The Spanner database/sql driver uses the Go client library for Google Cloud Spanner for session management, encoding and decoding data, and transaction management.
Connection String
A connection string is the string that specifies information about a data source and the means of connecting to it. It is passed in code to an underlying driver or provider to initiate the connection.
A typical connection string for Cloud Spanner consists of the fully qualified database name followed by an optional list of parameters:
A connection string can optionally also include a host and port number. This is used to connect to a custom endpoint (for example an in-mem mock server) and looks like this:
The full connection string regular expression is:
Note that as the driver uses the Go client to connect to Spanner, it is not necessary to specify a custom endpoint to connect to the Spanner emulator. The driver will automatically connect to the emulator if the SPANNER_EMULATOR_HOST
environment variable has been set.
Usage
Statements
The driver supports both named and positional parameters. Named parameters start with an ampersand (@
). Positional parameters are declared using a question mark (?
).
DDL Statements
DDL statements are not supported in transactions as per Cloud Spanner restriction. Instead, you can run them on a connection without an active transaction:
It is recommended to batch multiple DDL statements together for optimal execution speed. Multiple DDL statements can be sent in one batch to Cloud Spanner by defining a DDL batch:
You can also refer to the batch DDL example.
Limitations
Cloud Spanner features that are not supported in the driver are listed here.
Getting Involved
We'd love to hear from you, especially if you're a Golang developer considering Cloud Spanner or an existing Cloud Spanner customer who is considering using database/sql for new projects. The project is open-source, and you can comment, report bugs, and open pull requests on Github.
See Also
Before you get started, you need to have a golang project. For a complete set of examples, you can find them in the examples directory for the driver. You can additionally refer: