MSP-8976 Up deps

This commit is contained in:
Иван Перлов committed 2026-11-20 17:19:44 +03:00
1 parent b8ef777339
commit 11d705124d
603 files changed
+47715 -13202

No files matched your search

+27
View File
@@ -35,3 +35,30 @@ snapshot:
version_template: "{{ incpatch .Version }}-next"
changelog:
use: github-native
dockers_v2:
- images:
- ghcr.io/pressly/goose
dockerfile: goreleaser.Dockerfile
platforms:
- linux/amd64
- linux/arm64
# Prereleases only get the exact tag, for example v3.30.0-rc1.
tags:
- "{{ .Tag }}"
- "{{ if not .Prerelease }}v{{ .Major }}.{{ .Minor }}{{ end }}"
- "{{ if not .Prerelease }}v{{ .Major }}{{ end }}"
- "{{ if not .Prerelease }}latest{{ end }}"
labels:
org.opencontainers.image.title: goose
org.opencontainers.image.description: "Database migration tool"
org.opencontainers.image.source: https://github.com/pressly/goose
org.opencontainers.image.url: https://pressly.github.io/goose
org.opencontainers.image.licenses: MIT
org.opencontainers.image.version: "{{ .Tag }}"
org.opencontainers.image.revision: "{{ .FullCommit }}"
org.opencontainers.image.created: "{{ .Date }}"
# GHCR reads these from the image index of a multi-platform image.
annotations:
org.opencontainers.image.description: "Database migration tool"
org.opencontainers.image.source: https://github.com/pressly/goose
org.opencontainers.image.licenses: MIT
+82 -1
View File
@@ -7,6 +7,83 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
## [v3.30.1] - 2026-11-12
### Changed
- `+goose ENVSUB ON`: support more shell expansions, such as `${VAR:?message}`, `${VAR:+word}`,
and `${#VAR}`. A `$` that does not start a variable name, such as `$1`, is now kept as-is
instead of an error (#1174)
### Fixed
- Build failure when `github.com/mfridman/interpolate` is upgraded to v0.2.0, for example with
`go get -u` (#1176)
- Lock: fix an edge case where a long-lived locker could stop waiting for a held lock and fail
immediately. Programs that migrate once at startup were not affected (#1173)
## [v3.30.0] - 2026-11-10
### Added
- Container image at `ghcr.io/pressly/goose` for `linux/amd64` and `linux/arm64`, published on
each release. The image is based on distroless static, runs as a nonroot user, and supports
`.sql` migrations only (#1093)
### Changed
- Various dependency upgrades
- SQL parser: reduce memory use when parsing migration files, and make parsing much faster when
the race detector is on (#1155, #1156)
### Fixed
- CLI: `goose validate` failed on Go migrations that register an inlined function (#1110)
- Provider: SQL-only migrations with unpadded versions (`1_`, `2_`, `10_`) were sorted by
filename instead of version. This affected `ListSources` and `GetVersions`, as well as `Up`
when versioning was disabled (#1124)
## [v3.29.0] - 2026-10-11
### Added
- Support [environ credentials](https://github.com/ydb-platform/ydb-go-sdk-auth-environ#auth-environment-variables)
for YDB using connection string parameter `use_env_credentials`.
### Changed
- Various dependency upgrades
## [v3.28.0] - 2026-09-02
### Added
- CLI: `azuresql` driver for Azure SQL with Microsoft Entra ID (Azure AD) authentication via
`fedauth` connection string parameters, e.g.
`goose azuresql "sqlserver://host?database=mydb&fedauth=ActiveDirectoryDefault" status`.
Excluded when building with the `no_mssql` or `no_azuresql` tags (#1109)
- MySQL/MariaDB table-based `Locker` via `lock.NewMySQLTableLocker`, the MySQL counterpart to the
Postgres table locker from #993, accepting the same `TableLockerOption` set (#1075)
### Changed
- **Minimum Go version is now 1.26**
- ClickHouse: new `goose_db_version` tables are created with `ORDER BY (version_id)` instead of
`ORDER BY (date)`. Existing tables are unchanged (#1085)
- MySQL/TiDB: the `tstamp` column is now `DATETIME` instead of `TIMESTAMP`, which is capped at
2038-01-19 (#1053). Only newly created tables are affected; existing tables can be updated with:
```sql
ALTER TABLE goose_db_version MODIFY tstamp datetime NULL DEFAULT CURRENT_TIMESTAMP;
```
- Various dependency upgrades
### Fixed
- `goose create` returns a clear "file exists" error, including the path, instead of `%!w(<nil>)`
when the migration file already exists (#1104)
## [v3.27.3] - 2026-07-22
### Changed
@@ -325,7 +402,11 @@ Here's a quick summary:
- Add new `context.Context`-aware functions and methods, for both sql and go migrations.
- Return error when no migration files found or dir is not a directory.
[Unreleased]: https://github.com/pressly/goose/compare/v3.27.3...HEAD
[Unreleased]: https://github.com/pressly/goose/compare/v3.30.1...HEAD
[v3.30.1]: https://github.com/pressly/goose/compare/v3.30.0...v3.30.1
[v3.30.0]: https://github.com/pressly/goose/compare/v3.29.0...v3.30.0
[v3.29.0]: https://github.com/pressly/goose/compare/v3.28.0...v3.29.0
[v3.28.0]: https://github.com/pressly/goose/compare/v3.27.3...v3.28.0
[v3.27.3]: https://github.com/pressly/goose/compare/v3.27.2...v3.27.3
[v3.27.2]: https://github.com/pressly/goose/compare/v3.27.1...v3.27.2
[v3.27.1]: https://github.com/pressly/goose/compare/v3.27.0...v3.27.1
+4
View File
@@ -89,6 +89,10 @@ test-clickhouse: add-gowork
go test $(GO_TEST_FLAGS) ./internal/testing/integration -run='(TestClickhouse|TestClickhouseRemote)' |\
tparse --follow -sort=elapsed
test-mysql-long: add-gowork test-mysql
go test $(GO_TEST_FLAGS) ./internal/testing/integration/locking -run='TestMySQL' |\
tparse --follow -sort=elapsed
test-mysql: add-gowork
go test $(GO_TEST_FLAGS) ./internal/testing/integration -run='TestMySQL' | tparse --follow -sort=elapsed
+49 -13
View File
@@ -6,8 +6,6 @@
CI](https://github.com/pressly/goose/actions/workflows/ci.yaml/badge.svg)](https://github.com/pressly/goose/actions/workflows/ci.yaml)
[![Go
Reference](https://pkg.go.dev/badge/github.com/pressly/goose/v3.svg)](https://pkg.go.dev/github.com/pressly/goose/v3)
[![Go Report
Card](https://goreportcard.com/badge/github.com/pressly/goose/v3)](https://goreportcard.com/report/github.com/pressly/goose/v3)
Goose is a database migration tool. Both a CLI and a library.
@@ -39,8 +37,11 @@ Binary too big? Build a lite version by excluding the drivers you don't need:
go build -tags='no_postgres no_mysql no_sqlite3 no_ydb' -o goose ./cmd/goose
# Available build tags:
# no_clickhouse no_libsql no_mssql no_mysql
# no_postgres no_sqlite3 no_vertica no_ydb
# no_azuresql no_clickhouse no_libsql no_mssql
# no_mysql no_postgres no_sqlite3 no_vertica
# no_ydb
#
# Note: no_mssql also excludes the azuresql driver.
```
For macOS users `goose` is available as a [Homebrew
@@ -50,6 +51,22 @@ Formulae](https://formulae.brew.sh/formula/goose#default):
brew install goose
```
A container image is available for `linux/amd64` and `linux/arm64`. It has no shell and supports `.sql` migrations only. The working directory is `/migrations`.
```shell
docker run --rm \
-v "$PWD/migrations:/migrations" \
-e GOOSE_DRIVER=postgres \
-e GOOSE_DBSTRING="postgres://user:password@host:5432/dbname" \
ghcr.io/pressly/goose:latest up
```
Tags: `vX.Y.Z`, `vX.Y`, `vX`, and `latest`. To copy the binary into your own image:
```dockerfile
COPY --from=ghcr.io/pressly/goose:v3.30.1 /usr/local/bin/goose /usr/local/bin/goose
```
See [installation documentation](https://pressly.github.io/goose/installation/) for more details.
# Usage
@@ -75,6 +92,7 @@ Drivers:
sqlite3
spanner
mssql
azuresql
redshift
tidb
clickhouse
@@ -95,6 +113,7 @@ Examples:
goose redshift "postgres://user:password@qwerty.us-east-1.redshift.amazonaws.com:5439/db" status
goose tidb "user:password@/dbname?parseTime=true" status
goose mssql "sqlserver://user:password@hostname:1433?database=master" status
goose azuresql "sqlserver://myserver.database.windows.net?database=mydb&fedauth=ActiveDirectoryDefault" status
goose clickhouse "tcp://127.0.0.1:9000" status
goose ydb "grpcs://localhost:2135/local?go_query_mode=scripting&go_fake_tx=scripting&go_query_bind=declare,numeric" status
goose starrocks "user:password@/dbname?parseTime=true&interpolateParams=true" status
@@ -114,6 +133,8 @@ Options:
file path to root CA's certificates in pem format (only support on mysql)
-dir string
directory with migration files (default ".", can be set via the GOOSE_MIGRATION_DIR env variable).
-env string
load environment variables from file (default .env)
-h print help
-no-color
disable color output (NO_COLOR env variable supported)
@@ -143,12 +164,15 @@ Commands:
status Dump the migration status for the current DB
version Print the current version of the database
create NAME [sql|go] Creates new migration file with the current timestamp
env Print the current Goose environment configuration
fix Apply sequential ordering to migrations
validate Check migration files without running them
```
</details>
See [drivers](#drivers) for driver-specific details.
Commonly used commands:
[create](#create)<span>&nbsp;•&nbsp;</span> [up](#up)<span>&nbsp;•&nbsp;</span> [up-to](#up-to)<span>&nbsp;•&nbsp;</span> [down](#down)<span>&nbsp;•&nbsp;</span> [down-to](#down-to)<span>&nbsp;•&nbsp;</span> [status](#status)<span>&nbsp;•&nbsp;</span> [version](#version)
@@ -361,15 +385,18 @@ $$ LANGUAGE plpgsql;
<details>
<summary>Supported expansions (click here to expand):</summary>
- `${VAR}` or $VAR - expands to the value of the environment variable `VAR`
- `${VAR:-default}` - expands to the value of the environment variable `VAR`, or `default` if `VAR`
is unset or null
- `${VAR-default}` - expands to the value of the environment variable `VAR`, or `default` if `VAR`
is unset
- `${VAR?err_msg}` - expands to the value of the environment variable `VAR`, or prints `err_msg` and
error if `VAR` unset
- ~~`${VAR:?err_msg}` - expands to the value of the environment variable `VAR`, or prints `err_msg`
and error if `VAR` unset or null.~~ **THIS IS NOT SUPPORTED**
- `${VAR}` or `$VAR` - the value of `VAR`, or an empty string if `VAR` is unset
- `${VAR:-default}` - `default` if `VAR` is unset or empty
- `${VAR-default}` - `default` if `VAR` is unset
- `${VAR:?err_msg}` - an error with `err_msg` if `VAR` is unset or empty
- `${VAR?err_msg}` - an error with `err_msg` if `VAR` is unset
- `${VAR:+word}` - `word` if `VAR` is set and not empty, otherwise an empty string
- `${VAR+word}` - `word` if `VAR` is set, otherwise an empty string
- `${#VAR}` - the length of the value in characters
- `${VAR:offset}` or `${VAR:offset:length}` - a substring of the value
Write `$$` or `\$` for a literal `$`. A `$` that does not start a variable name, such as `$1`, is
kept as-is.
See
[mfridman/interpolate](https://github.com/mfridman/interpolate?tab=readme-ov-file#supported-expansions)
@@ -489,6 +516,15 @@ When you're ready to deploy your migrations in a production environment, we also
ordering. We recommend running `fix` in the CI pipeline, and only when the migrations are ready for
production.
# Drivers
Some drivers have specific requirements or special behaviour. Make sure to read the documentation
for your database's driver before adopting and deploying Goose.
* [ClickHouse](doc/dialect-clickhouse.md) only fully supports some clickhouse
deployment modes and requires careful configuration or work-arounds for
others.
## Credit
The gopher mascot was designed by [Renée French](https://reneefrench.blogspot.com/) / [CC
+1 -5
View File
@@ -58,11 +58,7 @@ func CreateWithTemplate(db *sql.DB, dir string, tmpl *template.Template, name, m
}
path := filepath.Join(dir, filename)
if _, err := os.Stat(path); !os.IsNotExist(err) {
return fmt.Errorf("failed to create migration file: %w", err)
}
f, err := os.Create(path)
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o666)
if err != nil {
return fmt.Errorf("failed to create migration file: %w", err)
}
+6 -5
View File
@@ -4,6 +4,7 @@ import (
"context"
"database/sql"
"fmt"
"slices"
)
// Down rolls back a single migration from the current version.
@@ -92,13 +93,13 @@ func DownToContext(ctx context.Context, db *sql.DB, dir string, version int64, o
// target version.
func downToNoVersioning(ctx context.Context, db *sql.DB, migrations Migrations, version int64) error {
var finalVersion int64
for i := len(migrations) - 1; i >= 0; i-- {
if version >= migrations[i].Version {
finalVersion = migrations[i].Version
for _, migration := range slices.Backward(migrations) {
if version >= migration.Version {
finalVersion = migration.Version
break
}
migrations[i].noVersioning = true
if err := migrations[i].DownContext(ctx, db); err != nil {
migration.noVersioning = true
if err := migration.DownContext(ctx, db); err != nil {
return err
}
}
+11
View File
@@ -0,0 +1,11 @@
# This Dockerfile is used by GoReleaser (see dockers_v2 in .goreleaser.yaml).
# It copies the prebuilt goose binary, so it does not work with a plain
# `docker build .` from the repository root.
#
# The distroless static image has CA certificates, tzdata, and a nonroot user,
# but no shell.
FROM gcr.io/distroless/static-debian13:nonroot
ARG TARGETPLATFORM
COPY $TARGETPLATFORM/goose /usr/local/bin/goose
WORKDIR /migrations
ENTRYPOINT ["/usr/local/bin/goose"]
+1 -1
View File
@@ -23,7 +23,7 @@ func (c *clickhouse) CreateTable(tableName string) string {
tstamp DateTime default now()
)
ENGINE = MergeTree()
ORDER BY (date)`
ORDER BY (version_id)`
return fmt.Sprintf(q, tableName)
}
+1 -1
View File
@@ -20,7 +20,7 @@ func (m *mysql) CreateTable(tableName string) string {
id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
version_id bigint NOT NULL,
is_applied boolean NOT NULL,
tstamp timestamp NULL default now(),
tstamp datetime NULL default CURRENT_TIMESTAMP,
PRIMARY KEY(id)
)`
return fmt.Sprintf(q, tableName)
+1 -1
View File
@@ -20,7 +20,7 @@ func (t *Tidb) CreateTable(tableName string) string {
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE,
version_id bigint NOT NULL,
is_applied boolean NOT NULL,
tstamp timestamp NULL default now(),
tstamp datetime NULL default CURRENT_TIMESTAMP,
PRIMARY KEY(id)
)`
return fmt.Sprintf(q, tableName)
+13 -37
View File
@@ -9,7 +9,6 @@ import (
"log"
"os"
"strings"
"sync"
"github.com/mfridman/interpolate"
)
@@ -81,14 +80,8 @@ func (s *stateMachine) print(msg string, args ...any) {
}
}
const scanBufSize = 4 * 1024 * 1024
var bufferPool = sync.Pool{
New: func() any {
buf := make([]byte, scanBufSize)
return &buf
},
}
// scanBufSize is the maximum length of a single line in a migration file.
const scanBufSize = 4 * 1024 * 1024 // 4 MiB
// Split given SQL script into individual statements and return
// SQL statements for given direction (up=true, down=false).
@@ -101,12 +94,11 @@ var bufferPool = sync.Pool{
// 'StatementBegin' and 'StatementEnd' to allow the script to
// tell us to ignore semicolons.
func ParseSQLMigration(r io.Reader, direction Direction, debug bool) (stmts []string, useTx bool, err error) {
scanBufPtr := bufferPool.Get().(*[]byte)
scanBuf := *scanBufPtr
defer bufferPool.Put(scanBufPtr)
scanner := bufio.NewScanner(r)
scanner.Buffer(scanBuf, scanBufSize)
// A nil buffer makes the scanner allocate its default 4 KiB buffer and grow
// it, up to scanBufSize, only when a line needs it. Most migration files are
// a few KiB, so a large fixed buffer per call would be mostly wasted.
scanner.Buffer(nil, scanBufSize)
stateMachine := newStateMachine(start, debug)
useTx = true
@@ -209,16 +201,15 @@ func ParseSQLMigration(r io.Reader, direction Direction, debug bool) (stmts []st
// Do not include the "+goose StatementEnd" annotation in the final statement.
default:
if useEnvsub {
expanded, err := interpolate.Interpolate(&envWrapper{}, line)
expanded, err := interpolate.Expand(line, interpolate.LookupFunc(os.LookupEnv))
if err != nil {
return nil, false, fmt.Errorf("variable substitution failed: %w:\n%s", err, line)
}
line = expanded
}
// Write SQL line to a buffer.
if _, err := buf.WriteString(line + "\n"); err != nil {
return nil, false, fmt.Errorf("failed to write to buf: %w", err)
}
buf.WriteString(line)
buf.WriteByte('\n')
}
// Read SQL body one by line, if we're in the right direction.
//
@@ -358,37 +349,22 @@ func missingSemicolonError(state parserState, direction Direction, s string) err
)
}
type envWrapper struct{}
var _ interpolate.Env = (*envWrapper)(nil)
func (e *envWrapper) Get(key string) (string, bool) {
return os.LookupEnv(key)
}
func cleanupStatement(input string) string {
return strings.TrimSpace(input)
}
// Checks the line to see if the line has a statement-ending semicolon
// or if the line contains a double-dash comment.
//
// The line is split into words on Unicode whitespace, the same way
// bufio.ScanWords does, and the words before the first "--" are inspected.
func endsWithSemicolon(line string) bool {
scanBufPtr := bufferPool.Get().(*[]byte)
scanBuf := *scanBufPtr
defer bufferPool.Put(scanBufPtr)
prev := ""
scanner := bufio.NewScanner(strings.NewReader(line))
scanner.Buffer(scanBuf, scanBufSize)
scanner.Split(bufio.ScanWords)
for scanner.Scan() {
word := scanner.Text()
for word := range strings.FieldsSeq(line) {
if strings.HasPrefix(word, "--") {
break
}
prev = word
}
return strings.HasSuffix(prev, ";")
}
+346
View File
@@ -0,0 +1,346 @@
package store
import (
"context"
"database/sql"
"errors"
"fmt"
"strings"
"time"
"go.uber.org/multierr"
)
// NewMySQL creates a new MySQL-based [LockStore].
func NewMySQL(tableName string) (LockStore, error) {
if tableName == "" {
return nil, errors.New("table name must not be empty")
}
return &mysqlStore{
tableName: tableName,
}, nil
}
var _ LockStore = (*mysqlStore)(nil)
type mysqlStore struct {
tableName string
}
func (s *mysqlStore) TableExists(
ctx context.Context,
db *sql.DB,
) (bool, error) {
schemaName, tableName := parseTableIdentifier(s.tableName)
var query string
var args []any
if schemaName != "" {
query = `SELECT EXISTS ( SELECT 1 FROM information_schema.tables WHERE table_schema = ? AND table_name = ? )`
args = []any{schemaName, tableName}
} else {
query = `SELECT EXISTS ( SELECT 1 FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = ? )`
args = []any{tableName}
}
var exists bool
if err := db.QueryRowContext(ctx, query, args...).Scan(
&exists,
); err != nil {
return false, fmt.Errorf("table exists: %w", err)
}
return exists, nil
}
func (s *mysqlStore) CreateLockTable(
ctx context.Context,
db *sql.DB,
) error {
exists, err := s.TableExists(ctx, db)
if err != nil {
return fmt.Errorf("check lock table existence: %w", err)
}
if exists {
return nil
}
query := fmt.Sprintf(`CREATE TABLE %s (
lock_id BIGINT NOT NULL PRIMARY KEY,
locked BOOLEAN NOT NULL DEFAULT 0,
locked_at DATETIME(6) NULL,
locked_by TEXT NULL,
lease_expires_at DATETIME(6) NULL,
updated_at DATETIME(6) NULL
)`, s.tableName)
if _, err := db.ExecContext(ctx, query); err != nil {
// Double-check if another process created it concurrently
if exists, checkErr := s.TableExists(ctx, db); checkErr == nil && exists {
// Another process created it, that's fine!
return nil
}
return fmt.Errorf("create lock table %q: %w", s.tableName, err)
}
return nil
}
func (s *mysqlStore) AcquireLock(
ctx context.Context,
db *sql.DB,
lockID int64,
lockedBy string,
leaseDuration time.Duration,
) (_ *AcquireLockResult, retErr error) {
leaseSeconds := int(leaseDuration.Seconds())
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return nil, fmt.Errorf("acquire lock %d: begin tx: %w", lockID, err)
}
defer func() {
if retErr != nil {
retErr = multierr.Append(retErr, tx.Rollback())
}
}()
// First, try to insert a brand-new row. If a row already exists for this lock_id,
// INSERT IGNORE silently no-ops (RowsAffected == 0) and we fall through to the UPDATE.
insertQ := fmt.Sprintf(`INSERT IGNORE INTO %s (lock_id, locked, locked_at, locked_by, lease_expires_at, updated_at)
VALUES (?, true, now(6), ?, now(6) + INTERVAL ? SECOND, now(6))`, s.tableName)
insertRes, err := tx.ExecContext(ctx, insertQ, lockID, lockedBy, leaseSeconds)
if err != nil {
return nil, fmt.Errorf("acquire lock %d: %w", lockID, err)
}
inserted, err := insertRes.RowsAffected()
if err != nil {
return nil, fmt.Errorf("acquire lock %d: rows affected: %w", lockID, err)
}
if inserted == 0 {
// Row exists: only steal if currently unlocked or lease has expired.
updateQ := fmt.Sprintf(`UPDATE %s SET
locked = true,
locked_at = now(6),
locked_by = ?,
lease_expires_at = now(6) + INTERVAL ? SECOND,
updated_at = now(6)
WHERE lock_id = ? AND (locked = false OR lease_expires_at < now(6))`, s.tableName)
updateRes, err := tx.ExecContext(ctx, updateQ, lockedBy, leaseSeconds, lockID)
if err != nil {
return nil, fmt.Errorf("acquire lock %d: %w", lockID, err)
}
affected, err := updateRes.RowsAffected()
if err != nil {
return nil, fmt.Errorf("acquire lock %d: rows affected: %w", lockID, err)
}
if affected == 0 {
// TODO(mf): should we return a special error type here?
return nil, fmt.Errorf("acquire lock %d: already held by another instance", lockID)
}
}
// MySQL has no RETURNING clause; read the row back to learn the resulting lease.
selectQ := fmt.Sprintf(`SELECT locked_by, lease_expires_at FROM %s WHERE lock_id = ?`, s.tableName)
var returnedLockedBy string
var leaseExpiresAt time.Time
if err := tx.QueryRowContext(ctx, selectQ, lockID).Scan(
&returnedLockedBy,
&leaseExpiresAt,
); err != nil {
return nil, fmt.Errorf("acquire lock %d: %w", lockID, err)
}
if err := tx.Commit(); err != nil {
return nil, fmt.Errorf("acquire lock %d: commit: %w", lockID, err)
}
// Verify we got the lock by checking the returned locked_by matches our instance ID
if returnedLockedBy != lockedBy {
return nil, fmt.Errorf("acquire lock %d: acquired by %s instead of %s", lockID, returnedLockedBy, lockedBy)
}
return &AcquireLockResult{
LockedBy: returnedLockedBy,
LeaseExpiresAt: leaseExpiresAt,
}, nil
}
func (s *mysqlStore) ReleaseLock(
ctx context.Context,
db *sql.DB,
lockID int64,
lockedBy string,
) (_ *ReleaseLockResult, retErr error) {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return nil, fmt.Errorf("release lock %d: begin tx: %w", lockID, err)
}
defer func() {
if retErr != nil {
retErr = multierr.Append(retErr, tx.Rollback())
}
}()
// Release lock only if it's held by the current instance
updateQ := fmt.Sprintf(`UPDATE %s SET
locked = false,
locked_at = NULL,
locked_by = NULL,
lease_expires_at = NULL,
updated_at = now(6)
WHERE lock_id = ? AND locked_by = ?`, s.tableName)
res, err := tx.ExecContext(ctx, updateQ, lockID, lockedBy)
if err != nil {
return nil, fmt.Errorf("release lock %d: %w", lockID, err)
}
affected, err := res.RowsAffected()
if err != nil {
return nil, fmt.Errorf("release lock %d: rows affected: %w", lockID, err)
}
if affected == 0 {
// TODO(mf): should we return a special error type here?
return nil, fmt.Errorf("release lock %d: not held by this instance", lockID)
}
if err := tx.Commit(); err != nil {
return nil, fmt.Errorf("release lock %d: commit: %w", lockID, err)
}
return &ReleaseLockResult{
LockID: lockID,
}, nil
}
func (s *mysqlStore) UpdateLease(
ctx context.Context,
db *sql.DB,
lockID int64,
lockedBy string,
leaseDuration time.Duration,
) (_ *UpdateLeaseResult, retErr error) {
leaseSeconds := int(leaseDuration.Seconds())
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return nil, fmt.Errorf("failed to update lease for lock %d: begin tx: %w", lockID, err)
}
defer func() {
if retErr != nil {
retErr = multierr.Append(retErr, tx.Rollback())
}
}()
// Update lease expiration time for heartbeat, only if we own the lock
updateQ := fmt.Sprintf(`UPDATE %s SET
lease_expires_at = now(6) + INTERVAL ? SECOND,
updated_at = now(6)
WHERE lock_id = ? AND locked_by = ? AND locked = true`, s.tableName)
res, err := tx.ExecContext(ctx, updateQ, leaseSeconds, lockID, lockedBy)
if err != nil {
return nil, fmt.Errorf("failed to update lease for lock %d: %w", lockID, err)
}
affected, err := res.RowsAffected()
if err != nil {
return nil, fmt.Errorf("failed to update lease for lock %d: rows affected: %w", lockID, err)
}
if affected == 0 {
return nil, fmt.Errorf("failed to update lease for lock %d: not held by this instance", lockID)
}
selectQ := fmt.Sprintf(`SELECT lease_expires_at FROM %s WHERE lock_id = ?`, s.tableName)
var leaseExpiresAt time.Time
if err := tx.QueryRowContext(ctx, selectQ, lockID).Scan(&leaseExpiresAt); err != nil {
return nil, fmt.Errorf("failed to update lease for lock %d: %w", lockID, err)
}
if err := tx.Commit(); err != nil {
return nil, fmt.Errorf("failed to update lease for lock %d: commit: %w", lockID, err)
}
return &UpdateLeaseResult{
LeaseExpiresAt: leaseExpiresAt,
}, nil
}
func (s *mysqlStore) CheckLockStatus(
ctx context.Context,
db *sql.DB,
lockID int64,
) (*LockStatus, error) {
query := fmt.Sprintf(`SELECT locked, locked_by, lease_expires_at, updated_at FROM %s WHERE lock_id = ?`, s.tableName)
var status LockStatus
err := db.QueryRowContext(ctx, query,
lockID,
).Scan(
&status.Locked,
&status.LockedBy,
&status.LeaseExpiresAt,
&status.UpdatedAt,
)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, fmt.Errorf("lock %d not found", lockID)
}
return nil, fmt.Errorf("check lock status for %d: %w", lockID, err)
}
return &status, nil
}
func (s *mysqlStore) CleanupStaleLocks(ctx context.Context, db *sql.DB) (_ []int64, retErr error) {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return nil, fmt.Errorf("cleanup stale locks: begin tx: %w", err)
}
defer func() {
if retErr != nil {
retErr = multierr.Append(retErr, tx.Rollback())
}
}()
// MySQL has no RETURNING on UPDATE; lock rows for update, collect their IDs, then clear them.
selectQ := fmt.Sprintf(`SELECT lock_id FROM %s WHERE locked = true AND lease_expires_at < now(6) FOR UPDATE`, s.tableName)
rows, err := tx.QueryContext(ctx, selectQ)
if err != nil {
return nil, fmt.Errorf("cleanup stale locks: %w", err)
}
var cleanedLocks []int64
for rows.Next() {
var lockID int64
if err := rows.Scan(&lockID); err != nil {
return nil, multierr.Append(fmt.Errorf("scan cleaned lock ID: %w", err), rows.Close())
}
cleanedLocks = append(cleanedLocks, lockID)
}
if err := rows.Err(); err != nil {
retErr = multierr.Append(retErr, rows.Close())
return nil, fmt.Errorf("iterate over cleaned locks: %w", err)
}
if err := rows.Close(); err != nil {
return nil, fmt.Errorf("close cleaned locks rows: %w", err)
}
if len(cleanedLocks) > 0 {
placeholders := strings.TrimSuffix(strings.Repeat("?,", len(cleanedLocks)), ",")
updateQ := fmt.Sprintf(`UPDATE %s SET
locked = false,
locked_at = NULL,
locked_by = NULL,
lease_expires_at = NULL,
updated_at = now(6)
WHERE lock_id IN (%s)`, s.tableName, placeholders)
args := make([]any, len(cleanedLocks))
for i, id := range cleanedLocks {
args[i] = id
}
if _, err := tx.ExecContext(ctx, updateQ, args...); err != nil {
return nil, fmt.Errorf("cleanup stale locks: %w", err)
}
}
if err := tx.Commit(); err != nil {
return nil, fmt.Errorf("cleanup stale locks: commit: %w", err)
}
return cleanedLocks, nil
}
+16
View File
@@ -3,6 +3,8 @@ package table
import (
"log/slog"
"time"
"github.com/sethvargo/go-retry"
)
// Config holds configuration for table locker.
@@ -26,3 +28,17 @@ type ProbeConfig struct {
IntervalDuration time.Duration
FailureThreshold uint64
}
// backoff returns a new backoff for one Lock or Unlock call. The backoff counts the retries it has
// used and never resets, so each call must get its own.
func (p ProbeConfig) backoff() retry.Backoff {
// retry.NewConstant is not used here, because it panics on an interval that is not positive.
constant := retry.BackoffFunc(func() (time.Duration, bool) {
return p.IntervalDuration, false
})
return retry.WithMaxRetries(
p.FailureThreshold,
// Add +/- 25% jitter to reduce thundering herd
retry.WithJitterPercent(25, constant),
)
}
+6 -14
View File
@@ -29,8 +29,8 @@ type Locker struct {
instanceID string
leaseDuration time.Duration
heartbeatInterval time.Duration
retryLock retry.Backoff
retryUnlock retry.Backoff
lockTimeout ProbeConfig
unlockTimeout ProbeConfig
logger *slog.Logger
retryPolicy RetryPolicyFunc
@@ -63,16 +63,8 @@ func New(lockStore store.LockStore, cfg Config) *Locker {
heartbeatInterval: cfg.HeartbeatInterval,
logger: logger,
retryPolicy: cfg.RetryPolicy,
retryLock: retry.WithMaxRetries(
cfg.LockTimeout.FailureThreshold,
// Add +/- 25% jitter to reduce thundering herd
retry.WithJitterPercent(25, retry.NewConstant(cfg.LockTimeout.IntervalDuration)),
),
retryUnlock: retry.WithMaxRetries(
cfg.UnlockTimeout.FailureThreshold,
// Add +/- 25% jitter to reduce thundering herd
retry.WithJitterPercent(25, retry.NewConstant(cfg.UnlockTimeout.IntervalDuration)),
),
lockTimeout: cfg.LockTimeout,
unlockTimeout: cfg.UnlockTimeout,
}
}
@@ -89,7 +81,7 @@ func (l *Locker) Lock(ctx context.Context, db *sql.DB) error {
return fmt.Errorf("ensure lock table exists: %w", err)
}
err := retry.Do(ctx, l.retryLock, func(ctx context.Context) error {
err := retry.Do(ctx, l.lockTimeout.backoff(), func(ctx context.Context) error {
_, err := l.store.AcquireLock(ctx, db, l.lockID, l.instanceID, l.leaseDuration)
if err != nil {
// Clean up any stale locks before retrying
@@ -143,7 +135,7 @@ func (l *Locker) Unlock(ctx context.Context, db *sql.DB) error {
// Stop heartbeat first
l.stopHeartbeat()
err := retry.Do(ctx, l.retryUnlock, func(ctx context.Context) error {
err := retry.Do(ctx, l.unlockTimeout.backoff(), func(ctx context.Context) error {
_, err := l.store.ReleaseLock(ctx, db, l.lockID, l.instanceID)
if err != nil {
if l.shouldRetry(err) {
+54
View File
@@ -0,0 +1,54 @@
package lock
import (
"fmt"
"time"
"github.com/pressly/goose/v3/lock/internal/store"
"github.com/pressly/goose/v3/lock/internal/table"
)
// NewMySQLTableLocker returns a Locker that uses MySQL table-based locking. It manages a single
// lock row and keeps the lock alive automatically.
//
// Default behavior:
//
// - Lease (30s): How long the lock is valid if heartbeat stops
// - Heartbeat (5s): How often the lock gets refreshed to keep it alive
// - If the process dies, others can take the lock after lease expires
//
// Defaults:
//
// Table: "goose_lock"
// Lock ID: 4097083626 (crc32 of "goose")
// Lock retry: 5s intervals, 5min timeout
// Unlock retry: 2s intervals, 1min timeout
//
// Lock and Unlock both retry on failure. Lock stays alive automatically until released. All
// defaults can be overridden with options.
func NewMySQLTableLocker(options ...TableLockerOption) (Locker, error) {
config := table.Config{
TableName: DefaultLockTableName,
LockID: DefaultLockID,
LeaseDuration: 30 * time.Second,
HeartbeatInterval: 5 * time.Second,
LockTimeout: table.ProbeConfig{
IntervalDuration: 5 * time.Second,
FailureThreshold: 60, // 5 minutes total
},
UnlockTimeout: table.ProbeConfig{
IntervalDuration: 2 * time.Second,
FailureThreshold: 30, // 1 minute total
},
}
for _, opt := range options {
if err := opt.apply(&config); err != nil {
return nil, err
}
}
lockStore, err := store.NewMySQL(config.TableName)
if err != nil {
return nil, fmt.Errorf("create lock store: %w", err)
}
return table.New(lockStore, config), nil
}
+7 -13
View File
@@ -86,28 +86,22 @@ func NewPostgresSessionLocker(opts ...SessionLockerOption) (SessionLocker, error
}
}
return &postgresSessionLocker{
lockID: cfg.lockID,
retryLock: retry.WithMaxRetries(
cfg.lockProbe.failureThreshold,
retry.NewConstant(cfg.lockProbe.intervalDuration),
),
retryUnlock: retry.WithMaxRetries(
cfg.unlockProbe.failureThreshold,
retry.NewConstant(cfg.unlockProbe.intervalDuration),
),
lockID: cfg.lockID,
lockProbe: cfg.lockProbe,
unlockProbe: cfg.unlockProbe,
}, nil
}
type postgresSessionLocker struct {
lockID int64
retryLock retry.Backoff
retryUnlock retry.Backoff
lockProbe probe
unlockProbe probe
}
var _ SessionLocker = (*postgresSessionLocker)(nil)
func (l *postgresSessionLocker) SessionLock(ctx context.Context, conn *sql.Conn) error {
return retry.Do(ctx, l.retryLock, func(ctx context.Context) error {
return retry.Do(ctx, l.lockProbe.backoff(), func(ctx context.Context) error {
row := conn.QueryRowContext(ctx, "SELECT pg_try_advisory_lock($1)", l.lockID)
var locked bool
if err := row.Scan(&locked); err != nil {
@@ -125,7 +119,7 @@ func (l *postgresSessionLocker) SessionLock(ctx context.Context, conn *sql.Conn)
}
func (l *postgresSessionLocker) SessionUnlock(ctx context.Context, conn *sql.Conn) error {
return retry.Do(ctx, l.retryUnlock, func(ctx context.Context) error {
return retry.Do(ctx, l.unlockProbe.backoff(), func(ctx context.Context) error {
var unlocked bool
row := conn.QueryRowContext(ctx, "SELECT pg_advisory_unlock($1)", l.lockID)
if err := row.Scan(&unlocked); err != nil {
+12
View File
@@ -3,6 +3,8 @@ package lock
import (
"errors"
"time"
"github.com/sethvargo/go-retry"
)
const (
@@ -89,6 +91,16 @@ type probe struct {
failureThreshold uint64
}
// backoff returns a new backoff for one lock or unlock call. The backoff counts the retries it
// has used and never resets, so each call must get its own.
func (p probe) backoff() retry.Backoff {
// retry.NewConstant is not used here, because it panics on an interval that is not positive.
constant := retry.BackoffFunc(func() (time.Duration, bool) {
return p.intervalDuration, false
})
return retry.WithMaxRetries(p.failureThreshold, constant)
}
var _ SessionLockerOption = (sessionLockerConfigFunc)(nil)
type sessionLockerConfigFunc func(*sessionLockerConfig) error
+4 -3
View File
@@ -8,6 +8,7 @@ import (
"io/fs"
"math"
"path"
"slices"
"sort"
"strings"
"time"
@@ -63,9 +64,9 @@ func (ms Migrations) Next(current int64) (*Migration, error) {
// Previous : Get the previous migration.
func (ms Migrations) Previous(current int64) (*Migration, error) {
for i := len(ms) - 1; i >= 0; i-- {
if ms[i].Version < current {
return ms[i], nil
for _, m := range slices.Backward(ms) {
if m.Version < current {
return m, nil
}
}
-4
View File
@@ -122,10 +122,6 @@ func merge(sources *fileSources, registered map[int64]*Migration) ([]*Migration,
migrations = append(migrations, m)
migrationLookup[source.Version] = m
}
// If there are no Go files in the filesystem and no registered Go migrations, return early.
if len(sources.goSources) == 0 && len(registered) == 0 {
return migrations, nil
}
// Return an error if the given sources contain a versioned Go migration that has not been
// registered. This is a sanity check to ensure users didn't accidentally create a valid looking
// Go migration file on disk and forget to register it.