-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Add DuckDB support with official driver and modern stdlib #1337
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
rriski
wants to merge
6
commits into
golang-migrate:master
Choose a base branch
from
rriski:duckdb-support
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
af3e803
Add DuckDB support
michaelmdresser 06ae57c
Update DuckDB driver to use official duckdb-go/v2 and errors.Join
rriski d28cb35
Use standard schema_migrations table name
rriski cda0657
docs: add DuckDB documentation to README
rriski 0994939
duckdb: add config parity with sqlite
rriski 8debcd4
duckdb: align tests with sqlite
rriski File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| # DuckDB | ||
|
|
||
| `duckdb://path/to/database.db` | ||
|
|
||
| | URL Query | Description | | ||
| |------------|-------------| | ||
| | `x-migrations-table` | Name of the migrations table (default: `schema_migrations`) | | ||
| | `x-no-tx-wrap` | Disable automatic transaction wrapping for migrations (default: `false`) | | ||
|
|
||
| ## Notes | ||
|
|
||
| * DuckDB is an in-process SQL OLAP database management system. | ||
| * Uses the official DuckDB Go driver: [github.com/duckdb/duckdb-go/v2](https://github.com/duckdb/duckdb-go) | ||
| * Supports in-memory databases using `:memory:` as the path. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,260 @@ | ||
| package duckdb | ||
|
|
||
| import ( | ||
| "database/sql" | ||
| "errors" | ||
| "fmt" | ||
| "io" | ||
| nurl "net/url" | ||
| "strconv" | ||
| "strings" | ||
| "sync/atomic" | ||
|
|
||
| "github.com/golang-migrate/migrate/v4" | ||
| "github.com/golang-migrate/migrate/v4/database" | ||
|
|
||
| _ "github.com/duckdb/duckdb-go/v2" | ||
| ) | ||
|
|
||
| func init() { | ||
| database.Register("duckdb", &DuckDB{}) | ||
| } | ||
|
|
||
| var DefaultMigrationsTable = "schema_migrations" | ||
|
|
||
| var ( | ||
| ErrNilConfig = errors.New("no config") | ||
| ) | ||
|
|
||
| type Config struct { | ||
| MigrationsTable string | ||
| NoTxWrap bool | ||
| } | ||
|
|
||
| type DuckDB struct { | ||
| db *sql.DB | ||
| isLocked atomic.Bool | ||
| config *Config | ||
| } | ||
|
|
||
| func (d *DuckDB) Open(url string) (database.Driver, error) { | ||
| purl, err := nurl.Parse(url) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("parsing url: %w", err) | ||
| } | ||
| dbfile := strings.Replace(migrate.FilterCustomQuery(purl).String(), "duckdb://", "", 1) | ||
| db, err := sql.Open("duckdb", dbfile) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("opening '%s': %w", dbfile, err) | ||
| } | ||
|
|
||
| qv := purl.Query() | ||
| migrationsTable := qv.Get("x-migrations-table") | ||
| if len(migrationsTable) == 0 { | ||
| migrationsTable = DefaultMigrationsTable | ||
| } | ||
|
|
||
| noTxWrap := false | ||
| if v := qv.Get("x-no-tx-wrap"); v != "" { | ||
| noTxWrap, err = strconv.ParseBool(v) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("x-no-tx-wrap: %s", err) | ||
| } | ||
| } | ||
|
|
||
| if err := db.Ping(); err != nil { | ||
| return nil, fmt.Errorf("pinging: %w", err) | ||
| } | ||
| cfg := &Config{ | ||
| MigrationsTable: migrationsTable, | ||
| NoTxWrap: noTxWrap, | ||
| } | ||
| return WithInstance(db, cfg) | ||
| } | ||
|
|
||
| func (d *DuckDB) Close() error { | ||
| return d.db.Close() | ||
| } | ||
|
|
||
| func (d *DuckDB) Lock() error { | ||
| if !d.isLocked.CompareAndSwap(false, true) { | ||
| return database.ErrLocked | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| func (d *DuckDB) Unlock() error { | ||
| if !d.isLocked.CompareAndSwap(true, false) { | ||
| return database.ErrNotLocked | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| func (d *DuckDB) Drop() error { | ||
| tablesQuery := `SELECT schema_name, table_name FROM duckdb_tables()` | ||
| tables, err := d.db.Query(tablesQuery) | ||
| if err != nil { | ||
| return &database.Error{OrigErr: err, Query: []byte(tablesQuery)} | ||
| } | ||
| defer func() { | ||
| if errClose := tables.Close(); errClose != nil { | ||
| err = errors.Join(err, errClose) | ||
| } | ||
| }() | ||
|
|
||
| tableNames := []string{} | ||
| for tables.Next() { | ||
| var ( | ||
| schemaName string | ||
| tableName string | ||
| ) | ||
|
|
||
| if err := tables.Scan(&schemaName, &tableName); err != nil { | ||
| return &database.Error{OrigErr: err, Err: "scanning schema and table name"} | ||
| } | ||
|
|
||
| if len(schemaName) > 0 { | ||
| tableNames = append(tableNames, fmt.Sprintf("%s.%s", schemaName, tableName)) | ||
| } else { | ||
| tableNames = append(tableNames, tableName) | ||
| } | ||
| } | ||
| if err := tables.Err(); err != nil { | ||
| return &database.Error{OrigErr: err, Query: []byte(tablesQuery), Err: "err in rows after scanning"} | ||
| } | ||
|
|
||
| for _, t := range tableNames { | ||
| dropQuery := fmt.Sprintf("DROP TABLE %s", t) | ||
| if _, err := d.db.Exec(dropQuery); err != nil { | ||
| return &database.Error{OrigErr: err, Query: []byte(dropQuery)} | ||
| } | ||
| } | ||
|
|
||
| return nil | ||
|
|
||
| } | ||
|
|
||
| func (d *DuckDB) SetVersion(version int, dirty bool) error { | ||
| tx, err := d.db.Begin() | ||
| if err != nil { | ||
| return &database.Error{OrigErr: err, Err: "transaction start failed"} | ||
| } | ||
|
|
||
| query := "DELETE FROM " + d.config.MigrationsTable | ||
| if _, err := tx.Exec(query); err != nil { | ||
| return &database.Error{OrigErr: err, Query: []byte(query)} | ||
| } | ||
|
|
||
| // Also re-write the schema version for nil dirty versions to prevent | ||
| // empty schema version for failed down migration on the first migration | ||
| // See: https://github.com/golang-migrate/migrate/issues/330 | ||
| // | ||
| // NOTE: Copied from sqlite implementation, unsure if this is necessary for | ||
| // duckdb | ||
| if version >= 0 || (version == database.NilVersion && dirty) { | ||
| query := fmt.Sprintf(`INSERT INTO %s (version, dirty) VALUES (?, ?)`, d.config.MigrationsTable) | ||
| if _, err := tx.Exec(query, version, dirty); err != nil { | ||
| if errRollback := tx.Rollback(); errRollback != nil { | ||
| err = errors.Join(err, errRollback) | ||
| } | ||
| return &database.Error{OrigErr: err, Query: []byte(query)} | ||
| } | ||
| } | ||
|
|
||
| if err := tx.Commit(); err != nil { | ||
| return &database.Error{OrigErr: err, Err: "transaction commit failed"} | ||
| } | ||
|
|
||
| return nil | ||
| } | ||
|
|
||
| func (m *DuckDB) Version() (version int, dirty bool, err error) { | ||
| query := "SELECT version, dirty FROM " + m.config.MigrationsTable + " LIMIT 1" | ||
| err = m.db.QueryRow(query).Scan(&version, &dirty) | ||
| if err != nil { | ||
| return database.NilVersion, false, nil | ||
| } | ||
| return version, dirty, nil | ||
| } | ||
|
|
||
| func (d *DuckDB) Run(migration io.Reader) error { | ||
| migr, err := io.ReadAll(migration) | ||
| if err != nil { | ||
| return fmt.Errorf("reading migration: %w", err) | ||
| } | ||
| query := string(migr[:]) | ||
|
|
||
| if d.config.NoTxWrap { | ||
| if _, err := d.db.Exec(query); err != nil { | ||
| return &database.Error{OrigErr: err, Query: []byte(query)} | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| tx, err := d.db.Begin() | ||
| if err != nil { | ||
| return &database.Error{OrigErr: err, Err: "transaction start failed"} | ||
| } | ||
| if _, err := tx.Exec(query); err != nil { | ||
| if errRollback := tx.Rollback(); errRollback != nil { | ||
| err = errors.Join(err, errRollback) | ||
| } | ||
| return &database.Error{OrigErr: err, Query: []byte(query)} | ||
| } | ||
| if err := tx.Commit(); err != nil { | ||
| return &database.Error{OrigErr: err, Err: "transaction commit failed"} | ||
| } | ||
| 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 Sqlite type. | ||
| func (d *DuckDB) ensureVersionTable() (err error) { | ||
| if err = d.Lock(); err != nil { | ||
| return err | ||
| } | ||
|
|
||
| defer func() { | ||
| if e := d.Unlock(); e != nil { | ||
| if err == nil { | ||
| err = e | ||
| } else { | ||
| err = errors.Join(err, e) | ||
| } | ||
| } | ||
| }() | ||
|
|
||
| query := fmt.Sprintf(` | ||
| CREATE TABLE IF NOT EXISTS %s (version BIGINT, dirty BOOLEAN); | ||
| CREATE UNIQUE INDEX IF NOT EXISTS version_unique ON %s (version); | ||
| `, d.config.MigrationsTable, d.config.MigrationsTable) | ||
|
|
||
| if _, err := d.db.Exec(query); err != nil { | ||
| return fmt.Errorf("creating version table via '%s': %w", query, err) | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| func WithInstance(instance *sql.DB, config *Config) (database.Driver, error) { | ||
| if config == nil { | ||
| return nil, ErrNilConfig | ||
| } | ||
|
|
||
| if err := instance.Ping(); err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| if len(config.MigrationsTable) == 0 { | ||
| config.MigrationsTable = DefaultMigrationsTable | ||
| } | ||
|
|
||
| mx := &DuckDB{ | ||
| db: instance, | ||
| config: config, | ||
| } | ||
| if err := mx.ensureVersionTable(); err != nil { | ||
| return nil, err | ||
| } | ||
| return mx, nil | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Comment references 'Sqlite type' but this is the DuckDB driver. Update to 'DuckDB type' for accuracy.