spansqlx

package module
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 15, 2022 License: MIT Imports: 7 Imported by: 0

README

spansqlx

spanner sql pkgs

install

go get github.com/reiot101/spansqlx

usage

Below is an example which shows some common use cases for spansqlx. Check example_test.go for more usage.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/reiot101/spansqlx"
)

func main() {
	var database = "projects/sandbox/instances/sandbox/databases/sandbox"
	// this Pings the spanner database trying to connect
	// use spansqlx.Open() for spanner.NewClient() semantics
	db, err := spansqlx.Open(context.Background(), spansqlx.WithDatabase(database))
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// use TxPipeline (spanner.ReadWriteTransation), exec multi statements.
	if err := db.TxPipeline(context.Background(), func(ctx context.Context) error {
		var sqlInsertSingers = `INSERT INTO Singers (SingerId, FirstName, LastName) VALUES(@singer_id, @first_name, @last_name)`
		for _, singer := range allSingers {
			if err := db.Exec(ctx, sqlInsertSingers,
				singer.SingerID,
				singer.FirstName,
				singer.LastName,
			); err != nil {
				return err
			}
		}

		var sqlInsertAlbums = `INSERT INTO Albums (SingerID, AlbumID, AlbumTitle) VALUES (@SingerID, @AlbumID, @AlbumTitle)`
		for _, album := range allAlbums {
			if err := db.NamedExec(ctx, sqlInsertAlbums, album); err != nil {
				return err
			}
		}

		return nil
	}); err != nil {
		log.Fatalf("failed to spansqlx.TxPipeline %v", err)
	}

	// Query the database, storing results in a []Singer (wrapped in []interface)
	if err := db.Select(context.Background(), nil, `SELECT * FROM Singers ORDER BY FirstName DESC`); err != nil {
		log.Fatal(err)
	}

	// You can also get a a single result
	var david Singer
	db.Get(context.Background(), &david, `SELECT * FROM Singers WHERE FirstName=first_name`, "David")
	fmt.Printf("%#v\n", david)
}

Documentation

Overview

Example (Usage)
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/reiot101/spansqlx"
)

type Singer struct {
	SingerID  int64
	FirstName string
	LastName  string
}

type Album struct {
	SingerID   int64
	AlbumID    int64
	AlbumTitle string
}

var (
	database = "projects/sandbox/instances/sandbox/databases/sandbox"

	allSingers = []Singer{
		{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"},
	}
	allAlbums = []Album{
		{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"},
	}
)

func main() {
	// this Pings the spanner database trying to connect
	// use spansqlx.Open() for spanner.NewClient() semantics
	db, err := spansqlx.Open(context.Background(), spansqlx.WithDatabase(database))
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// use TxPipeline (spanner.ReadWriteTransation), exec multi statements.
	if err := db.TxPipeline(context.Background(), func(ctx context.Context) error {
		var sqlInsertSingers = `INSERT INTO Singers (SingerId, FirstName, LastName) VALUES(@singer_id, @first_name, @last_name)`
		for _, singer := range allSingers {
			if err := db.Exec(ctx, sqlInsertSingers,
				singer.SingerID,
				singer.FirstName,
				singer.LastName,
			); err != nil {
				return err
			}
		}

		var sqlInsertAlbums = `INSERT INTO Albums (SingerID, AlbumID, AlbumTitle) VALUES (@SingerID, @AlbumID, @AlbumTitle)`
		for _, album := range allAlbums {
			if err := db.NamedExec(ctx, sqlInsertAlbums, album); err != nil {
				return err
			}
		}

		return nil
	}); err != nil {
		log.Fatalf("failed to spansqlx.TxPipeline %v", err)
	}

	// Query the database, storing results in a []Singer (wrapped in []interface)
	if err := db.Select(context.Background(), nil, `SELECT * FROM Singers ORDER BY FirstName DESC`); err != nil {
		log.Fatal(err)
	}

	// You can also get a a single result
	var david Singer
	db.Get(context.Background(), &david, `SELECT * FROM Singers WHERE FirstName=first_name`, "David")
	fmt.Printf("%#v\n", david)
}
Output:

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrBadConn = errors.New("scansqlx: bad connection")
	ErrNoRows  = errors.New("scansqlx: no rows")
)

Functions

func SetTxContext

func SetTxContext(ctx context.Context, arg interface{}) context.Context

Types

type DB

type DB struct {
	// contains filtered or unexported fields
}

DB is a wrapper around spanner.Client which keeps track of the options upon Open, used mostly to automatically bind named queries using the right bindvars.

func NewDb

func NewDb(ctx context.Context, db *spanner.Client) *DB

NewDb returns an DB instance.

func Open

func Open(ctx context.Context, opts ...Option) (*DB, error)

Open is the same as spanner.NewClient, but returns an *spansql.DB instead.

func (*DB) Close

func (d *DB) Close() error

Close the database connection

func (*DB) Exec

func (d *DB) Exec(ctx context.Context, sql string, args ...interface{}) error

func (*DB) ExecX

func (d *DB) ExecX(ctx context.Context, stmt spanner.Statement) error

func (*DB) Get

func (d *DB) Get(ctx context.Context, dest interface{}, sql string, args ...interface{}) error

Get within a transaction. Any placeholder parameters are replaced with supplied args. An error is returned if the result set is empty.

func (*DB) GetX

func (d *DB) GetX(ctx context.Context, dest interface{}, stmt spanner.Statement) error

GetX within a transaction. Based spanner statement. An error is returned if the result set is empty.

func (*DB) NamedExec

func (d *DB) NamedExec(ctx context.Context, sql string, arg interface{}) error

func (*DB) Ping

func (d *DB) Ping(ctx context.Context) error

Ping to a database and verify.

func (*DB) Query

func (d *DB) Query(ctx context.Context, sql string, args ...interface{}) ([]*spanner.Row, error)

Query queries the database and returns an *spanner.Row slice. Any placeholder parameters are replaced with supplied args.

func (*DB) QueryX

func (d *DB) QueryX(ctx context.Context, stmt spanner.Statement) ([]*spanner.Row, error)

QueryX queries the database and returns an *spanner.Row slice. Based spanner statement.

func (*DB) Select

func (d *DB) Select(ctx context.Context, dest interface{}, sql string, args ...interface{}) error

Select within a transaction. Any placeholder parameters are replaced with supplied args.

func (*DB) SelectX

func (d *DB) SelectX(ctx context.Context, dest interface{}, stmt spanner.Statement) error

SelectX within a transaction. Based spanner statement.

func (*DB) TxPipeline

func (d *DB) TxPipeline(ctx context.Context, callback func(ctx context.Context) error) error

TxPipeline is ReadWriteTransaction wrap.

type Option

type Option func(*Options) error

func WithClientConfig

func WithClientConfig(s *spanner.ClientConfig) Option

func WithClientOptions

func WithClientOptions(opts ...option.ClientOption) Option

func WithDatabase

func WithDatabase(s string) Option

type Options

type Options struct {
	// contains filtered or unexported fields
}

Directories

Path Synopsis
example
db

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL