waveterm/pkg/wstore/wstore_dbsetup.go

82 lines
1.8 KiB
Go
Raw Normal View History

2024-05-21 20:09:22 +02:00
// Copyright 2024, Command Line Inc.
// SPDX-License-Identifier: Apache-2.0
package wstore
import (
"context"
"fmt"
"log"
"path/filepath"
2024-05-21 20:09:22 +02:00
"time"
"github.com/jmoiron/sqlx"
"github.com/sawka/txwrap"
2024-09-05 23:25:45 +02:00
"github.com/wavetermdev/waveterm/pkg/util/migrateutil"
"github.com/wavetermdev/waveterm/pkg/wavebase"
"github.com/wavetermdev/waveterm/pkg/waveobj"
2024-05-22 06:15:11 +02:00
2024-09-05 23:25:45 +02:00
dbfs "github.com/wavetermdev/waveterm/db"
2024-05-21 20:09:22 +02:00
)
const WStoreDBName = "waveterm.db"
type TxWrap = txwrap.TxWrap
var globalDB *sqlx.DB
func InitWStore() error {
ctx, cancelFn := context.WithTimeout(context.Background(), 2*time.Second)
defer cancelFn()
var err error
globalDB, err = MakeDB(ctx)
if err != nil {
return err
}
err = migrateutil.Migrate("wstore", globalDB.DB, dbfs.WStoreMigrationFS, "migrations-wstore")
2024-05-21 20:09:22 +02:00
if err != nil {
return err
}
log.Printf("wstore initialized\n")
return nil
}
func GetDBName() string {
waveHome := wavebase.GetWaveHomeDir()
return filepath.Join(waveHome, wavebase.WaveDBDir, WStoreDBName)
2024-05-21 20:09:22 +02:00
}
func MakeDB(ctx context.Context) (*sqlx.DB, error) {
dbName := GetDBName()
rtn, err := sqlx.Open("sqlite3", fmt.Sprintf("file:%s?mode=rwc&_journal_mode=WAL&_busy_timeout=5000", dbName))
if err != nil {
return nil, err
}
rtn.DB.SetMaxOpenConns(1)
return rtn, nil
}
func WithTx(ctx context.Context, fn func(tx *TxWrap) error) (rtnErr error) {
2024-08-20 23:56:48 +02:00
waveobj.ContextUpdatesBeginTx(ctx)
defer func() {
if rtnErr != nil {
2024-08-20 23:56:48 +02:00
waveobj.ContextUpdatesRollbackTx(ctx)
} else {
2024-08-20 23:56:48 +02:00
waveobj.ContextUpdatesCommitTx(ctx)
}
}()
2024-05-22 06:15:11 +02:00
return txwrap.WithTx(ctx, globalDB, fn)
}
func WithTxRtn[RT any](ctx context.Context, fn func(tx *TxWrap) (RT, error)) (rtnVal RT, rtnErr error) {
2024-08-20 23:56:48 +02:00
waveobj.ContextUpdatesBeginTx(ctx)
defer func() {
if rtnErr != nil {
2024-08-20 23:56:48 +02:00
waveobj.ContextUpdatesRollbackTx(ctx)
} else {
2024-08-20 23:56:48 +02:00
waveobj.ContextUpdatesCommitTx(ctx)
}
}()
2024-05-22 06:15:11 +02:00
return txwrap.WithTxRtn(ctx, globalDB, fn)
}