-
-
Save broklyngagah/3041109279c0b1b636a5c8339a6912d4 to your computer and use it in GitHub Desktop.
Use JSON column with golang pgx driver.
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 ( | |
"fmt" | |
"encoding/json" | |
"github.com/jackc/pgx" | |
"log" | |
) | |
var schema = ` | |
CREATE TABLE person ( | |
first_name text, | |
last_name text, | |
contact JSON | |
);` | |
type Person struct { | |
FirstName string `db:"first_name"` | |
LastName string `db:"last_name"` | |
Contact map[string]string `db:"contact"` | |
} | |
func main() { | |
config := pgx.ConnConfig{ | |
Host: "localhost", | |
User: "test", | |
Password: "test", | |
Database: "test", | |
} | |
conn, err := pgx.Connect(config) | |
if err != nil { | |
log.Fatalln(err) | |
} | |
defer conn.Close() | |
// exec the schema or fail | |
_, err = conn.Exec("DROP TABLE IF EXISTS person;") | |
if err != nil { | |
panic(err) | |
} | |
_, err = conn.Exec(schema) | |
if err != nil { | |
panic(err) | |
} | |
var person Person | |
contact := map[string]string{"email": "[email protected]"} | |
contact_json, _ := json.Marshal(contact) | |
_, err = conn.Exec("INSERT INTO person (first_name, last_name, contact) VALUES ($1, $2, $3)", "Jason", "Moiron", contact_json) | |
if err != nil { | |
panic(err) | |
} | |
row := conn.QueryRow("SELECT first_name, last_name, contact FROM person LIMIT 1") | |
err = row.Scan(&person.FirstName, &person.LastName, &person.Contact) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Printf("%v", person) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment