/
db.go
129 lines (103 loc) · 2.03 KB
/
db.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
// DB-related business logic
package main
import (
"database/sql"
"errors"
"fmt"
// "log"
"io/ioutil"
"os"
_ "github.com/mattn/go-sqlite3"
)
const sqlSchemaInit = `
create table stub (
id integer not null primary key AUTOINCREMENT,
name text,
request_method text,
request_uri text,
request text,
response text,
created datetime,
last_viewed datetime,
views int
);
`
// main db connection for app
var DefaultDb *Db
type Db struct {
DbName string
Connection *sql.DB
}
// MakeDefault sets current DB as default
func (d *Db) MakeDefault() {
DefaultDb = d // just specify as default DB
}
func (d *Db) Close() {
d.Connection.Close()
}
func (d *Db) Init() error {
if d.DbName == `` {
return errors.New(`DB name is no set`)
}
conn, err := sql.Open("sqlite3", d.DbName)
if err != nil {
return err
}
d.Connection = conn
return nil
}
// Reset resets database to its prestine format
func (d *Db) Reset() error {
if d.DbName == `` {
return errors.New(`DB name is no set`)
}
if d.Connection != nil {
d.Close() // close current connection
}
// remove current DB
os.Remove(d.DbName)
// reconnect
err := d.Init()
// defer db.Close()
if err != nil {
return errors.New(fmt.Sprintf("%q: %s\n", err, sqlSchemaInit))
}
_, err = d.Connection.Exec(sqlSchemaInit)
if err != nil {
return errors.New(fmt.Sprintf("%q: %s\n", err, sqlSchemaInit))
}
return nil
}
// ImportFromFile imports SQL from file
func (d *Db) ImportFromFile(path string) error {
if d.Connection == nil {
return errors.New(`DB connection is not set`)
}
if path == `` {
return errors.New(`Import file is not specified`)
}
file, err := os.Open(path)
if err != nil {
return err
}
sql, err := ioutil.ReadAll(file)
if err != nil {
return err
}
_, err = d.Connection.Exec(string(sql))
if err != nil {
return err
}
return nil
}
func NewDb(dbname string, setAsDefault bool) (*Db, error) {
db := &Db{DbName: dbname}
err := db.Init()
if err != nil {
return db, err
}
if setAsDefault {
db.MakeDefault()
}
return db, nil
}