Skip to content

Commit

Permalink
[db_schema] Adjust schema migration to support v.22+ of cockroachdb
Browse files Browse the repository at this point in the history
  • Loading branch information
barroco committed Aug 25, 2024
1 parent 915d45b commit bd7dbcb
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
15 changes: 14 additions & 1 deletion cmds/db-manager/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,12 @@ func main() {
crdb.Pool.Close()
}()

crdbVersion, err := crdb.GetServerVersion()
if err != nil {
log.Panicf("Unable to retrieve the version of the server %s:%d: %v", connectParameters.Host, connectParameters.Port, err)
}
log.Printf("CRDB server version: %s", crdbVersion)

// Make sure specified database exists
exists, err := doesDatabaseExist(crdb, dbName)
if err != nil {
Expand Down Expand Up @@ -144,7 +150,14 @@ func main() {
if err != nil {
log.Panicf("Failed to load SQL content from %s: %v", fullFilePath, err)
}
migrationSQL := fmt.Sprintf("USE %s;\n", dbName) + string(rawMigrationSQL)

// Ensure SQL session has implicit transactions disabled for CRDB versions 22.2+
sessionConfigurationSQL := ""
if crdbVersion.Compare(*semver.New("22.2.0")) >= 0 {
sessionConfigurationSQL = "SET enable_implicit_transaction_for_batch_statements = false;\n"
}

migrationSQL := sessionConfigurationSQL + fmt.Sprintf("USE %s;\n", dbName) + string(rawMigrationSQL)

// Execute migration step
if _, err := crdb.Pool.Exec(context.Background(), migrationSQL); err != nil {
Expand Down
16 changes: 16 additions & 0 deletions pkg/cockroach/cockroach.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package cockroach
import (
"context"
"fmt"
"regexp"
"sort"
"strconv"
"strings"
Expand Down Expand Up @@ -219,3 +220,18 @@ func (db *DB) GetVersion(ctx context.Context, dbName string) (*semver.Version, e

return semver.NewVersion(dbVersion)
}

func (db *DB) GetServerVersion() (*semver.Version, error) {
const versionDbQuery = `
SELECT version();
`
var fullVersion string
err := db.Pool.QueryRow(context.Background(), versionDbQuery).Scan(&fullVersion)
if err != nil {
return nil, stacktrace.Propagate(err, "Error querying CRDB server version")
}

re := regexp.MustCompile(`v((0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*))`)
match := re.FindStringSubmatch(fullVersion)
return semver.New(match[1]), nil
}

0 comments on commit bd7dbcb

Please sign in to comment.