This repository has been archived by the owner on Feb 5, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sqlite.go
115 lines (95 loc) · 2.01 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package sqlite
import (
"database/sql"
"sync"
"github.com/deweppro/go-errors"
"github.com/deweppro/go-orm/schema"
_ "github.com/mattn/go-sqlite3" //nolint: golint
)
var (
_ schema.Connector = (*pool)(nil)
_ schema.ConfigInterface = (*Config)(nil)
)
type (
//Config pool of configs
Config struct {
Pool []Item `yaml:"sqlite"`
}
//Item config model
Item struct {
Name string `yaml:"name"`
File string `yaml:"file"`
}
pool struct {
conf schema.ConfigInterface
db map[string]*sql.DB
l sync.RWMutex
}
)
//List getting all configs
func (c *Config) List() (list []schema.ItemInterface) {
for _, item := range c.Pool {
list = append(list, item)
}
return
}
//GetName getting config name
func (i Item) GetName() string { return i.Name }
//GetDSN connection params
func (i Item) GetDSN() string { return i.File }
//Setup setting config conntections params
func (i Item) Setup(_ schema.SetupInterface) {}
//New init new sqlite connection
func New(conf schema.ConfigInterface) schema.Connector {
c := &pool{
conf: conf,
db: make(map[string]*sql.DB),
}
return c
}
//Dialect getting sql dialect
func (p *pool) Dialect() string {
return schema.SQLiteDialect
}
//Reconnect update connection to database
func (p *pool) Reconnect() error {
if err := p.Close(); err != nil {
return err
}
p.l.Lock()
defer p.l.Unlock()
for _, item := range p.conf.List() {
db, err := sql.Open("sqlite3", item.GetDSN())
if err != nil {
if er := p.Close(); er != nil {
return errors.Wrap(err, er)
}
return err
}
p.db[item.GetName()] = db
}
return nil
}
//Close closing connection
func (p *pool) Close() error {
p.l.Lock()
defer p.l.Unlock()
if len(p.db) > 0 {
for _, db := range p.db {
if err := db.Close(); err != nil {
return err
}
}
}
return nil
}
//Pool getting connection pool by name
func (p *pool) Pool(name string) (*sql.DB, error) {
p.l.RLock()
defer p.l.RUnlock()
db, ok := p.db[name]
if !ok {
return nil, schema.ErrPoolNotFound
}
return db, db.Ping()
}