forked from dexidp/dex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sqlite.go
61 lines (48 loc) · 1.36 KB
/
sqlite.go
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package ent
import (
"context"
"crypto/sha256"
"strings"
"entgo.io/ent/dialect/sql"
_ "github.com/mattn/go-sqlite3" // Register sqlite driver.
"github.com/sgalsaleh/dex/v2/pkg/log"
"github.com/sgalsaleh/dex/v2/storage"
"github.com/sgalsaleh/dex/v2/storage/ent/client"
"github.com/sgalsaleh/dex/v2/storage/ent/db"
)
// SQLite3 options for creating an SQL db.
type SQLite3 struct {
File string `json:"file"`
}
// Open always returns a new in sqlite3 storage.
func (s *SQLite3) Open(logger log.Logger) (storage.Storage, error) {
logger.Debug("experimental ent-based storage driver is enabled")
// Implicitly set foreign_keys pragma to "on" because it is required by ent
s.File = addFK(s.File)
drv, err := sql.Open("sqlite3", s.File)
if err != nil {
return nil, err
}
// always allow only one connection to sqlite3, any other thread/go-routine
// attempting concurrent access will have to wait
pool := drv.DB()
pool.SetMaxOpenConns(1)
databaseClient := client.NewDatabase(
client.WithClient(db.NewClient(db.Driver(drv))),
client.WithHasher(sha256.New),
)
if err := databaseClient.Schema().Create(context.TODO()); err != nil {
return nil, err
}
return databaseClient, nil
}
func addFK(dsn string) string {
if strings.Contains(dsn, "_fk") {
return dsn
}
delim := "?"
if strings.Contains(dsn, "?") {
delim = "&"
}
return dsn + delim + "_fk=1"
}