-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
76 lines (62 loc) · 1.61 KB
/
main.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
package main
import (
"context"
"github.com/jackc/pgtype"
"github.com/weinandt/go-base-projects/postgres/jsonb/postgres"
)
type Metadata struct {
Location string
}
type User struct {
ID string
Metadata Metadata
}
type CreateUserParams struct {
metadata pgtype.JSONB
}
const createQuery = `
INSERT INTO users ( metadata) VALUES ( $1 )`
func main() {
db, err := postgres.CreateDBPool()
if err != nil {
panic(err)
}
// Inserting happy path
var normalMetadata pgtype.JSONB
normalMetadata.Set(Metadata{
Location: "testLocation",
})
_ = db.QueryRowContext(context.Background(), createQuery, normalMetadata)
// Inserting default struct
var emptyMetadata pgtype.JSONB
emptyMetadata.Set(Metadata{})
_ = db.QueryRowContext(context.Background(), createQuery, emptyMetadata)
// Inserting golang nil.
_ = db.QueryRowContext(context.Background(), createQuery, nil)
// Inserting array.
var metadataArray pgtype.JSONB
metadataArray.Set([]Metadata{
Metadata{
Location: "first one",
},
Metadata{
Location: "second one",
},
})
_ = db.QueryRowContext(context.Background(), createQuery, metadataArray)
// Inserting array of pointers
var metadataArrayPointers pgtype.JSONB
metadataArrayPointers.Set([]*Metadata{
&Metadata{
Location: "first pointer one",
},
&Metadata{
Location: "second pointer one",
},
})
_ = db.QueryRowContext(context.Background(), createQuery, metadataArrayPointers)
// Inserting JSON null. Note this is not the same as a postgres null
var jsonNull pgtype.JSONB
jsonNull.Set([]byte("null"))
_ = db.QueryRowContext(context.Background(), createQuery, jsonNull)
}