forked from sqle/sqle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_test.go
66 lines (54 loc) · 1.43 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
package sqle_test
import (
"database/sql"
"fmt"
"gopkg.in/sqle/sqle.v0"
"gopkg.in/sqle/sqle.v0/mem"
gitqlsql "gopkg.in/sqle/sqle.v0/sql"
)
func Example() {
// Create a test memory database and register it to the default engine.
sqle.DefaultEngine.AddDatabase(createTestDatabase())
// Open a sql connection with the default engine.
conn, err := sql.Open(sqle.DriverName, "")
checkIfError(err)
// Prepare a query.
stmt, err := conn.Prepare(`SELECT name, count(*) FROM mytable
WHERE name = 'John Doe'
GROUP BY name`)
checkIfError(err)
// Get result rows.
rows, err := stmt.Query()
checkIfError(err)
// Iterate results and print them.
for {
if !rows.Next() {
break
}
name := ""
count := int64(0)
err := rows.Scan(&name, &count)
checkIfError(err)
fmt.Println(name, count)
}
checkIfError(rows.Err())
// Output: John Doe 2
}
func checkIfError(err error) {
if err != nil {
panic(err)
}
}
func createTestDatabase() *mem.Database {
db := mem.NewDatabase("test")
table := mem.NewTable("mytable", gitqlsql.Schema{
gitqlsql.Column{Name: "name", Type: gitqlsql.String},
gitqlsql.Column{Name: "email", Type: gitqlsql.String},
})
db.AddTable("mytable", table)
table.Insert(gitqlsql.NewRow("John Doe", "[email protected]"))
table.Insert(gitqlsql.NewRow("John Doe", "[email protected]"))
table.Insert(gitqlsql.NewRow("Jane Doe", "[email protected]"))
table.Insert(gitqlsql.NewRow("Evil Bob", "[email protected]"))
return db
}