summaryrefslogtreecommitdiff
path: root/sqlite.go
blob: bc3c7336c99a5a1ec26f6639222feccda07d363e (plain)
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
35
36
37
38
39
40
41
42
43
44
45
46
47
//go:build sqlite

package main

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

	sqldblogger "github.com/simukti/sqldb-logger"
)

type logger struct {
}

func (l logger) Log(ctx context.Context, level sqldblogger.Level, msg string, data map[string]interface{}) {
	attrs := make([]slog.Attr, 0, len(data))

	for k, v := range data {
		attrs = append(attrs, slog.Any(k, v))
	}

	var lvl slog.Level
	switch level {
	case sqldblogger.LevelDebug, sqldblogger.LevelTrace:
		lvl = slog.LevelDebug
	case sqldblogger.LevelInfo:
		lvl = slog.LevelInfo
	case sqldblogger.LevelError:
		lvl = slog.LevelError
	}

	slog.LogAttrs(ctx, lvl, msg, attrs...)
}

func openDB(_ string) *sql.DB {
	dsn := "test.sqlite"
	db, err := sql.Open(driverName, dsn)
	if err != nil {
		log.Fatal(err)
	}
	slog.SetLogLoggerLevel(slog.LevelDebug)
	return sqldblogger.OpenDriver(dsn, db.Driver(), logger{},
		sqldblogger.WithSQLQueryAsMessage(false),
		sqldblogger.WithMinimumLevel(sqldblogger.LevelTrace))
}