-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
78 lines (68 loc) · 2.01 KB
/
main.go
File metadata and controls
78 lines (68 loc) · 2.01 KB
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
// Command examples is a runnable tour of the sqlpro API. Every section runs
// against a throwaway SQLite database, so you can read the code and the output
// side by side. It doubles as the worked-example basis for the package README.
//
// Run it with:
//
// go run ./examples
//
// Each section lives in its own file (crud.go, bulk_tags.go, null_json.go,
// placeholders.go, transactions.go) and is referenced from the README.
package main
import (
"context"
"fmt"
"log"
"net/url"
"os"
"path/filepath"
_ "modernc.org/sqlite"
"github.com/programmfabrik/sqlpro"
)
// openExampleDB opens a fresh SQLite database in a temp file. SQLite is used so
// the examples are self-contained; everything shown works the same against
// PostgreSQL (open with sqlpro.Open("postgres", dsn)).
func openExampleDB() (sqlpro.DB, func()) {
dbFile := filepath.Join(os.TempDir(), "sqlpro_examples.db")
_ = os.Remove(dbFile)
// modernc.org/sqlite is configured through DSN query parameters.
qv := url.Values{}
qv.Add("_pragma", "foreign_keys(1)")
qv.Add("_pragma", "busy_timeout(10000)")
qv.Add("_pragma", "journal_mode(WAL)")
qv.Add("_time_format", "sqlite")
db, err := sqlpro.Open("sqlite", dbFile+"?"+qv.Encode())
if err != nil {
log.Fatalf("open: %v", err)
}
return db, func() {
db.Close()
_ = os.Remove(dbFile)
}
}
func main() {
db, cleanup := openExampleDB()
defer cleanup()
ctx := context.Background()
sections := []struct {
name string
fn func(context.Context, sqlpro.DB) error
}{
{"crud", crudExample},
{"query forms", queryExample},
{"bulk", bulkExample},
{"struct tags", tagsExample},
{"null & json", nullJSONExample},
{"null annotations", nullAnnotationsExample},
{"placeholders & escaping", placeholderExample},
{"transactions", transactionExample},
{"introspection", introspectionExample},
}
for _, s := range sections {
fmt.Printf("\n==== %s ====\n", s.name)
if err := s.fn(ctx, db); err != nil {
log.Fatalf("%s: %v", s.name, err)
}
}
fmt.Println("\nall examples completed ✔")
}