aboutsummaryrefslogtreecommitdiff
path: root/db/db.go
blob: 5241cd15dfd9521ec9fda098bf862a0962881915 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package db

import (
	"context"
	"database/sql"
	"fmt"
	"log/slog"

	"github.com/uptrace/bun"
	"github.com/uptrace/bun/dialect/sqlitedialect"
)

func GetDB(dbFile string) (*bun.DB, error) {
	db, err := sql.Open("sqlite3", dbFile)
	if err != nil {
		return nil, fmt.Errorf("open db failed: %w", err)
	}

	orm := bun.NewDB(db, sqlitedialect.New())
	orm.AddQueryHook(&queryHook{})

	return orm, nil
}

type queryHook struct {
}

func (*queryHook) BeforeQuery(ctx context.Context, qe *bun.QueryEvent) context.Context {
	return ctx
}

func (*queryHook) AfterQuery(ctx context.Context, qe *bun.QueryEvent) {
	slog.Debug("query", slog.String("query", qe.Query))
}