-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathexamples_test.go
82 lines (63 loc) · 1.39 KB
/
examples_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
package dotsql_test
import (
"database/sql"
"log"
"github.com/qustavo/dotsql"
)
func ExampleLoadFromFile() {
db, err := sql.Open("sqlite3", ":memory:")
if err != nil {
panic(err)
}
dot, err := dotsql.LoadFromFile("queries.sql")
if err != nil {
panic(err)
}
/* queries.sql looks like:
-- name: create-users-table
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
name VARCHAR(255),
email VARCHAR(255)
);
-- name: create-user
INSERT INTO users (name, email) VALUES(?, ?)
-- name: find-users-by-email
SELECT id,name,email FROM users WHERE email = ?
-- name: find-one-user-by-email
SELECT id,name,email FROM users WHERE email = ? LIMIT 1
--name: drop-users-table
DROP TABLE users
*/
// Exec
if _, err := dot.Exec(db, "create-users-table"); err != nil {
panic(err)
}
if _, err := dot.Exec(db, "create-user", "[email protected]"); err != nil {
panic(err)
}
// Query
rows, err := dot.Query(db, "find-users-by-email", "[email protected]")
if err != nil {
panic(err)
}
defer rows.Close()
for rows.Next() {
var id int
var name, email string
err = rows.Scan(&id, &name, &email)
if err != nil {
panic(err)
}
log.Println(email)
}
// QueryRow
row, err := dot.QueryRow(db, "find-one-user-by-email", "[email protected]")
if err != nil {
panic(err)
}
var id int
var name, email string
row.Scan(&id, &name, &email)
log.Println(email)
}