Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat(spanner): execute migration (#4221)

p0ny8e8b881ecfc7
diff --git a/plugin/db/spanner/migrate.go b/plugin/db/spanner/migrate.go
index dcdbe50184..65345ef70f 100644
--- a/plugin/db/spanner/migrate.go
+++ b/plugin/db/spanner/migrate.go
@@ -1,14 +1,20 @@
package spanner
import (
+ "bytes"
"context"
"fmt"
"strings"
+ "time"
"cloud.google.com/go/spanner"
"cloud.google.com/go/spanner/admin/database/apiv1/databasepb"
"go.uber.org/zap"
+ "github.com/google/uuid"
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/common"
"github.com/bytebase/bytebase/common/log"
"github.com/bytebase/bytebase/plugin/db"
"github.com/bytebase/bytebase/plugin/db/util"
@@ -52,11 +58,18 @@ func (d *Driver) SetupMigrationIfNeeded(ctx context.Context) error {
zap.String("environment", d.connCtx.EnvironmentID),
zap.String("instance", d.connCtx.InstanceID),
)
- statements := splitStatement(migrationSchema)
+ statements, err := sanitizeSQL(migrationSchema)
+ if err != nil {
+ return err
+ }
+ return d.creataDatabase(ctx, createBytebaseDatabaseStatement, statements)
+}
+
+func (d *Driver) creataDatabase(ctx context.Context, createStatement string, extraStatement []string) error {
op, err := d.dbClient.CreateDatabase(ctx, &databasepb.CreateDatabaseRequest{
Parent: d.config.Host,
- CreateStatement: createBytebaseDatabaseStatement,
- ExtraStatements: statements,
+ CreateStatement: createStatement,
+ ExtraStatements: extraStatement,
})
if err != nil {
return err
@@ -68,8 +81,169 @@ func (d *Driver) SetupMigrationIfNeeded(ctx context.Context) error {
}
// ExecuteMigration executes a migration.
-func (*Driver) ExecuteMigration(_ context.Context, _ *db.MigrationInfo, _ string) (string, string, error) {
- panic("not implemented")
+// ExecuteMigration will execute the database migration.
+// Returns the created migration history id and the updated schema on success.
+func (d *Driver) ExecuteMigration(ctx context.Context, m *db.MigrationInfo, statement string) (migrationHistoryID string, updatedSchema string, resErr error) {
+ var prevSchemaBuf bytes.Buffer
+ // Don't record schema if the database hasn't existed yet or is schemaless (e.g. Mongo).
+ if !m.CreateDatabase {
+ // For baseline migration, we also record the live schema to detect the schema drift.
+ // See https://bytebase.com/blog/what-is-database-schema-drift
+ if _, err := d.Dump(ctx, m.Database, &prevSchemaBuf, true /*schemaOnly*/); err != nil {
+ return "", "", util.FormatError(err)
+ }
+ }
+
+ // Switch to the database where the migration_history table resides.
+ if err := d.switchDatabase(ctx, db.BytebaseDatabase); err != nil {
+ return "", "", err
+ }
+
+ // Phase 1 - Pre-check before executing migration
+ // Phase 2 - Record migration history as PENDING
+ insertedID, err := d.beginMigration(ctx, m, prevSchemaBuf.String(), statement)
+ if err != nil {
+ if common.ErrorCode(err) == common.MigrationAlreadyApplied {
+ return insertedID, prevSchemaBuf.String(), nil
+ }
+ return "", "", errors.Wrapf(err, "failed to begin migration for issue %s", m.IssueID)
+ }
+
+ startedNs := time.Now().UnixNano()
+
+ defer func() {
+ if err := d.endMigration(ctx, startedNs, insertedID, updatedSchema, db.BytebaseDatabase, resErr == nil /*isDone*/); err != nil {
+ log.Error("Failed to update migration history record",
+ zap.Error(err),
+ zap.String("migration_id", migrationHistoryID),
+ )
+ }
+ }()
+
+ // Phase 3 - Executing migration
+ // Branch migration type always has empty sql.
+ // Baseline migration type could has non-empty sql but will not execute.
+ // https://github.com/bytebase/bytebase/issues/394
+ doMigrate := true
+ if statement == "" {
+ doMigrate = false
+ }
+ if m.Type == db.Baseline {
+ doMigrate = false
+ }
+ if doMigrate {
+ // Switch back to the target database.
+ if !m.CreateDatabase {
+ if err := d.switchDatabase(ctx, m.Database); err != nil {
+ return "", "", err
+ }
+ if _, err := d.Execute(ctx, statement, m.CreateDatabase); err != nil {
+ return "", "", util.FormatError(err)
+ }
+ } else {
+ if err := d.creataDatabase(ctx, statement, nil); err != nil {
+ return "", "", err
+ }
+ }
+ }
+
+ // Phase 4 - Dump the schema after migration
+ var afterSchemaBuf bytes.Buffer
+ if _, err := d.Dump(ctx, m.Database, &afterSchemaBuf, true /*schemaOnly*/); err != nil {
+ return "", "", util.FormatError(err)
+ }
+
+ return insertedID, afterSchemaBuf.String(), nil
+}
+
+// BeginMigration checks before executing migration and inserts a migration history record with pending status.
+func (d *Driver) beginMigration(ctx context.Context, m *db.MigrationInfo, prevSchema string, statement string) (insertedID string, err error) {
+ // Convert version to stored version.
+ storedVersion, err := util.ToStoredVersion(m.UseSemanticVersion, m.Version, m.SemanticVersionSuffix)
+ if err != nil {
+ return "", errors.Wrap(err, "failed to convert to stored version")
+ }
+ // Phase 1 - Pre-check before executing migration
+ // Check if the same migration version has already been applied.
+ if list, err := d.FindMigrationHistoryList(ctx, &db.MigrationHistoryFind{
+ Database: &m.Namespace,
+ Version: &m.Version,
+ }); err != nil {
+ return "", errors.Wrap(err, "failed to check duplicate version")
+ } else if len(list) > 0 {
+ migrationHistory := list[0]
+ switch migrationHistory.Status {
+ case db.Done:
+ if migrationHistory.IssueID != m.IssueID {
+ return migrationHistory.ID, common.Errorf(common.MigrationFailed, "database %q has already applied version %s by issue %s", m.Database, m.Version, migrationHistory.IssueID)
+ }
+ return migrationHistory.ID, common.Errorf(common.MigrationAlreadyApplied, "database %q has already applied version %s", m.Database, m.Version)
+ case db.Pending:
+ err := errors.Errorf("database %q version %s migration is already in progress", m.Database, m.Version)
+ log.Debug(err.Error())
+ // For force migration, we will ignore the existing migration history and continue to migration.
+ if m.Force {
+ return migrationHistory.ID, nil
+ }
+ return "", common.Wrap(err, common.MigrationPending)
+ case db.Failed:
+ err := errors.Errorf("database %q version %s migration has failed, please check your database to make sure things are fine and then start a new migration using a new version ", m.Database, m.Version)
+ log.Debug(err.Error())
+ // For force migration, we will ignore the existing migration history and continue to migration.
+ if m.Force {
+ return migrationHistory.ID, nil
+ }
+ return "", common.Wrap(err, common.MigrationFailed)
+ }
+ }
+
+ // Get largestSequence, largestVersionSinceBaseline in a transaction.
+ tx := d.client.ReadOnlyTransaction()
+ defer tx.Close()
+
+ largestSequence, err := d.findLargestSequence(ctx, tx, m.Namespace, false /* baseline */)
+ if err != nil {
+ return "", err
+ }
+
+ // Check if there is any higher version already been applied since the last baseline or branch.
+ if version, err := d.findLargestVersionSinceBaseline(ctx, tx, m.Namespace); err != nil {
+ return "", err
+ } else if version != nil && len(*version) > 0 && *version >= m.Version {
+ // len(*version) > 0 is used because Clickhouse will always return non-nil version with empty string.
+ return "", common.Errorf(common.MigrationOutOfOrder, "database %q has already applied version %s which >= %s", m.Database, *version, m.Version)
+ }
+
+ // Phase 2 - Record migration history as PENDING.
+ // MySQL runs DDL in its own transaction, so we can't commit migration history together with DDL in a single transaction.
+ // Thus we sort of doing a 2-phase commit, where we first write a PENDING migration record, and after migration completes, we then
+ // update the record to DONE together with the updated schema.
+ statementRecord, _ := common.TruncateString(statement, common.MaxSheetSize)
+ if insertedID, err = d.insertPendingHistory(ctx, largestSequence+1, prevSchema, m, storedVersion, statementRecord); err != nil {
+ return "", err
+ }
+
+ return insertedID, nil
+}
+
+// EndMigration updates the migration history record to DONE or FAILED depending on migration is done or not.
+func (d *Driver) endMigration(ctx context.Context, startedNs int64, migrationHistoryID string, updatedSchema string, databaseName string, isDone bool) (err error) {
+ migrationDurationNs := time.Now().UnixNano() - startedNs
+ if err := d.switchDatabase(ctx, databaseName); err != nil {
+ return err
+ }
+
+ if isDone {
+ // Upon success, update the migration history as 'DONE', execution_duration_ns, updated schema.
+ err = d.updateHistoryAsDone(ctx, migrationDurationNs, updatedSchema, migrationHistoryID)
+ } else {
+ // Otherwise, update the migration history as 'FAILED', execution_duration.
+ err = d.updateHistoryAsFailed(ctx, migrationDurationNs, migrationHistoryID)
+ }
+ if err != nil {
+ return err
+ }
+ return nil
}
// FindMigrationHistoryList finds the migration history list.
@@ -186,3 +360,214 @@ func (d *Driver) FindMigrationHistoryList(ctx context.Context, find *db.Migratio
return migrationHistoryList, nil
}
+
+func (d *Driver) findLargestVersionSinceBaseline(ctx context.Context, tx *spanner.ReadOnlyTransaction, namespace string) (*string, error) {
+ largestBaselineSequence, err := d.findLargestSequence(ctx, tx, namespace, true /* baseline */)
+ if err != nil {
+ return nil, err
+ }
+ query := `
+ SELECT
+ MAX(version)
+ FROM migration_history
+ WHERE namespace = @namespace AND sequence >= @sequence
+ `
+ params := map[string]interface{}{
+ "namespace": namespace,
+ "sequence": largestBaselineSequence,
+ }
+ stmt := spanner.Statement{SQL: query, Params: params}
+ iter := tx.Query(ctx, stmt)
+ var versions []spanner.NullString
+ for {
+ row, err := iter.Next()
+ if err == iterator.Done {
+ break
+ }
+ if err != nil {
+ return nil, err
+ }
+ var version spanner.NullString
+ if err := row.Columns(&version); err != nil {
+ return nil, err
+ }
+ versions = append(versions, version)
+ }
+ if len(versions) != 1 {
+ return nil, errors.New("expect to get 1 row")
+ }
+ if versions[0].Valid {
+ version := versions[0].StringVal
+ return &version, nil
+ }
+ return nil, nil
+}
+
+func (*Driver) findLargestSequence(ctx context.Context, tx *spanner.ReadOnlyTransaction, namespace string, baseline bool) (int, error) {
+ query := `
+ SELECT
+ MAX(sequence)
+ FROM migration_history
+ WHERE namespace = @namespace
+ `
+ if baseline {
+ query = fmt.Sprintf("%s AND (type = '%s' OR type = '%s')", query, db.Baseline, db.Branch)
+ }
+ params := map[string]interface{}{"namespace": namespace}
+ stmt := spanner.Statement{SQL: query, Params: params}
+ iter := tx.Query(ctx, stmt)
+ var sequences []spanner.NullInt64
+ for {
+ row, err := iter.Next()
+ if err == iterator.Done {
+ break
+ }
+ if err != nil {
+ return 0, err
+ }
+ var sequence spanner.NullInt64
+ if err := row.Columns(&sequence); err != nil {
+ return 0, err
+ }
+ sequences = append(sequences, sequence)
+ }
+ if len(sequences) != 1 {
+ return 0, errors.New("expect to get 1 row")
+ }
+ if sequences[0].Valid {
+ return int(sequences[0].Int64), nil
+ }
+
+ return 0, nil
+}
+
+func (d *Driver) insertPendingHistory(ctx context.Context, sequence int, prevSchema string, m *db.MigrationInfo, storedVersion, statement string) (string, error) {
+ id := uuid.NewString()
+ query := `
+ INSERT INTO migration_history (
+ id,
+ created_by,
+ created_ts,
+ updated_by,
+ updated_ts,
+ release_version,
+ namespace,
+ sequence,
+ source,
+ type,
+ status,
+ version,
+ description,
+ statement,
+ schema,
+ schema_prev,
+ execution_duration_ns,
+ issue_id,
+ payload
+ )
+ VALUES (
+ @id,
+ @creator,
+ UNIX_SECONDS(CURRENT_TIMESTAMP()),
+ @creator,
+ UNIX_SECONDS(CURRENT_TIMESTAMP()),
+ @release_version,
+ @namespace,
+ @sequence,
+ @source,
+ @type,
+ @status,
+ @version,
+ @description,
+ @statement,
+ @schema,
+ @schema_prev,
+ 0,
+ @issue_id,
+ @payload)
+ `
+ params := map[string]interface{}{
+ "id": id,
+ "creator": m.Creator,
+ "release_version": m.ReleaseVersion,
+ "namespace": m.Namespace,
+ "sequence": sequence,
+ "source": m.Source,
+ "type": m.Type,
+ "status": db.Pending,
+ "version": storedVersion,
+ "description": m.Description,
+ "statement": statement,
+ "schema": prevSchema,
+ "schema_prev": prevSchema,
+ "issue_id": m.IssueID,
+ "payload": m.Payload,
+ }
+ stmt := spanner.Statement{SQL: query, Params: params}
+ if _, err := d.client.ReadWriteTransaction(ctx, func(ctx context.Context, rwt *spanner.ReadWriteTransaction) error {
+ if _, err := rwt.Update(ctx, stmt); err != nil {
+ return err
+ }
+ return nil
+ }); err != nil {
+ return "", err
+ }
+
+ return id, nil
+}
+
+func (d *Driver) updateHistoryAsDone(ctx context.Context, migrationDurationNs int64, updatedSchema string, insertedID string) error {
+ query := `
+ UPDATE
+ migration_history
+ SET
+ status = @status,
+ execution_duration_ns = @execution_duration_ns,
+ schema = @schema
+ WHERE id = @id
+ `
+ params := map[string]interface{}{
+ "status": db.Done,
+ "execution_duration_ns": migrationDurationNs,
+ "schema": updatedSchema,
+ "id": insertedID,
+ }
+ stmt := spanner.Statement{SQL: query, Params: params}
+
+ if _, err := d.client.ReadWriteTransaction(ctx, func(ctx context.Context, rwt *spanner.ReadWriteTransaction) error {
+ if _, err := rwt.Update(ctx, stmt); err != nil {
+ return err
+ }
+ return nil
+ }); err != nil {
+ return err
+ }
+ return nil
+}
+
+func (d *Driver) updateHistoryAsFailed(ctx context.Context, migrationDurationNs int64, insertedID string) error {
+ query := `
+ UPDATE
+ migration_history
+ SET
+ status = @status,
+ execution_duration_ns = @execution_duration_ns
+ WHERE id = @id
+ `
+ params := map[string]interface{}{
+ "status": db.Failed,
+ "execution_duration_ns": migrationDurationNs,
+ "id": insertedID,
+ }
+ stmt := spanner.Statement{SQL: query, Params: params}
+
+ if _, err := d.client.ReadWriteTransaction(ctx, func(ctx context.Context, rwt *spanner.ReadWriteTransaction) error {
+ if _, err := rwt.Update(ctx, stmt); err != nil {
+ return err
+ }
+ return nil
+ }); err != nil {
+ return err
+ }
+ return nil
+}
diff --git a/plugin/db/spanner/spanner.go b/plugin/db/spanner/spanner.go
index 48febc10bb..63bec3bb93 100644
--- a/plugin/db/spanner/spanner.go
+++ b/plugin/db/spanner/spanner.go
@@ -7,10 +7,10 @@ import (
_ "embed"
"fmt"
"regexp"
- "strings"
spanner "cloud.google.com/go/spanner"
spannerdb "cloud.google.com/go/spanner/admin/database/apiv1"
+ adminpb "cloud.google.com/go/spanner/admin/database/apiv1/databasepb"
"go.uber.org/zap"
"github.com/pkg/errors"
@@ -156,12 +156,57 @@ func (*Driver) GetDBConnection(_ context.Context, _ string) (*sql.DB, error) {
}
// Execute executes a SQL statement.
-func (*Driver) Execute(_ context.Context, _ string, _ bool) (int64, error) {
- panic("not implemented")
+func (d *Driver) Execute(ctx context.Context, statement string, createDatabase bool) (int64, error) {
+ if createDatabase {
+ return 0, errors.Errorf("cannot set createDatabase to true")
+ }
+ var rowCount int64
+ stmts, err := sanitizeSQL(statement)
+ if err != nil {
+ return 0, err
+ }
+
+ ddl := func() bool {
+ for _, stmt := range stmts {
+ if isDDL(stmt) {
+ return true
+ }
+ }
+ return false
+ }()
+
+ if ddl {
+ op, err := d.dbClient.UpdateDatabaseDdl(ctx, &adminpb.UpdateDatabaseDdlRequest{
+ Database: getDSN(d.config.Host, d.dbName),
+ Statements: stmts,
+ })
+ if err != nil {
+ return 0, err
+ }
+ return 0, op.Wait(ctx)
+ }
+
+ if _, err := d.client.ReadWriteTransaction(ctx, func(ctx context.Context, rwt *spanner.ReadWriteTransaction) error {
+ spannerStmts := []spanner.Statement{}
+ for _, stmt := range stmts {
+ spannerStmts = append(spannerStmts, spanner.NewStatement(stmt))
+ }
+ counts, err := rwt.BatchUpdate(ctx, spannerStmts)
+ if err != nil {
+ return err
+ }
+ for _, count := range counts {
+ rowCount += count
+ }
+ return nil
+ }); err != nil {
+ return 0, err
+ }
+ return rowCount, nil
}
// Query queries a SQL statement.
-func (*Driver) Query(_ context.Context, _ string, _ *db.QueryContext) ([]interface{}, error) {
+func (*Driver) Query(context.Context, string, *db.QueryContext) ([]interface{}, error) {
panic("not implemented")
}
@@ -183,15 +228,3 @@ func getDatabaseFromDSN(dsn string) (string, error) {
}
return matches["DATABASEGROUP"], nil
}
-
-func splitStatement(statement string) []string {
- var res []string
- for _, s := range strings.Split(statement, ";") {
- trimmed := strings.TrimSpace(s)
- if trimmed == "" {
- continue
- }
- res = append(res, trimmed)
- }
- return res
-}
diff --git a/plugin/db/spanner/spanner_migration_schema.sql b/plugin/db/spanner/spanner_migration_schema.sql
index e4456a1cbf..21adb3df1e 100644
--- a/plugin/db/spanner/spanner_migration_schema.sql
+++ b/plugin/db/spanner/spanner_migration_schema.sql
@@ -1,20 +1,41 @@
+-- This is the bytebase schema to track migration info for Spanner
+-- Create a database called bytebase in the driver.
+-- CREATE DATABASE bytebase;
+
+-- Create migration_history table
CREATE TABLE migration_history (
+ -- id is UUIDv4. See https://cloud.google.com/spanner/docs/schema-design#uuid_primary_key
id STRING(MAX) NOT NULL,
created_by STRING(MAX) NOT NULL,
created_ts INT64 NOT NULL,
updated_by STRING(MAX) NOT NULL,
updated_ts INT64 NOT NULL,
+ -- Record the client version creating this migration history. For Bytebase, we use its binary release version. Different Bytebase release might
+ -- record different history info and this field helps to handle such situation properly. Moreover, it helps debugging.
release_version STRING(MAX) NOT NULL,
+ -- Allows granular tracking of migration history (e.g If an application manages schemas for a multi-tenant service and each tenant has its own schema, that application can use namespace to record the tenant name to track the per-tenant schema migration)
+ -- Since bytebase also manages different application databases from an instance, it leverages this field to track each database migration history.
namespace STRING(MAX) NOT NULL,
+ -- Used to detect out of order migration together with 'namespace' and 'version' column.
sequence INT64 NOT NULL,
CONSTRAINT sequence_is_non_negative CHECK (sequence >= 0),
+ -- We call it source because maybe we could load history from other migration tool.
+ -- Current allowed values are UI, VCS, LIBRARY.
source STRING(MAX) NOT NULL,
+ -- Current allowed values are BASELINE, MIGRATE, MIGRATE_SDL, BRANCH, DATA.
type STRING(MAX) NOT NULL,
+ -- Current allowed values are PENDING, DONE, FAILED.
+ -- We create a "PENDING" record before applying the DDL and update that record to "DONE" after applying the DDL.
status STRING(MAX) NOT NULL,
+ -- Record the migration version.
version STRING(MAX) NOT NULL,
description STRING(MAX) NOT NULL,
+ -- Record the migration statement
statement STRING(MAX) NOT NULL,
+ -- Record the schema after migration
schema STRING(MAX) NOT NULL,
+ -- Record the schema before migration. Though we could also fetch it from the previous migration history, it would complicate fetching logic.
+ -- Besides, by storing the schema_prev, we can perform consistency check to see if the migration history has any gaps.
schema_prev STRING(MAX) NOT NULL,
execution_duration_ns INT64 NOT NULL,
issue_id STRING(MAX) NOT NULL,
@@ -27,4 +48,4 @@ CREATE UNIQUE INDEX bytebase_idx_unique_migration_history_namespace_version ON m
CREATE INDEX bytebase_idx_migration_history_namespace_source_type ON migration_history(namespace, source, type);
-CREATE INDEX bytebase_idx_migration_history_namespace_created ON migration_history(namespace, created_ts);
\ No newline at end of file
+CREATE INDEX bytebase_idx_migration_history_namespace_created ON migration_history(namespace, created_ts);
diff --git a/plugin/db/spanner/statement_parser.go b/plugin/db/spanner/statement_parser.go
new file mode 100644
index 0000000000..2a6812499b
--- /dev/null
+++ b/plugin/db/spanner/statement_parser.go
@@ -0,0 +1,204 @@
+package spanner
+
+import (
+ "strings"
+
+ "cloud.google.com/go/spanner"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/status"
+)
+
+var ddlStatements = map[string]bool{"CREATE": true, "DROP": true, "ALTER": true}
+
+// RemoveCommentsAndTrim removes any comments in the query string and trims any
+// spaces at the beginning and end of the query. This makes checking what type
+// of query a string is a lot easier, as only the first word(s) need to be
+// checked after this has been removed.
+// source: https://github.com/googleapis/go-sql-spanner/blob/e33bd23e1ebfa2fe1b947bced9eacdc6454595eb/statement_parser.go
+func removeCommentsAndTrim(sql string) (string, error) {
+ const singleQuote = '\''
+ const doubleQuote = '"'
+ const backtick = '`'
+ const hyphen = '-'
+ const dash = '#'
+ const slash = '/'
+ const asterisk = '*'
+ isInQuoted := false
+ isInSingleLineComment := false
+ isInMultiLineComment := false
+ var startQuote rune
+ lastCharWasEscapeChar := false
+ isTripleQuoted := false
+ res := strings.Builder{}
+ res.Grow(len(sql))
+ index := 0
+ runes := []rune(sql)
+ for index < len(runes) {
+ c := runes[index]
+ if isInQuoted {
+ if (c == '\n' || c == '\r') && !isTripleQuoted {
+ return "", spanner.ToSpannerError(status.Errorf(codes.InvalidArgument, "statement contains an unclosed literal: %s", sql))
+ } else if c == startQuote {
+ if lastCharWasEscapeChar {
+ lastCharWasEscapeChar = false
+ } else if isTripleQuoted {
+ if len(runes) > index+2 && runes[index+1] == startQuote && runes[index+2] == startQuote {
+ isInQuoted = false
+ startQuote = 0
+ isTripleQuoted = false
+ _, _ = res.WriteRune(c)
+ _, _ = res.WriteRune(c)
+ index += 2
+ }
+ } else {
+ isInQuoted = false
+ startQuote = 0
+ }
+ } else if c == '\\' {
+ lastCharWasEscapeChar = true
+ } else {
+ lastCharWasEscapeChar = false
+ }
+ _, _ = res.WriteRune(c)
+ } else {
+ // We are not in a quoted string.
+ if isInSingleLineComment {
+ if c == '\n' {
+ isInSingleLineComment = false
+ // Include the line feed in the result.
+ _, _ = res.WriteRune(c)
+ }
+ } else if isInMultiLineComment {
+ if len(runes) > index+1 && c == asterisk && runes[index+1] == slash {
+ isInMultiLineComment = false
+ index++
+ }
+ } else {
+ if c == dash || (len(runes) > index+1 && c == hyphen && runes[index+1] == hyphen) {
+ // This is a single line comment.
+ isInSingleLineComment = true
+ } else if len(runes) > index+1 && c == slash && runes[index+1] == asterisk {
+ isInMultiLineComment = true
+ index++
+ } else {
+ if c == singleQuote || c == doubleQuote || c == backtick {
+ isInQuoted = true
+ startQuote = c
+ // Check whether it is a triple-quote.
+ if len(runes) > index+2 && runes[index+1] == startQuote && runes[index+2] == startQuote {
+ isTripleQuoted = true
+ _, _ = res.WriteRune(c)
+ _, _ = res.WriteRune(c)
+ index += 2
+ }
+ }
+ _, _ = res.WriteRune(c)
+ }
+ }
+ }
+ index++
+ }
+ if isInQuoted {
+ return "", spanner.ToSpannerError(status.Errorf(codes.InvalidArgument, "statement contains an unclosed literal: %s", sql))
+ }
+ trimmed := strings.TrimSpace(res.String())
+ if len(trimmed) > 0 && trimmed[len(trimmed)-1] == ';' {
+ return trimmed[:len(trimmed)-1], nil
+ }
+ return trimmed, nil
+}
+
+func splitStatement(sql string) ([]string, error) {
+ var stmts []string
+ const singleQuote = '\''
+ const doubleQuote = '"'
+ const backtick = '`'
+ const delimiter = ';'
+ isInQuoted := false
+ var startQuote rune
+ lastCharWasEscapeChar := false
+ isTripleQuoted := false
+ res := strings.Builder{}
+ res.Grow(len(sql))
+ index := 0
+ runes := []rune(sql)
+ for index < len(runes) {
+ c := runes[index]
+ if isInQuoted {
+ if (c == '\n' || c == '\r') && !isTripleQuoted {
+ return nil, spanner.ToSpannerError(status.Errorf(codes.InvalidArgument, "statement contains an unclosed literal: %s", sql))
+ } else if c == startQuote {
+ if lastCharWasEscapeChar {
+ lastCharWasEscapeChar = false
+ } else if isTripleQuoted {
+ if len(runes) > index+2 && runes[index+1] == startQuote && runes[index+2] == startQuote {
+ isInQuoted = false
+ startQuote = 0
+ isTripleQuoted = false
+ _, _ = res.WriteRune(c)
+ _, _ = res.WriteRune(c)
+ index += 2
+ }
+ } else {
+ isInQuoted = false
+ startQuote = 0
+ }
+ } else if c == '\\' {
+ lastCharWasEscapeChar = true
+ } else {
+ lastCharWasEscapeChar = false
+ }
+ _, _ = res.WriteRune(c)
+ } else {
+ // We are not in a quoted string.
+ if c == singleQuote || c == doubleQuote || c == backtick {
+ isInQuoted = true
+ startQuote = c
+ // Check whether it is a triple-quote.
+ if len(runes) > index+2 && runes[index+1] == startQuote && runes[index+2] == startQuote {
+ isTripleQuoted = true
+ _, _ = res.WriteRune(c)
+ _, _ = res.WriteRune(c)
+ index += 2
+ }
+ _, _ = res.WriteRune(c)
+ } else if c == delimiter {
+ stmts = append(stmts, strings.Trim(res.String(), " \n\t"))
+ res.Reset()
+ res.Grow(len(sql))
+ } else {
+ _, _ = res.WriteRune(c)
+ }
+ }
+ index++
+ }
+ if isInQuoted {
+ return nil, spanner.ToSpannerError(status.Errorf(codes.InvalidArgument, "statement contains an unclosed literal: %s", sql))
+ }
+ if res.Len() > 0 {
+ stmts = append(stmts, strings.Trim(res.String(), " \n\t"))
+ }
+ return stmts, nil
+}
+
+func sanitizeSQL(sql string) ([]string, error) {
+ query, err := removeCommentsAndTrim(sql)
+ if err != nil {
+ return nil, err
+ }
+ stmts, err := splitStatement(query)
+ if err != nil {
+ return nil, err
+ }
+ return stmts, nil
+}
+
+// isDDL returns true if the given sql string is a DDL statement.
+func isDDL(query string) bool {
+ for ddl := range ddlStatements {
+ if strings.EqualFold(query[:len(ddl)], ddl) {
+ return true
+ }
+ }
+ return false
+}
diff --git a/plugin/db/spanner/statement_parser_test.go b/plugin/db/spanner/statement_parser_test.go
new file mode 100644
index 0000000000..c92ca72d31
--- /dev/null
+++ b/plugin/db/spanner/statement_parser_test.go
@@ -0,0 +1,491 @@
+package spanner
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestRemoveCommentsAndTrim(t *testing.T) {
+ tests := []struct {
+ input string
+ want string
+ wantErr bool
+ }{
+ {
+ input: ``,
+ want: ``,
+ },
+ {
+ input: `SELECT 1;`,
+ want: `SELECT 1`,
+ },
+ {
+ input: `-- This is a single line comment
+SELECT 1;`,
+ want: `SELECT 1`,
+ },
+ {
+ input: `# This is a single line comment
+SELECT 1;`,
+ want: `SELECT 1`,
+ },
+ {
+ input: `/* This is a multi line comment on one line */
+SELECT 1;`,
+ want: `SELECT 1`,
+ },
+ {
+ input: `/* This
+is
+a
+multiline
+comment
+*/
+SELECT 1;`,
+ want: `SELECT 1`,
+ },
+ {
+ input: `/* This
+* is
+* a
+* multiline
+* comment
+*/
+SELECT 1;`,
+ want: `SELECT 1`,
+ },
+ {
+ input: `/** This is a javadoc style comment on one line */
+SELECT 1;`,
+ want: `SELECT 1`,
+ },
+ {
+ input: `/** This
+is
+a
+javadoc
+style
+comment
+on
+multiple
+lines
+*/
+SELECT 1;`,
+ want: `SELECT 1`,
+ },
+ {
+ input: `/** This
+* is
+* a
+* javadoc
+* style
+* comment
+* on
+* multiple
+* lines
+*/
+SELECT 1;`,
+ want: `SELECT 1`,
+ },
+ {
+ input: `-- First comment
+SELECT--second comment
+1`,
+ want: `SELECT
+1`,
+ },
+ {
+ input: `# First comment
+SELECT#second comment
+1`,
+ want: `SELECT
+1`,
+ },
+ {
+ input: `-- First comment
+SELECT--second comment
+1--third comment`,
+ want: `SELECT
+1`,
+ },
+ {
+ input: `# First comment
+SELECT#second comment
+1#third comment`,
+ want: `SELECT
+1`,
+ },
+ {
+ input: `/* First comment */
+SELECT/* second comment */
+1`,
+ want: `SELECT
+1`,
+ },
+ {
+ input: `/* First comment */
+SELECT/* second comment */
+1/* third comment */`,
+ want: `SELECT
+1`,
+ },
+ {
+ input: `SELECT "TEST -- This is not a comment"`,
+ want: `SELECT "TEST -- This is not a comment"`,
+ },
+ {
+ input: `-- This is a comment
+SELECT "TEST -- This is not a comment"`,
+ want: `SELECT "TEST -- This is not a comment"`,
+ },
+ {
+ input: `-- This is a comment
+SELECT "TEST -- This is not a comment" -- This is a comment`,
+ want: `SELECT "TEST -- This is not a comment"`,
+ },
+ {
+ input: `SELECT "TEST # This is not a comment"`,
+ want: `SELECT "TEST # This is not a comment"`,
+ },
+ {
+ input: `# This is a comment
+SELECT "TEST # This is not a comment"`,
+ want: `SELECT "TEST # This is not a comment"`,
+ },
+ {
+ input: `# This is a comment
+SELECT "TEST # This is not a comment" # This is a comment`,
+ want: `SELECT "TEST # This is not a comment"`,
+ },
+ {
+ input: `SELECT "TEST /* This is not a comment */"`,
+ want: `SELECT "TEST /* This is not a comment */"`,
+ },
+ {
+ input: `/* This is a comment */
+SELECT "TEST /* This is not a comment */"`,
+ want: `SELECT "TEST /* This is not a comment */"`,
+ },
+ {
+ input: `/* This is a comment */
+SELECT "TEST /* This is not a comment */" /* This is a comment */`,
+ want: `SELECT "TEST /* This is not a comment */"`,
+ },
+ {
+ input: `SELECT 'TEST -- This is not a comment'`,
+ want: `SELECT 'TEST -- This is not a comment'`,
+ },
+ {
+ input: `-- This is a comment
+SELECT 'TEST -- This is not a comment'`,
+ want: `SELECT 'TEST -- This is not a comment'`,
+ },
+ {
+ input: `-- This is a comment
+SELECT 'TEST -- This is not a comment' -- This is a comment`,
+ want: `SELECT 'TEST -- This is not a comment'`,
+ },
+ {
+ input: `SELECT 'TEST # This is not a comment'`,
+ want: `SELECT 'TEST # This is not a comment'`,
+ },
+ {
+ input: `# This is a comment
+SELECT 'TEST # This is not a comment'`,
+ want: `SELECT 'TEST # This is not a comment'`,
+ },
+ {
+ input: `# This is a comment
+SELECT 'TEST # This is not a comment' # This is a comment`,
+ want: `SELECT 'TEST # This is not a comment'`,
+ },
+ {
+ input: `SELECT 'TEST /* This is not a comment */'`,
+ want: `SELECT 'TEST /* This is not a comment */'`,
+ },
+ {
+ input: `/* This is a comment */
+SELECT 'TEST /* This is not a comment */'`,
+ want: `SELECT 'TEST /* This is not a comment */'`,
+ },
+ {
+ input: `/* This is a comment */
+SELECT 'TEST /* This is not a comment */' /* This is a comment */`,
+ want: `SELECT 'TEST /* This is not a comment */'`,
+ },
+ {
+ input: `SELECT '''TEST
+-- This is not a comment
+'''`,
+ want: `SELECT '''TEST
+-- This is not a comment
+'''`,
+ },
+ {
+ input: ` -- This is a comment
+SELECT '''TEST
+-- This is not a comment
+''' -- This is a comment`,
+ want: `SELECT '''TEST
+-- This is not a comment
+'''`,
+ },
+ {
+ input: `SELECT '''TEST
+# This is not a comment
+'''`,
+ want: `SELECT '''TEST
+# This is not a comment
+'''`,
+ },
+ {
+ input: ` # This is a comment
+SELECT '''TEST
+# This is not a comment
+''' # This is a comment`,
+ want: `SELECT '''TEST
+# This is not a comment
+'''`,
+ },
+ {
+ input: `SELECT '''TEST
+/* This is not a comment */
+'''`,
+ want: `SELECT '''TEST
+/* This is not a comment */
+'''`,
+ },
+ {
+ input: ` /* This is a comment */
+SELECT '''TEST
+/* This is not a comment */
+''' /* This is a comment */`,
+ want: `SELECT '''TEST
+/* This is not a comment */
+'''`,
+ },
+ {
+ input: `SELECT """TEST
+-- This is not a comment
+"""`,
+ want: `SELECT """TEST
+-- This is not a comment
+"""`,
+ },
+ {
+ input: ` -- This is a comment
+SELECT """TEST
+-- This is not a comment
+""" -- This is a comment`,
+ want: `SELECT """TEST
+-- This is not a comment
+"""`,
+ },
+ {
+ input: `SELECT """TEST
+# This is not a comment
+"""`,
+ want: `SELECT """TEST
+# This is not a comment
+"""`,
+ },
+ {
+ input: ` # This is a comment
+SELECT """TEST
+# This is not a comment
+""" # This is a comment`,
+ want: `SELECT """TEST
+# This is not a comment
+"""`,
+ },
+ {
+ input: `SELECT """TEST
+/* This is not a comment */
+"""`,
+ want: `SELECT """TEST
+/* This is not a comment */
+"""`,
+ },
+ {
+ input: ` /* This is a comment */
+SELECT """TEST
+/* This is not a comment */
+""" /* This is a comment */`,
+ want: `SELECT """TEST
+/* This is not a comment */
+"""`,
+ },
+ {
+ input: `/* This is a comment /* this is still a comment */
+SELECT 1`,
+ want: `SELECT 1`,
+ },
+ {
+ input: `/** This is a javadoc style comment /* this is still a comment */
+SELECT 1`,
+ want: `SELECT 1`,
+ },
+ {
+ input: `/** This is a javadoc style comment /** this is still a comment */
+SELECT 1`,
+ want: `SELECT 1`,
+ },
+ {
+ input: `/** This is a javadoc style comment /** this is still a comment **/
+SELECT 1`,
+ want: `SELECT 1`,
+ },
+ }
+ a := require.New(t)
+ for _, tc := range tests {
+ got, err := removeCommentsAndTrim(tc.input)
+ if tc.wantErr {
+ a.Error(err)
+ } else {
+ a.NoError(err)
+ }
+ a.Equal(tc.want, got)
+ }
+}
+
+func TestSanitizeQuery(t *testing.T) {
+ tests := []struct {
+ input string
+ want []string
+ wantErr bool
+ }{
+ {
+ input: `
+ --- 123456
+ SELECT 1;
+ --- 6312
+ SELECT 2;
+ ---123
+ ---123
+ /* 213123 */
+ SELECT 3;
+ `,
+ want: []string{
+ "SELECT 1", "SELECT 2", "SELECT 3",
+ },
+ },
+ {
+ input: `
+-- This is the bytebase schema to track migration info for Spanner
+-- Create a database called bytebase in the driver.
+-- CREATE DATABASE bytebase;
+
+-- Create migration_history table
+CREATE TABLE migration_history (
+ -- id is UUIDv4.
+ id STRING(MAX) NOT NULL,
+ created_by STRING(MAX) NOT NULL,
+ created_ts INT64 NOT NULL,
+ updated_by STRING(MAX) NOT NULL,
+ updated_ts INT64 NOT NULL,
+ -- Record the client version creating this migration history. For Bytebase, we use its binary release version. Different Bytebase release might
+ -- record different history info and this field helps to handle such situation properly. Moreover, it helps debugging.
+ release_version STRING(MAX) NOT NULL,
+ -- Allows granular tracking of migration history (e.g If an application manages schemas for a multi-tenant service and each tenant has its own schema, that application can use namespace to record the tenant name to track the per-tenant schema migration)
+ -- Since bytebase also manages different application databases from an instance, it leverages this field to track each database migration history.
+ namespace STRING(MAX) NOT NULL,
+ -- Used to detect out of order migration together with 'namespace' and 'version' column.
+ sequence INT64 NOT NULL,
+ CONSTRAINT sequence_is_non_negative CHECK (sequence >= 0),
+ -- We call it source because maybe we could load history from other migration tool.
+ -- Current allowed values are UI, VCS, LIBRARY.
+ source STRING(MAX) NOT NULL,
+ -- Current allowed values are BASELINE, MIGRATE, MIGRATE_SDL, BRANCH, DATA.
+ type STRING(MAX) NOT NULL,
+ -- Current allowed values are PENDING, DONE, FAILED.
+ -- We create a "PENDING" record before applying the DDL and update that record to "DONE" after applying the DDL.
+ status STRING(MAX) NOT NULL,
+ -- Record the migration version.
+ version STRING(MAX) NOT NULL,
+ description STRING(MAX) NOT NULL,
+ -- Record the migration statement
+ statement STRING(MAX) NOT NULL,
+ -- Record the schema after migration
+ schema STRING(MAX) NOT NULL,
+ -- Record the schema before migration. Though we could also fetch it from the previous migration history, it would complicate fetching logic.
+ -- Besides, by storing the schema_prev, we can perform consistency check to see if the migration history has any gaps.
+ schema_prev STRING(MAX) NOT NULL,
+ execution_duration_ns INT64 NOT NULL,
+ issue_id STRING(MAX) NOT NULL,
+ payload STRING(MAX) NOT NULL
+) PRIMARY KEY(id);
+
+CREATE UNIQUE INDEX bytebase_idx_unique_migration_history_namespace_sequence ON migration_history (namespace, sequence);
+
+CREATE UNIQUE INDEX bytebase_idx_unique_migration_history_namespace_version ON migration_history (namespace, version);
+
+CREATE INDEX bytebase_idx_migration_history_namespace_source_type ON migration_history(namespace, source, type);
+
+CREATE INDEX bytebase_idx_migration_history_namespace_created ON migration_history(namespace, created_ts);
+ `,
+ want: []string{
+ `CREATE TABLE migration_history (
+
+ id STRING(MAX) NOT NULL,
+ created_by STRING(MAX) NOT NULL,
+ created_ts INT64 NOT NULL,
+ updated_by STRING(MAX) NOT NULL,
+ updated_ts INT64 NOT NULL,
+
+
+ release_version STRING(MAX) NOT NULL,
+
+
+ namespace STRING(MAX) NOT NULL,
+
+ sequence INT64 NOT NULL,
+ CONSTRAINT sequence_is_non_negative CHECK (sequence >= 0),
+
+
+ source STRING(MAX) NOT NULL,
+
+ type STRING(MAX) NOT NULL,
+
+
+ status STRING(MAX) NOT NULL,
+
+ version STRING(MAX) NOT NULL,
+ description STRING(MAX) NOT NULL,
+
+ statement STRING(MAX) NOT NULL,
+
+ schema STRING(MAX) NOT NULL,
+
+
+ schema_prev STRING(MAX) NOT NULL,
+ execution_duration_ns INT64 NOT NULL,
+ issue_id STRING(MAX) NOT NULL,
+ payload STRING(MAX) NOT NULL
+) PRIMARY KEY(id)`,
+ "CREATE UNIQUE INDEX bytebase_idx_unique_migration_history_namespace_sequence ON migration_history (namespace, sequence)",
+ "CREATE UNIQUE INDEX bytebase_idx_unique_migration_history_namespace_version ON migration_history (namespace, version)",
+ "CREATE INDEX bytebase_idx_migration_history_namespace_source_type ON migration_history(namespace, source, type)",
+ "CREATE INDEX bytebase_idx_migration_history_namespace_created ON migration_history(namespace, created_ts)",
+ },
+ },
+ {
+ input: `
+ SELECT 1;
+ SELECT '2;3;4;';
+ SELECT 2;
+ `,
+ want: []string{"SELECT 1", "SELECT '2;3;4;'", "SELECT 2"},
+ },
+ }
+ a := require.New(t)
+ for _, tc := range tests {
+ got, err := sanitizeSQL(tc.input)
+ if tc.wantErr {
+ a.Error(err)
+ } else {
+ a.NoError(err)
+ }
+ a.Equal(tc.want, got)
+ }
+}
diff --git a/server/issue.go b/server/issue.go
index 3df4228e94..eef04e636e 100644
--- a/server/issue.go
+++ b/server/issue.go
@@ -1251,6 +1251,8 @@ func getCreateDatabaseStatement(dbType db.Type, createDatabaseContext api.Create
// mongodb statement in mongosh with --file flag, and it doesn't support `use <database>` statement in the file.
// And we pass the database name to Bytebase engine driver, which will be used to build the connection string.
return fmt.Sprintf(`db.createCollection("%s");`, createDatabaseContext.TableName), nil
+ case db.Spanner:
+ return fmt.Sprintf("CREATE DATABASE %s", databaseName), nil
}
return "", errors.Errorf("unsupported database type %s", dbType)
}
@@ -1306,6 +1308,14 @@ func createGhostTaskList(database *store.DatabaseMessage, instance *store.Instan
// checkCharacterSetCollationOwner checks if the character set, collation and owner are legal according to the dbType.
func checkCharacterSetCollationOwner(dbType db.Type, characterSet, collation, owner string) error {
switch dbType {
+ case db.Spanner:
+ // Spanner does not support character set and collation at the database level.
+ if characterSet != "" {
+ return errors.Errorf("Spanner does not support character set, but got %s", characterSet)
+ }
+ if collation != "" {
+ return errors.Errorf("Spanner does not support collation, but got %s", collation)
+ }
case db.ClickHouse:
// ClickHouse does not support character set and collation at the database level.
if characterSet != "" {