-
Notifications
You must be signed in to change notification settings - Fork 0
/
driver_sqlite.go
110 lines (85 loc) · 2.21 KB
/
driver_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
// +build !disable_driver_sqlite
package sqlstorage
import (
"database/sql"
"fmt"
"regexp"
"strings"
"facette.io/maputil"
"facette.io/sliceutil"
"github.com/jinzhu/gorm"
"github.com/mattn/go-sqlite3"
"github.com/pkg/errors"
)
const (
defaultSqliteDriverPath = "data.db"
)
// sqliteDriver implements the database driver interface for SQLite 3.
type sqliteDriver struct {
path string
}
func (d sqliteDriver) Name() string {
return "sqlite3"
}
func (d sqliteDriver) Open() (*sql.DB, error) {
return sql.Open("sqlite3_ext", d.path)
}
func (d sqliteDriver) Init(db *gorm.DB) error {
// Enable 'foreign_key' pragma
return db.Exec("PRAGMA foreign_keys = ON").Error
}
func (d sqliteDriver) NormalizeError(err error) error {
sqliteErr, ok := err.(sqlite3.Error)
if !ok {
return err
}
switch sqliteErr.ExtendedCode {
case sqlite3.ErrConstraintPrimaryKey, sqlite3.ErrConstraintUnique:
return ErrItemConflict
case sqlite3.ErrConstraintForeignKey:
return ErrUnknownReference
case sqlite3.ErrConstraintNotNull:
return ErrMissingField
}
return err
}
func (d sqliteDriver) WhereClause(column string, v interface{}) (string, interface{}) {
operator := "="
extra := ""
switch v.(type) {
case GlobModifier:
operator = "LIKE"
extra = " ESCAPE '\\'"
s := string(v.(GlobModifier))
s = strings.Replace(s, "%", "\\%", -1)
s = strings.Replace(s, "_", "\\_", -1)
s = strings.Replace(s, "*", "%", -1)
v = strings.Replace(s, "?", "_", -1)
case RegexpModifier:
operator = "REGEXP"
v = "(?i)" + string(v.(RegexpModifier))
case string:
if s := v.(string); s == "null" {
operator = "IS"
v = nil
}
}
return fmt.Sprintf("%s %s ?%s", column, operator, extra), v
}
func init() {
if !sliceutil.Has(sql.Drivers(), "sqlite3_ext") {
sql.Register("sqlite3_ext", &sqlite3.SQLiteDriver{
ConnectHook: func(c *sqlite3.SQLiteConn) error {
return c.RegisterFunc("regexp", regexp.MatchString, true)
},
})
}
drivers["sqlite"] = func(name string, settings *maputil.Map) (sqlDriver, error) {
var err error
d := &sqliteDriver{}
if d.path, err = settings.GetString("path", defaultSqliteDriverPath); err != nil {
return nil, errors.Wrap(err, "invalid \"path\" setting")
}
return d, nil
}
}