-
Notifications
You must be signed in to change notification settings - Fork 124
/
quick-start.go
118 lines (92 loc) · 2.49 KB
/
quick-start.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
package main
import (
"database/sql"
"encoding/json"
"fmt"
"os"
_ "github.com/lib/pq"
// dot import so that jet go code would resemble as much as native SQL
// dot import is not mandatory
. "github.com/go-jet/jet/v2/examples/quick-start/.gen/jetdb/dvds/table"
. "github.com/go-jet/jet/v2/postgres"
"github.com/go-jet/jet/v2/examples/quick-start/.gen/jetdb/dvds/model"
)
const (
host = "localhost"
port = 5432
user = "jet"
password = "jet"
dbName = "jetdb"
)
func main() {
// Connect to database
var connectString = fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", host, port, user, password, dbName)
db, err := sql.Open("postgres", connectString)
panicOnError(err)
defer db.Close()
// Write query
stmt := SELECT(
Actor.ActorID, Actor.FirstName, Actor.LastName, Actor.LastUpdate,
Film.AllColumns,
Language.AllColumns.Except(Language.LastUpdate),
Category.AllColumns,
).FROM(
Actor.
INNER_JOIN(FilmActor, Actor.ActorID.EQ(FilmActor.ActorID)).
INNER_JOIN(Film, Film.FilmID.EQ(FilmActor.FilmID)).
INNER_JOIN(Language, Language.LanguageID.EQ(Film.LanguageID)).
INNER_JOIN(FilmCategory, FilmCategory.FilmID.EQ(Film.FilmID)).
INNER_JOIN(Category, Category.CategoryID.EQ(FilmCategory.CategoryID)),
).WHERE(
Language.Name.EQ(Char(20)("English")).
AND(Category.Name.NOT_EQ(Text("Action"))).
AND(Film.Length.GT(Int(180))),
).ORDER_BY(
Actor.ActorID.ASC(),
Film.FilmID.ASC(),
)
// Execute query and store result
var dest []struct {
model.Actor
Films []struct {
model.Film
Language model.Language
Categories []model.Category
}
}
err = stmt.Query(db, &dest)
panicOnError(err)
printStatementInfo(stmt)
jsonSave("./dest.json", dest)
// New Destination
var dest2 []struct {
model.Category
Films []model.Film
Actors []model.Actor
}
err = stmt.Query(db, &dest2)
panicOnError(err)
jsonSave("./dest2.json", dest2)
}
func jsonSave(path string, v interface{}) {
jsonText, _ := json.MarshalIndent(v, "", "\t")
err := os.WriteFile(path, jsonText, 0600)
panicOnError(err)
}
func printStatementInfo(stmt SelectStatement) {
query, args := stmt.Sql()
fmt.Println("Parameterized query: ")
fmt.Println("==============================")
fmt.Println(query)
fmt.Println("Arguments: ")
fmt.Println(args)
debugSQL := stmt.DebugSql()
fmt.Println("\n\nDebug sql: ")
fmt.Println("==============================")
fmt.Println(debugSQL)
}
func panicOnError(err error) {
if err != nil {
panic(err)
}
}