A library that simplifies access to PostgreSQL databases.
- Despite
go-postgresuses Jack Christensen'sPGXlibrary internally, it aims to act as a generic database driver likedatabase/sqland avoid the developer to use specificPGXtypes and routines. - Most of the commonly used types in Postgres can be mapped to standard Golang types including
time.Timefor timestamps (except Postgres' time with tz which is not supported) - When reading
JSON/JSONBfields, the code will try to unmarshall it into the destination variable. In order to just retrieve the json value as a string, add the::textsuffix to the field in theSELECTquery. - To avoid overflows on high
uint64values, you can store them inNUMERIC(24,0)fields. - When reading time-only fields, the date part of the
time.Timevariable is set toJanuary 1, 2000.
package main
import (
"context""github.com/randlabs/go-postgres"
)
typeDatastruct {
IdintNamestring
}
funcmain() {
ctx:=context.Background()
// Create database driverdb, err:=postgres.New(ctx, postgres.Options{
Host: "127.0.0.1",
Port: 5432,
User: "postgres",
Password: "1234",
Name: "sampledb",
})
iferr!=nil {
// ....
}
deferdb.Close()
// Insert some datadata:=Data{
Id: 1,
Name: "example",
}
_, err=db.Exec(ctx, `INSERT INTO test_table (id, name) VALUES ($1, $2)`, data.Id, data.Name)
iferr!=nil {
// ....
}
// Read itvarnamestringerr=db.QueryRow(ctx, `SELECT name FROM test_table WHERE id = $1)`, 1).Scan(&name)
iferr!=nil {
// ....ifpostgres.IsNoRowsError(err) {
// This should not happen. We cannot find the record we just inserted.
}
}
// ....
}See LICENSE file for details.