Skip to content

Instantly share code, notes, and snippets.

@bodokaiser
Created August 9, 2019 08:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bodokaiser/1287d9183c8c6a5ac0f0134a0eaf88c2 to your computer and use it in GitHub Desktop.
Save bodokaiser/1287d9183c8c6a5ac0f0134a0eaf88c2 to your computer and use it in GitHub Desktop.
Example on how to sql/driver Scanner and Valuer interface with jackx/pgx.
package main
import (
"database/sql/driver"
"log"
"github.com/jackc/pgx"
"github.com/jackc/pgx/pgtype"
)
// Tags represents a collection of tags.
type Tags []string
// Scan implements sql/driver Scanner interface.
func (t *Tags) Scan(src interface{}) (err error) {
var ta pgtype.TextArray
err = ta.Scan(src)
if err != nil {
return
}
err = ta.AssignTo(t)
return
}
// Value implements sql/driver Scanner interface.
func (t Tags) Value() (driver.Value, error) {
var ta pgtype.TextArray
err := ta.Set(t)
if err != nil {
return nil, err
}
return ta.Value()
}
func main() {
var id int
var tags Tags
conn, err := pgx.Connect(pgx.ConnConfig{
User: "postgres",
Host: "localhost",
Database: "test",
})
if err != nil {
log.Fatalf("failed to connect to database: %v\n", err)
}
err = conn.QueryRow("SELECT id, tags FROM tags_table LIMIT 1").Scan(&id, &tags)
if err != nil {
log.Fatalf("failed to execute query and scan to tags: %v\n", err)
}
log.Printf("id: %v, tags: %v\n", id, tags)
}
create table if not exists tags_table (
"id" serial primary key,
"tags" text[] not null default '{}'
);
insert into tags_table (tags) values ('{"foo", "bar", "baz"}');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment