refactor into an importable library and keep an example

move-migrations-to-option
Mason Payne 2024-08-22 00:05:50 -06:00
parent cdc8fc4e5e
commit cfd22dfc9c
6 changed files with 18 additions and 8 deletions

View File

@ -1,4 +1,4 @@
package libsqlDB package libsqldb
import ( import (
"database/sql" "database/sql"

View File

@ -1,6 +1,6 @@
//go:build !windows //go:build !windows
package libsqlDB package libsqldb
import ( import (
"database/sql" "database/sql"
@ -26,6 +26,8 @@ var syncInterval = 200 * time.Millisecond
func NewLibSqlDB(primaryUrl string, migrationFiles embed.FS, opts ...Options) (*LibSqlDB, error) { func NewLibSqlDB(primaryUrl string, migrationFiles embed.FS, opts ...Options) (*LibSqlDB, error) {
l := libSqlDefaults() l := libSqlDefaults()
_migrationFiles = migrationFiles
for _, option := range opts { for _, option := range opts {
err := option(l) err := option(l)
if err != nil { if err != nil {

View File

@ -1,18 +1,24 @@
package main package main
import ( import (
"embed"
"fmt" "fmt"
"git.sa.vin/payne8/libsqldb"
"os" "os"
) )
//go:embed migrations/*.sql
var migrationFiles embed.FS
func main() { func main() {
primaryUrl := os.Getenv("LIBSQL_DATABASE_URL") primaryUrl := os.Getenv("LIBSQL_DATABASE_URL")
authToken := os.Getenv("LIBSQL_AUTH_TOKEN") authToken := os.Getenv("LIBSQL_AUTH_TOKEN")
tdb, err := libsqlDB.NewLibSqlDB( tdb, err := libsqldb.NewLibSqlDB(
primaryUrl, primaryUrl,
libsqlDB.WithAuthToken(authToken), migrationFiles,
libsqlDB.WithLocalDBName("local.db"), libsqldb.WithAuthToken(authToken),
libsqldb.WithLocalDBName("local.db"),
) )
if err != nil { if err != nil {
fmt.Fprintf(os.Stderr, "failed to open db %s: %s", primaryUrl, err) fmt.Fprintf(os.Stderr, "failed to open db %s: %s", primaryUrl, err)

2
go.mod
View File

@ -1,4 +1,4 @@
module {{.ModulePath}} module git.sa.vin/payne8/libsqldb
go 1.21 go 1.21

View File

@ -1,6 +1,6 @@
//go:build windows //go:build windows
package libsqlDB package libsqldb
import ( import (
"database/sql" "database/sql"
@ -8,7 +8,7 @@ import (
"fmt" "fmt"
"time" "time"
multierror "github.com/hashicorp/go-multierror" "github.com/hashicorp/go-multierror"
_ "github.com/tursodatabase/libsql-client-go/libsql" _ "github.com/tursodatabase/libsql-client-go/libsql"
) )
@ -26,6 +26,8 @@ type LibSqlDB struct {
func NewLibSqlDB(primaryUrl string, migrationFiles embed.FS, opts ...Options) (*LibSqlDB, error) { func NewLibSqlDB(primaryUrl string, migrationFiles embed.FS, opts ...Options) (*LibSqlDB, error) {
l := &LibSqlDB{} l := &LibSqlDB{}
_migrationFiles = migrationFiles
for _, option := range opts { for _, option := range opts {
err := option(l) err := option(l)
if err != nil { if err != nil {