2017-06-04 20:13:49 +00:00
|
|
|
package spanner
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"io/ioutil"
|
|
|
|
"log"
|
|
|
|
nurl "net/url"
|
|
|
|
"regexp"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"golang.org/x/net/context"
|
|
|
|
|
|
|
|
"cloud.google.com/go/spanner"
|
2017-06-04 20:53:33 +00:00
|
|
|
sdb "cloud.google.com/go/spanner/admin/database/apiv1"
|
2017-06-04 20:13:49 +00:00
|
|
|
|
2018-10-10 22:11:48 +00:00
|
|
|
"github.com/golang-migrate/migrate/v4"
|
|
|
|
"github.com/golang-migrate/migrate/v4/database"
|
2017-06-04 20:13:49 +00:00
|
|
|
|
2019-02-26 23:56:57 +00:00
|
|
|
"github.com/hashicorp/go-multierror"
|
2017-06-04 20:13:49 +00:00
|
|
|
"google.golang.org/api/iterator"
|
|
|
|
adminpb "google.golang.org/genproto/googleapis/spanner/admin/database/v1"
|
|
|
|
)
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
db := Spanner{}
|
2017-06-04 20:53:33 +00:00
|
|
|
database.Register("spanner", &db)
|
2017-06-04 20:13:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// DefaultMigrationsTable is used if no custom table is specified
|
|
|
|
const DefaultMigrationsTable = "SchemaMigrations"
|
|
|
|
|
|
|
|
// Driver errors
|
|
|
|
var (
|
|
|
|
ErrNilConfig = fmt.Errorf("no config")
|
|
|
|
ErrNoDatabaseName = fmt.Errorf("no database name")
|
|
|
|
ErrNoSchema = fmt.Errorf("no schema")
|
|
|
|
ErrDatabaseDirty = fmt.Errorf("database is dirty")
|
|
|
|
)
|
|
|
|
|
|
|
|
// Config used for a Spanner instance
|
|
|
|
type Config struct {
|
|
|
|
MigrationsTable string
|
|
|
|
DatabaseName string
|
|
|
|
}
|
|
|
|
|
|
|
|
// Spanner implements database.Driver for Google Cloud Spanner
|
|
|
|
type Spanner struct {
|
2017-06-04 20:53:33 +00:00
|
|
|
db *DB
|
2017-06-04 20:13:49 +00:00
|
|
|
|
|
|
|
config *Config
|
|
|
|
}
|
|
|
|
|
2017-06-04 20:53:33 +00:00
|
|
|
type DB struct {
|
|
|
|
admin *sdb.DatabaseAdminClient
|
|
|
|
data *spanner.Client
|
|
|
|
}
|
|
|
|
|
2018-10-28 13:00:05 +00:00
|
|
|
func NewDB(admin sdb.DatabaseAdminClient, data spanner.Client) *DB {
|
|
|
|
return &DB{
|
|
|
|
admin: &admin,
|
|
|
|
data: &data,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-06-04 20:53:33 +00:00
|
|
|
// WithInstance implements database.Driver
|
|
|
|
func WithInstance(instance *DB, config *Config) (database.Driver, error) {
|
|
|
|
if config == nil {
|
|
|
|
return nil, ErrNilConfig
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(config.DatabaseName) == 0 {
|
|
|
|
return nil, ErrNoDatabaseName
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(config.MigrationsTable) == 0 {
|
|
|
|
config.MigrationsTable = DefaultMigrationsTable
|
|
|
|
}
|
|
|
|
|
|
|
|
sx := &Spanner{
|
|
|
|
db: instance,
|
|
|
|
config: config,
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := sx.ensureVersionTable(); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return sx, nil
|
|
|
|
}
|
|
|
|
|
2017-06-04 20:13:49 +00:00
|
|
|
// Open implements database.Driver
|
2017-06-04 20:53:33 +00:00
|
|
|
func (s *Spanner) Open(url string) (database.Driver, error) {
|
2017-06-04 20:13:49 +00:00
|
|
|
purl, err := nurl.Parse(url)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
ctx := context.Background()
|
2017-06-04 20:53:33 +00:00
|
|
|
|
|
|
|
adminClient, err := sdb.NewDatabaseAdminClient(ctx)
|
2017-06-04 20:13:49 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2017-06-04 20:53:33 +00:00
|
|
|
dbname := strings.Replace(migrate.FilterCustomQuery(purl).String(), "spanner://", "", 1)
|
2017-06-04 20:13:49 +00:00
|
|
|
dataClient, err := spanner.NewClient(ctx, dbname)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
migrationsTable := purl.Query().Get("x-migrations-table")
|
|
|
|
|
2017-06-04 20:53:33 +00:00
|
|
|
db := &DB{admin: adminClient, data: dataClient}
|
|
|
|
return WithInstance(db, &Config{
|
|
|
|
DatabaseName: dbname,
|
|
|
|
MigrationsTable: migrationsTable,
|
|
|
|
})
|
2017-06-04 20:13:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Close implements database.Driver
|
|
|
|
func (s *Spanner) Close() error {
|
2017-06-04 20:53:33 +00:00
|
|
|
s.db.data.Close()
|
|
|
|
return s.db.admin.Close()
|
2017-06-04 20:13:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Lock implements database.Driver but doesn't do anything because Spanner only
|
|
|
|
// enqueues the UpdateDatabaseDdlRequest.
|
|
|
|
func (s *Spanner) Lock() error {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Unlock implements database.Driver but no action required, see Lock.
|
|
|
|
func (s *Spanner) Unlock() error {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Run implements database.Driver
|
|
|
|
func (s *Spanner) Run(migration io.Reader) error {
|
|
|
|
migr, err := ioutil.ReadAll(migration)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// run migration
|
2017-09-18 19:47:29 +00:00
|
|
|
stmts := migrationStatements(migr)
|
2017-06-04 20:13:49 +00:00
|
|
|
ctx := context.Background()
|
|
|
|
|
2017-06-04 20:53:33 +00:00
|
|
|
op, err := s.db.admin.UpdateDatabaseDdl(ctx, &adminpb.UpdateDatabaseDdlRequest{
|
2017-06-04 20:13:49 +00:00
|
|
|
Database: s.config.DatabaseName,
|
2017-09-18 19:47:29 +00:00
|
|
|
Statements: stmts,
|
2017-06-04 20:13:49 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
if err != nil {
|
2017-06-04 20:53:33 +00:00
|
|
|
return &database.Error{OrigErr: err, Err: "migration failed", Query: migr}
|
2017-06-04 20:13:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if err := op.Wait(ctx); err != nil {
|
2017-06-04 20:53:33 +00:00
|
|
|
return &database.Error{OrigErr: err, Err: "migration failed", Query: migr}
|
2017-06-04 20:13:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// SetVersion implements database.Driver
|
|
|
|
func (s *Spanner) SetVersion(version int, dirty bool) error {
|
|
|
|
ctx := context.Background()
|
|
|
|
|
2017-06-04 20:53:33 +00:00
|
|
|
_, err := s.db.data.ReadWriteTransaction(ctx,
|
2017-06-04 20:13:49 +00:00
|
|
|
func(ctx context.Context, txn *spanner.ReadWriteTransaction) error {
|
|
|
|
m := []*spanner.Mutation{
|
|
|
|
spanner.Delete(s.config.MigrationsTable, spanner.AllKeys()),
|
|
|
|
spanner.Insert(s.config.MigrationsTable,
|
|
|
|
[]string{"Version", "Dirty"},
|
|
|
|
[]interface{}{version, dirty},
|
|
|
|
)}
|
|
|
|
return txn.BufferWrite(m)
|
|
|
|
})
|
|
|
|
if err != nil {
|
2017-06-04 20:53:33 +00:00
|
|
|
return &database.Error{OrigErr: err}
|
2017-06-04 20:13:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Version implements database.Driver
|
|
|
|
func (s *Spanner) Version() (version int, dirty bool, err error) {
|
|
|
|
ctx := context.Background()
|
|
|
|
|
|
|
|
stmt := spanner.Statement{
|
|
|
|
SQL: `SELECT Version, Dirty FROM ` + s.config.MigrationsTable + ` LIMIT 1`,
|
|
|
|
}
|
2017-06-04 20:53:33 +00:00
|
|
|
iter := s.db.data.Single().Query(ctx, stmt)
|
2017-06-04 20:13:49 +00:00
|
|
|
defer iter.Stop()
|
|
|
|
|
|
|
|
row, err := iter.Next()
|
|
|
|
switch err {
|
|
|
|
case iterator.Done:
|
2017-06-04 20:53:33 +00:00
|
|
|
return database.NilVersion, false, nil
|
2017-06-04 20:13:49 +00:00
|
|
|
case nil:
|
|
|
|
var v int64
|
|
|
|
if err = row.Columns(&v, &dirty); err != nil {
|
2017-06-04 20:53:33 +00:00
|
|
|
return 0, false, &database.Error{OrigErr: err, Query: []byte(stmt.SQL)}
|
2017-06-04 20:13:49 +00:00
|
|
|
}
|
|
|
|
version = int(v)
|
|
|
|
default:
|
2017-06-04 20:53:33 +00:00
|
|
|
return 0, false, &database.Error{OrigErr: err, Query: []byte(stmt.SQL)}
|
2017-06-04 20:13:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return version, dirty, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Drop implements database.Driver. Retrieves the database schema first and
|
|
|
|
// creates statements to drop the indexes and tables accordingly.
|
|
|
|
// Note: The drop statements are created in reverse order to how they're
|
|
|
|
// provided in the schema. Assuming the schema describes how the database can
|
|
|
|
// be "build up", it seems logical to "unbuild" the database simply by going the
|
|
|
|
// opposite direction. More testing
|
|
|
|
func (s *Spanner) Drop() error {
|
|
|
|
ctx := context.Background()
|
2017-06-04 20:53:33 +00:00
|
|
|
res, err := s.db.admin.GetDatabaseDdl(ctx, &adminpb.GetDatabaseDdlRequest{
|
2017-06-04 20:13:49 +00:00
|
|
|
Database: s.config.DatabaseName,
|
|
|
|
})
|
|
|
|
if err != nil {
|
2017-06-04 20:53:33 +00:00
|
|
|
return &database.Error{OrigErr: err, Err: "drop failed"}
|
2017-06-04 20:13:49 +00:00
|
|
|
}
|
|
|
|
if len(res.Statements) == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
r := regexp.MustCompile(`(CREATE TABLE\s(\S+)\s)|(CREATE.+INDEX\s(\S+)\s)`)
|
|
|
|
stmts := make([]string, 0)
|
|
|
|
for i := len(res.Statements) - 1; i >= 0; i-- {
|
|
|
|
s := res.Statements[i]
|
|
|
|
m := r.FindSubmatch([]byte(s))
|
|
|
|
|
|
|
|
if len(m) == 0 {
|
|
|
|
continue
|
|
|
|
} else if tbl := m[2]; len(tbl) > 0 {
|
|
|
|
stmts = append(stmts, fmt.Sprintf(`DROP TABLE %s`, tbl))
|
|
|
|
} else if idx := m[4]; len(idx) > 0 {
|
|
|
|
stmts = append(stmts, fmt.Sprintf(`DROP INDEX %s`, idx))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-06-04 20:53:33 +00:00
|
|
|
op, err := s.db.admin.UpdateDatabaseDdl(ctx, &adminpb.UpdateDatabaseDdlRequest{
|
2017-06-04 20:13:49 +00:00
|
|
|
Database: s.config.DatabaseName,
|
|
|
|
Statements: stmts,
|
|
|
|
})
|
|
|
|
if err != nil {
|
2017-06-04 20:53:33 +00:00
|
|
|
return &database.Error{OrigErr: err, Query: []byte(strings.Join(stmts, "; "))}
|
2017-06-04 20:13:49 +00:00
|
|
|
}
|
|
|
|
if err := op.Wait(ctx); err != nil {
|
2017-06-04 20:53:33 +00:00
|
|
|
return &database.Error{OrigErr: err, Query: []byte(strings.Join(stmts, "; "))}
|
2017-06-04 20:13:49 +00:00
|
|
|
}
|
|
|
|
|
2019-02-26 23:56:57 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// ensureVersionTable checks if versions table exists and, if not, creates it.
|
|
|
|
// Note that this function locks the database, which deviates from the usual
|
|
|
|
// convention of "caller locks" in the Spanner type.
|
|
|
|
func (s *Spanner) ensureVersionTable() (err error) {
|
|
|
|
if err = s.Lock(); err != nil {
|
2017-06-04 20:13:49 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2019-02-26 23:56:57 +00:00
|
|
|
defer func() {
|
|
|
|
if e := s.Unlock(); e != nil {
|
|
|
|
if err == nil {
|
|
|
|
err = e
|
|
|
|
} else {
|
|
|
|
err = multierror.Append(err, e)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
2017-06-04 20:13:49 +00:00
|
|
|
|
|
|
|
ctx := context.Background()
|
|
|
|
tbl := s.config.MigrationsTable
|
2017-06-24 08:46:57 +00:00
|
|
|
iter := s.db.data.Single().Read(ctx, tbl, spanner.AllKeys(), []string{"Version"})
|
2017-06-04 20:13:49 +00:00
|
|
|
if err := iter.Do(func(r *spanner.Row) error { return nil }); err == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
stmt := fmt.Sprintf(`CREATE TABLE %s (
|
|
|
|
Version INT64 NOT NULL,
|
|
|
|
Dirty BOOL NOT NULL
|
|
|
|
) PRIMARY KEY(Version)`, tbl)
|
|
|
|
|
2017-06-04 20:53:33 +00:00
|
|
|
op, err := s.db.admin.UpdateDatabaseDdl(ctx, &adminpb.UpdateDatabaseDdlRequest{
|
2017-06-04 20:13:49 +00:00
|
|
|
Database: s.config.DatabaseName,
|
|
|
|
Statements: []string{stmt},
|
|
|
|
})
|
|
|
|
|
|
|
|
if err != nil {
|
2017-06-04 20:53:33 +00:00
|
|
|
return &database.Error{OrigErr: err, Query: []byte(stmt)}
|
2017-06-04 20:13:49 +00:00
|
|
|
}
|
|
|
|
if err := op.Wait(ctx); err != nil {
|
2017-06-04 20:53:33 +00:00
|
|
|
return &database.Error{OrigErr: err, Query: []byte(stmt)}
|
2017-06-04 20:13:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
2017-09-18 19:47:29 +00:00
|
|
|
|
|
|
|
func migrationStatements(migration []byte) []string {
|
|
|
|
regex := regexp.MustCompile(";$")
|
|
|
|
migrationString := string(migration[:])
|
|
|
|
migrationString = strings.TrimSpace(migrationString)
|
|
|
|
migrationString = regex.ReplaceAllString(migrationString, "")
|
|
|
|
|
|
|
|
statements := strings.Split(migrationString, ";")
|
|
|
|
return statements
|
|
|
|
}
|