-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
example_test.go
379 lines (340 loc) · 8.9 KB
/
example_test.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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
// Copyright 2021 Roxy Light
// SPDX-License-Identifier: ISC
package sqlite_test
import (
"bytes"
"context"
"fmt"
"io"
"regexp"
"time"
"golang.org/x/text/collate"
"golang.org/x/text/language"
"zombiezen.com/go/sqlite"
"zombiezen.com/go/sqlite/sqlitex"
)
func Example() {
// Open an in-memory database.
conn, err := sqlite.OpenConn(":memory:")
if err != nil {
// handle error
}
defer conn.Close()
// Execute a query.
err = sqlitex.ExecuteTransient(conn, "SELECT 'hello, world';", &sqlitex.ExecOptions{
ResultFunc: func(stmt *sqlite.Stmt) error {
fmt.Println(stmt.ColumnText(0))
return nil
},
})
if err != nil {
// handle error
}
// Output:
// hello, world
}
// This is the same as the main package example, but uses the SQLite
// statement API instead of sqlitex.
func Example_withoutX() {
// Open an in-memory database.
conn, err := sqlite.OpenConn(":memory:")
if err != nil {
// handle error
}
defer conn.Close()
// Prepare a statement.
stmt, _, err := conn.PrepareTransient("SELECT 'hello, world';")
if err != nil {
// handle error
}
// Transient statements must always be finalized.
defer stmt.Finalize()
for {
row, err := stmt.Step()
if err != nil {
// handle error
}
if !row {
break
}
fmt.Println(stmt.ColumnText(0))
}
// Output:
// hello, world
}
func ExampleConn_SetInterrupt() {
conn, err := sqlite.OpenConn(":memory:")
if err != nil {
panic(err)
}
defer conn.Close()
// You can use the Done() channel from a context to set deadlines and timeouts
// on queries.
ctx, cancel := context.WithTimeout(context.TODO(), 100*time.Millisecond)
defer cancel()
conn.SetInterrupt(ctx.Done())
}
// This example shows how to register a basic scalar function.
//
// If you're looking to use regular expressions in your application,
// use [zombiezen.com/go/sqlite/ext/refunc.Register].
func ExampleConn_CreateFunction() {
conn, err := sqlite.OpenConn(":memory:")
if err != nil {
// handle error
}
defer conn.Close()
// Add a regexp(pattern, string) function.
err = conn.CreateFunction("regexp", &sqlite.FunctionImpl{
NArgs: 2,
Deterministic: true,
Scalar: func(ctx sqlite.Context, args []sqlite.Value) (sqlite.Value, error) {
re, err := regexp.Compile(args[0].Text())
if err != nil {
return sqlite.Value{}, fmt.Errorf("regexp: %w", err)
}
found := 0
if re.MatchString(args[1].Text()) {
found = 1
}
return sqlite.IntegerValue(int64(found)), nil
},
})
if err != nil {
// handle error
}
matches, err := sqlitex.ResultBool(conn.Prep(`SELECT regexp('fo+', 'foo');`))
if err != nil {
// handle error
}
fmt.Println("First matches:", matches)
matches, err = sqlitex.ResultBool(conn.Prep(`SELECT regexp('fo+', 'bar');`))
if err != nil {
// handle error
}
fmt.Println("Second matches:", matches)
// Output:
// First matches: true
// Second matches: false
}
// This example shows the same regexp function as in the CreateFunction example,
// but it uses auxiliary data to avoid recompiling the regular expression.
//
// This is the implementation used in [zombiezen.com/go/sqlite/ext/refunc].
func ExampleContext_AuxData() {
conn, err := sqlite.OpenConn(":memory:")
if err != nil {
// handle error
}
defer conn.Close()
// Add a regexp(pattern, string) function.
usedAux := false
err = conn.CreateFunction("regexp", &sqlite.FunctionImpl{
NArgs: 2,
Deterministic: true,
Scalar: func(ctx sqlite.Context, args []sqlite.Value) (sqlite.Value, error) {
// First: attempt to retrieve the compiled regexp from a previous call.
re, ok := ctx.AuxData(0).(*regexp.Regexp)
if ok {
usedAux = true
} else {
// Auxiliary data not present. Either this is the first call with this
// argument, or SQLite has discarded the auxiliary data.
var err error
re, err = regexp.Compile(args[0].Text())
if err != nil {
return sqlite.Value{}, fmt.Errorf("regexp: %w", err)
}
// Store the auxiliary data for future calls.
ctx.SetAuxData(0, re)
}
found := 0
if re.MatchString(args[1].Text()) {
found = 1
}
return sqlite.IntegerValue(int64(found)), nil
},
})
if err != nil {
// handle error
}
const query = `WITH test_strings(i, s) AS (VALUES (1, 'foo'), (2, 'bar')) ` +
`SELECT i, regexp('fo+', s) FROM test_strings ORDER BY i;`
err = sqlitex.ExecuteTransient(conn, query, &sqlitex.ExecOptions{
ResultFunc: func(stmt *sqlite.Stmt) error {
fmt.Printf("Match %d: %t\n", stmt.ColumnInt(0), stmt.ColumnInt(1) != 0)
return nil
},
})
if err != nil {
// handle error
}
if usedAux {
fmt.Println("Used aux data to speed up query!")
}
// Output:
// Match 1: true
// Match 2: false
// Used aux data to speed up query!
}
func ExampleBlob() {
// Create a new database with a "blobs" table with a single column, "myblob".
conn, err := sqlite.OpenConn(":memory:")
if err != nil {
// handle error
}
defer conn.Close()
err = sqlitex.ExecuteTransient(conn, `CREATE TABLE blobs (myblob blob);`, nil)
if err != nil {
// handle error
}
// Insert a new row with enough space for the data we want to insert.
const dataToInsert = "Hello, World!"
err = sqlitex.ExecuteTransient(
conn,
`INSERT INTO blobs (myblob) VALUES (zeroblob(?));`,
&sqlitex.ExecOptions{
Args: []any{len(dataToInsert)},
},
)
if err != nil {
// handle error
}
// Open a handle to the "myblob" column on the row we just inserted.
blob, err := conn.OpenBlob("", "blobs", "myblob", conn.LastInsertRowID(), true)
if err != nil {
// handle error
}
_, writeErr := blob.WriteString(dataToInsert)
closeErr := blob.Close()
if writeErr != nil {
// handle error
}
if closeErr != nil {
// handle error
}
// Read back the blob.
var data []byte
err = sqlitex.ExecuteTransient(conn, `SELECT myblob FROM blobs;`, &sqlitex.ExecOptions{
ResultFunc: func(stmt *sqlite.Stmt) error {
data = make([]byte, stmt.ColumnLen(0))
stmt.ColumnBytes(0, data)
return nil
},
})
if err != nil {
// handle error
}
fmt.Printf("%s\n", data)
// Output:
// Hello, World!
}
func ExampleConn_SetAuthorizer() {
// Create a new database.
conn, err := sqlite.OpenConn(":memory:")
if err != nil {
// handle error
}
defer conn.Close()
// Set an authorizer that prevents any mutations.
err = conn.SetAuthorizer(sqlite.AuthorizeFunc(func(action sqlite.Action) sqlite.AuthResult {
typ := action.Type()
if typ == sqlite.OpSelect ||
typ == sqlite.OpRead ||
// Permit function calls.
typ == sqlite.OpFunction ||
// Permit transactions.
typ == sqlite.OpTransaction ||
typ == sqlite.OpSavepoint {
return sqlite.AuthResultOK
}
return sqlite.AuthResultDeny
}))
if err != nil {
// handle error
}
// Authorizers operate during statement preparation, so this will succeed:
stmt, _, err := conn.PrepareTransient(`SELECT 'Hello, World!';`)
if err != nil {
panic(err)
} else {
fmt.Println("Read-only statement prepared!")
if err := stmt.Finalize(); err != nil {
panic(err)
}
}
// But this will not:
stmt, _, err = conn.PrepareTransient(`CREATE TABLE foo (id INTEGER PRIMARY KEY);`)
if err != nil {
fmt.Println("Prepare CREATE TABLE failed with code", sqlite.ErrCode(err))
} else if err := stmt.Finalize(); err != nil {
panic(err)
}
// Output:
// Read-only statement prepared!
// Prepare CREATE TABLE failed with code SQLITE_AUTH
}
// This example shows how to use a changegroup to produce similar results to
// a call to ConcatChangesets.
func ExampleChangegroup() {
// Get changesets from somewhere.
var changeset1, changeset2 io.Reader
// Create a changegroup.
grp := new(sqlite.Changegroup)
defer grp.Clear()
// Add changesets to the changegroup.
if err := grp.Add(changeset1); err != nil {
// Handle error
}
if err := grp.Add(changeset2); err != nil {
// Handle error
}
// Write the changegroup to a buffer.
output := new(bytes.Buffer)
if _, err := grp.WriteTo(output); err != nil {
// Handle error
}
}
func ExampleConn_SetCollation() {
// Create a new database.
conn, err := sqlite.OpenConn(":memory:")
if err != nil {
// handle error
}
defer conn.Close()
// Override the built-in NOCASE collating sequence
// to be Unicode aware.
nocaseCollator := collate.New(language.Und, collate.IgnoreCase)
if err := conn.SetCollation("NOCASE", nocaseCollator.CompareString); err != nil {
// handle error
}
// Create a table that uses the NOCASE collating sequence.
err = sqlitex.ExecuteScript(conn, `
CREATE TABLE foo (mytext TEXT COLLATE NOCASE);
INSERT INTO foo VALUES
('atext'),
('btext'),
('ctext'),
('ątext'),
('ćtext');
`, nil)
if err != nil {
// handle error
}
// The column will be implicitly ordered using its collating sequence.
err = sqlitex.ExecuteTransient(conn, `SELECT mytext FROM foo ORDER BY mytext ASC;`, &sqlitex.ExecOptions{
ResultFunc: func(stmt *sqlite.Stmt) error {
fmt.Println(stmt.ColumnText(0))
return nil
},
})
if err != nil {
// handle error
}
// Output:
// atext
// ątext
// btext
// ctext
// ćtext
}