-
Notifications
You must be signed in to change notification settings - Fork 0
/
sqlite.go
217 lines (202 loc) · 5.65 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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
/*
creatTime: 2020/11/10
creator: JustKeepSilence
github: https://github.com/JustKeepSilence
goVersion: 1.16
*/
package db
import (
"database/sql"
_ "github.com/mattn/go-sqlite3"
"golang.org/x/sync/errgroup"
)
// SQLite errors
type sqliteConnectionError struct {
ErrorInfo string
}
func (ct sqliteConnectionError) Error() string {
return ct.ErrorInfo
}
type sqliteExecutionError struct {
ErrorInfo string
}
func (se sqliteExecutionError) Error() string {
return se.ErrorInfo
}
type sqliteRowsError struct {
ErrorInfo string
}
func (sr sqliteRowsError) Error() string {
return sr.ErrorInfo
}
type sqliteTransactionError struct {
ErrorInfo string
}
func (st sqliteTransactionError) Error() string {
return st.ErrorInfo
}
// connect SQLite, if not exist then create
func connectSqlite(sqlitePath string) (*sql.DB, error) {
db, err := sql.Open("sqlite3", sqlitePath)
if db == nil {
return nil, sqliteConnectionError{"sqliteConnectionError: null sqlite pointer"}
}
if err != nil {
return nil, sqliteConnectionError{"sqliteConnectionError: " + err.Error()}
}
return db, nil
}
// query data from SQLite, the format of return value is: [{columnName1: value1, columnName2: value2}]
func query(sqlitePath, queryString string) ([]map[string]string, error) {
db, err := connectSqlite(sqlitePath)
if err != nil {
return nil, err
}
defer func(db *sql.DB) {
_ = db.Close()
}(db)
rows, err := db.Query(queryString)
if err != nil {
return nil, sqliteExecutionError{"sqliteExecutionError: " + err.Error()}
}
columnNames, _ := rows.Columns() // get column names
var scanColumns []interface{} // Store the address of the variable corresponding to each column to store the result of the Scan scan
var rowsData []map[string]string // store the data of rows
for i := 0; i < len(columnNames); i++ {
var columnName sql.NullString // see:https://golang.org/pkg/database/sql/#NullString
scanColumns = append(scanColumns, &columnName) //Create a new variable named columnName every time,
// and put its address in, so that every time Scan is called, the number in scanColumns will be updated
//correspondingly, scanColumns[index] in scanColumns is each index- in the corresponding database 1 column of data
}
for rows.Next() {
err := rows.Scan(scanColumns...)
if err != nil {
// Write each row of data to scanColumns
return nil, sqliteRowsError{"sqliteRowsError: " + err.Error()}
}
temp := make(map[string]string)
for index, scanColumnValue := range scanColumns {
ns := *(scanColumnValue.(*sql.NullString))
if ns.Valid {
// valid string
temp[columnNames[index]] = ns.String
} else {
// invalid string
temp[columnNames[index]] = "null"
}
}
rowsData = append(rowsData, temp)
}
return rowsData, nil
}
// insert items into group
func insertItems(sqlitePath, insertString string, rowValues ...[]string) error {
db, err := connectSqlite(sqlitePath)
if err != nil {
return sqliteConnectionError{"sqliteConnectionError: " + err.Error()}
}
tx, err := db.Begin()
if err != nil {
return sqliteTransactionError{"sqliteTransactionError: " + err.Error()}
}
stmt, err := tx.Prepare(insertString)
if err != nil {
return sqliteTransactionError{"sqliteTransactionError: " + err.Error()}
}
eg := errgroup.Group{}
for _, rowValue := range rowValues {
insertedRows := rowValue
eg.Go(func() error {
var data []interface{} // data to be inserted
for i := 0; i < len(insertedRows); i++ {
data = append(data, insertedRows[i]) // can't use []string as []interface directly
}
_, err := stmt.Exec(data...)
if err != nil {
/* fail in inserting data
tx.Rollback() is the key ,see https://github.com/mattn/go-sqlite3/issues/184
*/
//flagChan <- true
return sqliteExecutionError{"sqliteExecutionError: " + err.Error() + "\n"}
} else {
return nil
}
})
}
if err := eg.Wait(); err != nil {
defer func(tx *sql.Tx) {
_ = tx.Rollback()
}(tx)
defer func(db *sql.DB) {
_ = db.Close()
}(db)
defer func(stmt *sql.Stmt) {
_ = stmt.Close()
}(stmt)
return err
} else {
if err := tx.Commit(); err != nil {
defer func(tx *sql.Tx) {
_ = tx.Rollback()
}(tx)
defer func(db *sql.DB) {
_ = db.Close()
}(db)
defer func(stmt *sql.Stmt) {
_ = stmt.Close()
}(stmt)
return sqliteTransactionError{"sqliteTransactionError: " + err.Error()}
} else {
defer func(tx *sql.Tx) {
_ = tx.Rollback()
}(tx)
defer func(db *sql.DB) {
_ = db.Close()
}(db)
defer func(stmt *sql.Stmt) {
_ = stmt.Close()
}(stmt)
return nil
}
}
}
// update items with transaction
func updateItems(sqlitePath string, sqlStrings ...string) error {
db, err := connectSqlite(sqlitePath)
if err != nil {
return sqliteConnectionError{"sqliteConnectionError: " + err.Error()}
}
defer func(db *sql.DB) {
_ = db.Close()
}(db)
tx, err := db.Begin()
if err != nil {
return sqliteTransactionError{"sqliteTransactionError: " + err.Error()}
}
for _, sqlString := range sqlStrings {
if _, err := tx.Exec(sqlString, nil); err != nil {
_ = tx.Rollback()
return sqliteExecutionError{"sqliteExecutionError: " + err.Error()}
}
}
if err := tx.Commit(); err != nil {
return sqliteExecutionError{"sqliteExecutionError: " + err.Error()}
}
return nil
}
// update item
func updateItem(sqlitePath, sqlString string) (int64, error) {
db, err := connectSqlite(sqlitePath)
if err != nil {
return -1, sqliteConnectionError{"sqliteConnectionError: " + err.Error()}
}
defer func(db *sql.DB) {
_ = db.Close()
}(db)
r, err := db.Exec(sqlString, nil)
if err != nil {
return -1, sqliteConnectionError{"sqliteConnectionError: " + err.Error()}
}
e, _ := r.RowsAffected()
return e, nil
}