-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdriver.go
More file actions
60 lines (52 loc) · 1.37 KB
/
driver.go
File metadata and controls
60 lines (52 loc) · 1.37 KB
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
package sqliteha
import (
"context"
"database/sql"
"database/sql/driver"
"fmt"
"sync"
"github.com/litesql/go-ha"
"modernc.org/sqlite"
)
func init() {
sql.Register("sqlite-ha", &Driver{})
}
type Driver struct {
once sync.Once
ConnectionHook sqlite.ConnectionHookFn
Options []ha.Option
}
func (d *Driver) Open(name string) (driver.Conn, error) {
connector, err := d.OpenConnector(name)
if err != nil {
return nil, err
}
return connector.Connect(context.Background())
}
func (d *Driver) OpenConnector(name string) (driver.Connector, error) {
dsn, opts, err := ha.NameToOptions(name)
if err != nil {
return nil, fmt.Errorf("invalid params: %w", err)
}
opts = append(opts, d.Options...)
var drv sqlite.Driver
d.once.Do(func() {
if d.ConnectionHook != nil {
drv.RegisterConnectionHook(d.ConnectionHook)
}
})
return ha.NewConnector(dsn, &drv, func(cfg ha.ConnHooksConfig) ha.ConnHooksProvider {
return newConnHooksProvider(cfg)
}, Backup, opts...)
}
func NewConnector(name string, opts ...ha.Option) (*ha.Connector, error) {
dsn, nameOpts, err := ha.NameToOptions(name)
if err != nil {
return nil, fmt.Errorf("invalid params: %w", err)
}
opts = append(opts, nameOpts...)
var drv sqlite.Driver
return ha.NewConnector(dsn, &drv, func(cfg ha.ConnHooksConfig) ha.ConnHooksProvider {
return newConnHooksProvider(cfg)
}, Backup, opts...)
}