aster.cloud aster.cloud
  • /
  • Platforms
    • Public Cloud
    • On-Premise
    • Hybrid Cloud
    • Data
  • Architecture
    • Design
    • Solutions
    • Enterprise
  • Engineering
    • Automation
    • Software Engineering
    • Project Management
    • DevOps
  • Programming
    • Learning
  • Tools
  • About
  • /
  • Platforms
    • Public Cloud
    • On-Premise
    • Hybrid Cloud
    • Data
  • Architecture
    • Design
    • Solutions
    • Enterprise
  • Engineering
    • Automation
    • Software Engineering
    • Project Management
    • DevOps
  • Programming
    • Learning
  • Tools
  • About
aster.cloud aster.cloud
  • /
  • Platforms
    • Public Cloud
    • On-Premise
    • Hybrid Cloud
    • Data
  • Architecture
    • Design
    • Solutions
    • Enterprise
  • Engineering
    • Automation
    • Software Engineering
    • Project Management
    • DevOps
  • Programming
    • Learning
  • Tools
  • About
  • Engineering
  • Software Engineering

Golang’s Database/SQL Driver Support For Cloud Spanner Is Now Generally Available

  • aster.cloud
  • October 9, 2022
  • 3 minute read

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:

 


Partner with aster.cloud
for your next big idea.
Let us know here.



From our partners:

CITI.IO :: Business. Institutions. Society. Global Political Economy.
CYBERPOGO.COM :: For the Arts, Sciences, and Technology.
DADAHACKS.COM :: Parenting For The Rest Of Us.
ZEDISTA.COM :: Entertainment. Sports. Culture. Escape.
TAKUMAKU.COM :: For The Hearth And Home.
ASTER.CLOUD :: From The Cloud And Beyond.
LIWAIWAI.COM :: Intelligence, Inside and Outside.
GLOBALCLOUDPLATFORMS.COM :: For The World's Computing Needs.
FIREGULAMAN.COM :: For The Fire In The Belly Of The Coder.
ASTERCASTER.COM :: Supra Astra. Beyond The Stars.
BARTDAY.COM :: Prosperity For Everyone.

import _ "github.com/googleapis/go-sql-spanner"

db, err := sql.Open("spanner", "projects/PROJECT/instances/INSTANCE/databases/DATABASE")
if err != nil {
    log.Fatal(err)
}

// Print Singers with ID greater than 500.
rows, err := db.QueryContext(ctx, "SELECT SingerId, FirstName FROM Singers WHERE SingerId > @id", 500)
if err != nil {
    log.Fatal(err)
}
defer rows.Close()

var (
    singerID   int64
    firstName string
)
for rows.Next() {
    if err := rows.Scan(&singerID, &firstName); err != nil {
        log.Fatal(err)
    }
    fmt.Println(singerID, firstName)
}

 

Installation

Simple install the package to your $GOPATH with the go tool from shell:

 

$ go get -u github.com/googleapis/go-sql-spanner

 

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:

 

projects/my-project/instances/my-instance/databases/my-database?credentials=/path/to/credentials.json

 

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:

 

127.0.0.1:55217/projects/p/instances/i/databases/d?useplaintext=true;

 

The full connection string regular expression is:

Read More  Force Terraform Resource Recreation

 

((?P<HOSTGROUP>[\w.-]+(?:\.[\w\.-]+)*[\w\-\._~:/?#\[\]@!\$&'\(\)\*\+,;=.]+)/)?projects/(?P<PROJECTGROUP>(([a-z]|[-.:]|[0-9])+|(DEFAULT_PROJECT_ID)))(/instances/(?P<INSTANCEGROUP>([a-z]|[-]|[0-9])+)(/databases/(?P<DATABASEGROUP>([a-z]|[-]|[_]|[0-9])+))?)?(([\?|;])(?P<PARAMSGROUP>.*))?

 

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 (?).

 

db.QueryContext(ctx, "SELECT SingerId, FirstName FROM Singers WHERE SingerId = @id", 14544498215374)

db.ExecContext(ctx, "INSERT INTO Singers (SingerId, FirstName, LastName) VALUES (@id, @firstName, @lastName)", id, firstName, lastName)

db.ExecContext(ctx, "DELETE FROM Singers WHERE SingerId = ?", 14544498215374)

 

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:

 

db, _ := sql.Open("spanner", "projects/PROJECT/instances/INSTANCE/databases/DATABASE")
db.ExecContext(ctx, "CREATE TABLE ...")

 

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:

 

conn, _ := db.Conn(ctx)
// Executing `START BATCH DDL` will initialize a DDL batch.
// Subsequent statements must all be DDL until `RUN BATCH` or `ABORT BATCH` is executed.
_, _ = conn.ExecContext(ctx, "START BATCH DDL")

// This will be cached locally until a `RUN BATCH` statement is executed.
_, _ = conn.ExecContext(ctx, `CREATE TABLE Singers (
     SingerId INT64,
     FirstName STRING(MAX),
     LastName STRING(MAX),
) PRIMARY KEY (SingerId)`)


_, _ = conn.ExecContext(ctx, "CREATE INDEX Idx_Singers_Name ON Singers (Name)")

// Executing `RUN BATCH` will run the previous DDL statements as one batch.
_, _ := conn.ExecContext(ctx, "RUN BATCH")

 

Read More  Unlocking Opportunities With Data Transformation

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:

  • Cloud Spanner product documentation
  • Getting started with Cloud Spanner in Go
  • Cloud Spanner Golang client library
  • Cloud Spanner Quotas & Limits
  • Benchmark run of driver against the go client

 

 

By: Rahul Yadav (Software Engineer, Google Cloud)
Source: Google Cloud Blog


For enquiries, product placements, sponsorships, and collaborations, connect with us at [email protected]. We'd love to hear from you!

Our humans need coffee too! Your support is highly appreciated, thank you!

aster.cloud

Related Topics
  • Cloud Spanner
  • Database Driver
  • Databases
  • Golang
  • Google Cloud
  • Tutorials
You May Also Like
View Post
  • Engineering
  • Technology

Guide: Our top four AI Hypercomputer use cases, reference architectures and tutorials

  • March 9, 2025
View Post
  • Software Engineering
  • Technology

Claude 3.7 Sonnet and Claude Code

  • February 25, 2025
View Post
  • Computing
  • Engineering

Why a decades old architecture decision is impeding the power of AI computing

  • February 19, 2025
View Post
  • Engineering
  • Software Engineering

This Month in Julia World

  • January 17, 2025
View Post
  • Engineering
  • Software Engineering

Google Summer of Code 2025 is here!

  • January 17, 2025
View Post
  • Data
  • Engineering

Hiding in Plain Site: Attackers Sneaking Malware into Images on Websites

  • January 16, 2025
View Post
  • Computing
  • Design
  • Engineering
  • Technology

Here’s why it’s important to build long-term cryptographic resilience

  • December 24, 2024
IBM and Ferrari Premium Partner
View Post
  • Data
  • Engineering

IBM Selected as Official Fan Engagement and Data Analytics Partner for Scuderia Ferrari HP

  • November 7, 2024

Stay Connected!
LATEST
  • college-of-cardinals-2025 1
    The Definitive Who’s Who of the 2025 Papal Conclave
    • May 7, 2025
  • conclave-poster-black-smoke 2
    The World Is Revalidating Itself
    • May 6, 2025
  • oracle-ibm 3
    IBM and Oracle Expand Partnership to Advance Agentic AI and Hybrid Cloud
    • May 6, 2025
  • 4
    Conclave: How A New Pope Is Chosen
    • April 25, 2025
  • Getting things done makes her feel amazing 5
    Nurturing Minds in the Digital Revolution
    • April 25, 2025
  • 6
    AI is automating our jobs – but values need to change if we are to be liberated by it
    • April 17, 2025
  • 7
    Canonical Releases Ubuntu 25.04 Plucky Puffin
    • April 17, 2025
  • 8
    United States Army Enterprise Cloud Management Agency Expands its Oracle Defense Cloud Services
    • April 15, 2025
  • 9
    Tokyo Electron and IBM Renew Collaboration for Advanced Semiconductor Technology
    • April 2, 2025
  • 10
    IBM Accelerates Momentum in the as a Service Space with Growing Portfolio of Tools Simplifying Infrastructure Management
    • March 27, 2025
about
Hello World!

We are aster.cloud. We’re created by programmers for programmers.

Our site aims to provide guides, programming tips, reviews, and interesting materials for tech people and those who want to learn in general.

We would like to hear from you.

If you have any feedback, enquiries, or sponsorship request, kindly reach out to us at:

[email protected]
Most Popular
  • 1
    Tariffs, Trump, and Other Things That Start With T – They’re Not The Problem, It’s How We Use Them
    • March 25, 2025
  • 2
    IBM contributes key open-source projects to Linux Foundation to advance AI community participation
    • March 22, 2025
  • 3
    Co-op mode: New partners driving the future of gaming with AI
    • March 22, 2025
  • 4
    Mitsubishi Motors Canada Launches AI-Powered “Intelligent Companion” to Transform the 2025 Outlander Buying Experience
    • March 10, 2025
  • PiPiPi 5
    The Unexpected Pi-Fect Deals This March 14
    • March 13, 2025
  • /
  • Technology
  • Tools
  • About
  • Contact Us

Input your search keywords and press Enter.