dbmigrate

package
v1.30.0 Latest Latest
Warning

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

Go to latest
Published: Jul 12, 2026 License: Apache-2.0 Imports: 12 Imported by: 0

Documentation

Overview

Package dbmigrate는 embed.FS의 manifest.txt 순서대로 SQL 파일을 실행합니다.

패키지 개요

이 패키지는 bot별 migrations embed.FS와 database/sql 또는 pgx 실행 함수를 주입받아 manifest 순서를 공통으로 처리합니다. manifest 라인은 "NNN file.sql" 형식을 기대하며 빈 줄과 '#' 주석은 무시합니다.

주요 사용 패턴

err := dbmigrate.Apply(ctx, migrations.FS, dbmigrate.SQLExec(db))
err = dbmigrate.Apply(ctx, migrations.FS, func(ctx context.Context, query string, args ...any) error {
    _, execErr := conn.Exec(ctx, query, args...)
    return execErr
}, dbmigrate.WithOnly("0001_repository_baseline.sql"))

Index

Constants

View Source
const (
	// ManifestName은 기본 migration manifest 파일명이다.
	ManifestName = "manifest.txt"
)

Variables

This section is empty.

Functions

func Apply

func Apply(ctx context.Context, fsys fs.FS, exec Execer, opts ...Option) error

Apply는 manifest 순서대로 SQL 파일을 읽어 exec로 실행한다.

func Baseline added in v1.28.0

func Baseline(ctx context.Context, fsys fs.FS, exec Execer, through string, l Ledger) error

Baseline은 지정 migration까지 ledger에 적용 완료로 기록한다.

func Manifest

func Manifest(fsys fs.FS) (names []string, err error)

Manifest는 manifest.txt를 파싱해 적용 순서대로 SQL 파일명을 반환한다.

func WithAdvisoryLock added in v1.28.0

func WithAdvisoryLock(ctx context.Context, s LockSession, cfg LockConfig, fn func(context.Context) error) (err error)

WithAdvisoryLock은 advisory lock을 잡은 동안 fn을 실행한다.

Types

type Execer

type Execer func(context.Context, string, ...any) error

Execer는 migration SQL 실행 함수다.

func SQLExec

func SQLExec(db SQLExecer) Execer

SQLExec는 database/sql 계열 handle을 Execer로 감싼다.

type Ledger added in v1.28.0

type Ledger struct {
	// Table은 ledger 테이블 이름이다.
	Table string
}

Ledger는 적용된 migration 파일명을 저장하는 테이블 설정이다.

func (Ledger) Applied added in v1.28.0

func (l Ledger) Applied(ctx context.Context, q RowQuerier, name string) (bool, error)

Applied는 migration 파일명이 ledger에 기록되어 있는지 조회한다.

func (Ledger) Ensure added in v1.28.0

func (l Ledger) Ensure(ctx context.Context, exec Execer) error

Ensure는 ledger 테이블을 없으면 생성한다.

func (Ledger) Record added in v1.28.0

func (l Ledger) Record(ctx context.Context, exec Execer, name string) error

Record는 migration 파일명을 ledger에 idempotent하게 기록한다.

type LockConfig added in v1.28.0

type LockConfig struct {
	// Key는 PostgreSQL advisory lock key다.
	Key int64
	// Acquire는 lock 획득 최대 대기 시간이다.
	Acquire time.Duration
	// Poll은 lock 획득 재시도 간격이다.
	Poll time.Duration
	// Release는 lock 해제 최대 대기 시간이다.
	Release time.Duration
	// OnUnlockError는 unlock 실패를 return 대신 전달받는 callback이다.
	OnUnlockError func(error)
}

LockConfig는 migration advisory lock 획득과 해제 설정이다.

type LockSession added in v1.28.0

type LockSession interface {
	// TryAdvisoryLock은 advisory lock 획득을 한 번 시도한다.
	TryAdvisoryLock(ctx context.Context, key int64) (bool, error)
	// AdvisoryUnlock은 advisory lock 해제를 시도한다.
	AdvisoryUnlock(ctx context.Context, key int64) (bool, error)
}

LockSession은 PostgreSQL advisory lock 최소 동작이다.

func SQLLockSession added in v1.28.0

func SQLLockSession(c *sql.Conn) LockSession

SQLLockSession은 database/sql 연결을 LockSession으로 감싼다.

type Option

type Option func(*options)

Option은 migration 적용 동작을 조정한다.

func WithLedger added in v1.28.0

func WithLedger(l Ledger, q RowQuerier) Option

WithLedger는 적용 완료 ledger를 사용해 migration을 idempotent하게 만든다. Apply와 Record는 별도 Execer 호출이라 원자적이지 않고, ledger는 at-least-once이므로 migration SQL은 idempotent해야 한다. ledger 단독은 동시 실행을 막지 못한다: 여러 마이그레이터가 같은 migration을 동시에 Applied()==false로 보고 함께 실행할 수 있다. 다중 레플리카에서 single-flight가 필요하면 Apply를 WithAdvisoryLock으로 감싸라.

func WithOnly

func WithOnly(names ...string) Option

WithOnly는 지정한 migration 파일명만 manifest 순서대로 적용한다. manifest에 없는 이름은 Apply가 세션 설정·ledger 생성 전에 거부하지만, Apply를 WithAdvisoryLock 안에서 호출하는 문서화된 패턴에서는 이 검출이 lock 획득 뒤에 일어난다. lock 전 fail-fast가 필요하면 호출자가 Manifest()로 사전 검증하라.

func WithSession added in v1.29.0

func WithSession(cfg SessionConfig) Option

type Row added in v1.28.0

type Row interface {
	// Scan은 row 값을 destination에 복사한다.
	Scan(dest ...any) error
}

Row는 단일 SQL row scan 동작이다.

type RowQuerier added in v1.28.0

type RowQuerier interface {
	// QueryRow는 단일 row 조회를 실행한다.
	QueryRow(ctx context.Context, query string, args ...any) Row
}

RowQuerier는 context-aware 단일 row 조회 동작이다.

func SQLQueryRow added in v1.28.0

func SQLQueryRow(db SQLQueryRowContext) RowQuerier

SQLQueryRow는 database/sql 계열 handle을 RowQuerier로 감싼다.

type SQLExecer

type SQLExecer interface {
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
}

SQLExecer는 database/sql 계열 ExecContext 최소 인터페이스다.

type SQLQueryRowContext added in v1.28.0

type SQLQueryRowContext interface {
	// QueryRowContext는 context-aware 단일 row 조회를 실행한다.
	QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
}

SQLQueryRowContext는 database/sql 계열 QueryRowContext 최소 인터페이스다.

type SessionConfig added in v1.29.0

type SessionConfig struct {
	LockTimeout      time.Duration
	StatementTimeout time.Duration
}

set_config(..., false)는 session scope라 connection 수명 동안 유지된다 — exec는 마이그레이션 전용 pinned connection이어야 하며, pool 바인딩 exec에 적용하면 설정이 임의의 conn 하나에만 남아 이후 세션으로 샌다.

func (SessionConfig) Configure added in v1.29.0

func (c SessionConfig) Configure(ctx context.Context, exec Execer) error

type UnlockFailureEvicter added in v1.29.0

type UnlockFailureEvicter interface {
	EvictAfterUnlockFailure() error
}

WithAdvisoryLock은 unlock이 에러이거나 released=false(lock 미보유)로 끝나면 세션 lock 상태가 불확실하다고 보고 이 메서드를 호출한다. pooled conn 구현체는 여기서 conn을 hijack 후 close해, lock을 쥔 채 풀로 반환·재사용되는 것을 막아야 한다.

Jump to

Keyboard shortcuts

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