Created
August 9, 2019 08:14
-
-
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.
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 ( | |
"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) | |
} |
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 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