Last active
July 25, 2018 11:17
-
-
Save ants/78fbc5d660d52956c73789bf98d597aa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE TABLE data (id serial primary key, name text, data jsonb); | |
INSERT INTO data (name, data) VALUES ('testing', '{"foo": 1, "bar": 2}'); | |
INSERT INTO data (name, data) DEFAULT VALUES; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ants@ants-ThinkPad:~/tmp/test-conn$ go run test.go | |
Output json for testing(1): {"Id":1,"Name":"testing","Data":{"bar":2,"foo":1}} | |
Unmarshaled to Id=1 Name=testing Data={"bar":2,"foo":1} | |
Output json for <null>(2): {"Id":2,"Name":null,"Data":null} | |
Unmarshaled to Id=2 Name=<null> Data=<<<NULL>>> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"fmt" | |
"database/sql" | |
_ "github.com/lib/pq" | |
"encoding/json" | |
) | |
type MyData struct { | |
Id int | |
Name *string | |
Data *json.RawMessage | |
} | |
func coalesce(input *string, default_value string) string { | |
if input == nil { | |
return default_value | |
} | |
return *input | |
} | |
func main() { | |
// In main part of the application | |
db, err := sql.Open("postgres", "dbname=postgres host=localhost sslmode=disable user=postgres") | |
defer db.Close() | |
checkErr(err) | |
// In single request | |
tx, err := db.BeginTx(context.Background(), &sql.TxOptions{sql.LevelRepeatableRead, false}) | |
checkErr(err) | |
rows, err := tx.Query("SELECT id, name, data FROM data") // Run query in that transaction | |
checkErr(err) | |
for rows.Next() { | |
var obj MyData | |
checkErr(rows.Scan(&obj.Id, &obj.Name, &obj.Data)) | |
jsonOut, err := json.Marshal(obj) | |
checkErr(err) | |
fmt.Printf("Output json for %v(%v): %v\n", coalesce(obj.Name, "<null>"), obj.Id, string(jsonOut)) | |
var obj2 MyData | |
checkErr(json.Unmarshal(jsonOut, &obj2)) | |
var data string | |
if obj2.Data != nil { | |
data = string(*obj2.Data) | |
} else { | |
data = "<<<NULL>>>" | |
} | |
fmt.Printf("Unmarshaled to Id=%v Name=%v Data=%s\n", obj2.Id, coalesce(obj2.Name, "<null>"), data) | |
} | |
// doStuffWith(rows) | |
rows.Close() | |
checkErr(tx.Commit()) | |
} | |
func checkErr(err error) { | |
if err != nil { | |
panic(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment