forked from kuroneko/gosqlite3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.go
294 lines (265 loc) · 6.39 KB
/
database.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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
package sqlite3
// #include "bundle/sqlite3.h"
import "C"
import "fmt"
import "os"
import "strconv"
import "syscall"
import "time"
type Errno int
func (e Errno) String() (err string) {
if err = errText[e]; err == "" {
err = fmt.Sprintf("errno %v", int(e))
}
return
}
const(
OK = Errno(iota)
ERROR
INTERNAL
PERM
ABORT
BUSY
LOCKED
NOMEM
READONLY
INTERRUPT
IOERR
CORRUPT
NOTFOUND
FULL
CANTOPEN
PROTOCOL
EMPTY
SCHEMA
TOOBIG
CONSTRAINT
MISMATCH
MISUSE
NOLFS
AUTH
FORMAT
RANGE
NOTDB
ROW = Errno(100)
DONE = Errno(101)
ENCODER = Errno(1000)
SAVEPOINT = Errno(1001)
)
var errText = map[Errno]string {
ERROR: "SQL error or missing database",
INTERNAL: "Internal logic error in SQLite",
PERM: "Access permission denied",
ABORT: "Callback routine requested an abort",
BUSY: "The database file is locked",
LOCKED: "A table in the database is locked",
NOMEM: "A malloc() failed",
READONLY: "Attempt to write a readonly database",
INTERRUPT: "Operation terminated by sqlite3_interrupt()",
IOERR: "Some kind of disk I/O error occurred",
CORRUPT: "The database disk image is malformed",
NOTFOUND: "NOT USED. Table or record not found",
FULL: "Insertion failed because database is full",
CANTOPEN: "Unable to open the database file",
PROTOCOL: "NOT USED. Database lock protocol error",
EMPTY: "Database is empty",
SCHEMA: "The database schema changed",
TOOBIG: "String or BLOB exceeds size limit",
CONSTRAINT: "Abort due to constraint violation",
MISMATCH: "Data type mismatch",
MISUSE: "Library used incorrectly",
NOLFS: "Uses OS features not supported on host",
AUTH: "Authorization denied",
FORMAT: "Auxiliary database format error",
RANGE: "2nd parameter to sqlite3_bind out of range",
NOTDB: "File opened that is not a database file",
ROW: "sqlite3_step() has another row ready",
DONE: "sqlite3_step() has finished executing",
ENCODER: "blob encoding failed",
SAVEPOINT: "invalid or unknown savepoint identifier",
}
type Database struct {
handle *C.sqlite3
Filename string
Flags C.int
Savepoints []interface{}
}
func TransientDatabase() (db *Database) {
return &Database{ Filename: ":memory:" }
}
func Open(filename string, flags... int) (db *Database, e os.Error) {
defer func() {
if x := recover(); x != nil {
db.Close()
db = nil
e = MISUSE
}
}()
db = &Database{ Filename: filename }
if len(flags) == 0 {
e = db.Open(C.SQLITE_OPEN_FULLMUTEX, C.SQLITE_OPEN_READWRITE, C.SQLITE_OPEN_CREATE)
} else {
e = db.Open(flags...)
}
return
}
func (db *Database) Open(flags... int) (e os.Error) {
if C.sqlite3_threadsafe() == 0 {
panic("sqlite library is not thread-safe")
}
if db.handle != nil {
e = CANTOPEN
} else {
db.Flags = 0
for _, v := range flags { db.Flags = db.Flags | C.int(v) }
if err := Errno(C.sqlite3_open_v2(C.CString(db.Filename), &db.handle, db.Flags, nil)); err != OK {
e = err
} else if db.handle == nil {
e = CANTOPEN
}
}
return
}
func (db *Database) Close() {
C.sqlite3_close(db.handle)
db.handle = nil
}
func (db *Database) LastInsertRowID() int64 {
return int64(C.sqlite3_last_insert_rowid(db.handle))
}
func (db *Database) Changes() int {
return int(C.sqlite3_changes(db.handle))
}
func (db *Database) TotalChanges() int {
return int(C.sqlite3_total_changes(db.handle))
}
func (db *Database) Error() os.Error {
return Errno(C.sqlite3_errcode(db.handle))
}
func (db *Database) Prepare(sql string, values... interface{}) (s *Statement, e os.Error) {
s = &Statement{ db: db, timestamp: time.Nanoseconds() }
if rv := Errno(C.sqlite3_prepare_v2(db.handle, C.CString(sql), -1, &s.cptr, nil)); rv != OK {
s, e = nil, rv
} else {
if len(values) > 0 {
e, _ = s.BindAll(values...)
}
}
return
}
func (db *Database) Execute(sql string, f... func(*Statement, ...interface{})) (c int, e os.Error) {
var st *Statement
st, e = db.Prepare(sql)
if e == nil {
c, e = st.All(f...)
}
if e == OK {
e = nil
}
return
}
func (db *Database) Begin() (e os.Error) {
_, e = db.Execute("BEGIN")
return
}
func (db *Database) Rollback() (e os.Error) {
_, e = db.Execute("ROLLBACK")
return
}
func (db *Database) Commit() (e os.Error) {
_, e = db.Execute("COMMIT")
return
}
func savepointID(id interface{}) (s string) {
switch id := id.(type) {
case string: s = id
case []byte: s = string(id)
case fmt.Stringer: s = id.String()
case int: s = strconv.Itoa(id)
case uint: s = strconv.Uitoa(id)
default: panic(SAVEPOINT)
}
return
}
func (db *Database) Mark(id interface{}) (e os.Error) {
if st, err := db.Prepare("SAVEPOINT ?", savepointID(id)); err == nil {
_, e = st.All()
} else {
e = err
}
return
}
func (db *Database) MergeSteps(id interface{}) (e os.Error) {
if st, err := db.Prepare("RELEASE SAVEPOINT ?", savepointID(id)); err == nil {
_, e = st.All()
} else {
e = err
}
return
}
func (db *Database) Release(id interface{}) (e os.Error) {
if st, err := db.Prepare("ROLLBACK TRANSACTION TO SAVEPOINT ?", savepointID(id)); err == nil {
_, e = st.All()
} else {
e = err
}
return
}
func (db *Database) SavePoints() (s []interface{}) {
s = make([]interface{}, len(db.Savepoints))
copy(s, db.Savepoints)
return
}
func (db *Database) Load(source *Database, dbname string) (e os.Error) {
if dbname == "" {
dbname = "main"
}
if backup, rv := NewBackup(db, dbname, source, dbname); rv == nil {
e = backup.Full()
} else {
e = rv
}
return
}
func (db *Database) Save(target *Database, dbname string) (e os.Error) {
return target.Load(db, dbname)
}
type Reporter chan *ProgressReport
type BackupParameters struct {
Target string
PagesPerStep int
QueueLength int
Interval int64
}
func (db *Database) Backup(p BackupParameters) (r Reporter, e os.Error) {
if target, e := Open(p.Target); e == nil {
if backup, e := NewBackup(target, "main", db, "main"); e == nil && p.PagesPerStep > 0 {
r = make(Reporter, p.QueueLength)
go func() {
defer target.Close()
defer backup.Finish()
defer close(r)
for {
report := &ProgressReport{
Source: db.Filename,
Target: p.Target,
Error: backup.Step(p.PagesPerStep),
Total: backup.PageCount(),
Remaining: backup.Remaining(),
}
r <- report
if e, ok := report.Error.(Errno); ok && !(e == OK || e == BUSY || e == LOCKED) {
break
}
if p.Interval > 0 {
syscall.Sleep(p.Interval)
}
}
}()
} else {
target.Close()
e = target.Error()
}
}
return
}