2024-08-21 23:38:18 -06:00
|
|
|
//go:build windows
|
|
|
|
|
2024-08-22 00:05:50 -06:00
|
|
|
package libsqldb
|
2024-08-21 23:38:18 -06:00
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
|
|
|
"embed"
|
|
|
|
"fmt"
|
|
|
|
"time"
|
|
|
|
|
2024-08-22 00:05:50 -06:00
|
|
|
"github.com/hashicorp/go-multierror"
|
2024-08-21 23:38:18 -06:00
|
|
|
_ "github.com/tursodatabase/libsql-client-go/libsql"
|
|
|
|
)
|
|
|
|
|
|
|
|
type LibSqlDB struct {
|
2024-08-22 00:16:35 -06:00
|
|
|
DB *sql.DB
|
2024-08-21 23:38:18 -06:00
|
|
|
|
|
|
|
dir string // only used for embedded replica
|
|
|
|
localDBName string // only used for embedded replica but needs to be here for consistency
|
|
|
|
authToken string
|
|
|
|
syncInterval time.Duration // only used for embedded replica
|
|
|
|
encryptionKey string // only used for embedded replica
|
|
|
|
readYourWrites *bool // only used for embedded replica
|
2024-10-16 18:04:01 -06:00
|
|
|
useMigrations bool
|
|
|
|
migrationFiles embed.FS
|
|
|
|
migrations []Migrations
|
2024-08-21 23:38:18 -06:00
|
|
|
}
|
|
|
|
|
2024-10-16 18:04:01 -06:00
|
|
|
func NewLibSqlDB(primaryUrl string, opts ...Options) (*LibSqlDB, error) {
|
2024-08-21 23:38:18 -06:00
|
|
|
l := &LibSqlDB{}
|
|
|
|
|
|
|
|
for _, option := range opts {
|
|
|
|
err := option(l)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("error applying options | %w", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
url := primaryUrl
|
|
|
|
if l.authToken != "" {
|
|
|
|
url = primaryUrl + "?authToken=" + l.authToken
|
|
|
|
}
|
|
|
|
|
|
|
|
db, err := sql.Open("libsql", url)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("error setting up LibSQL db | %w", err)
|
|
|
|
}
|
|
|
|
|
2024-10-16 18:04:01 -06:00
|
|
|
if l.useMigrations {
|
|
|
|
err = l.setupMigrations()
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("error setting up migrations | %w", err)
|
|
|
|
}
|
2024-08-21 23:38:18 -06:00
|
|
|
}
|
|
|
|
|
2024-10-16 18:04:01 -06:00
|
|
|
l.DB = db
|
|
|
|
|
|
|
|
return l, nil
|
2024-08-21 23:38:18 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
func (t *LibSqlDB) Close() error {
|
|
|
|
var resultError *multierror.Error
|
|
|
|
|
2024-08-22 00:47:04 -06:00
|
|
|
if err := t.DB.Close(); err != nil {
|
2024-08-21 23:38:18 -06:00
|
|
|
resultError = multierror.Append(resultError, fmt.Errorf("failed to close database: %w", err))
|
|
|
|
}
|
|
|
|
|
|
|
|
return resultError.ErrorOrNil()
|
|
|
|
}
|