-
Notifications
You must be signed in to change notification settings - Fork 855
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How to use arrays with v5/stdlib #1779
Comments
You can pass Go arrays directly as query arguments. For scanning you need to use package main
import (
"database/sql"
"log"
"os"
"github.com/jackc/pgx/v5/pgtype"
_ "github.com/jackc/pgx/v5/stdlib"
)
func main() {
db, err := sql.Open("pgx", os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}
defer db.Close()
m := pgtype.NewMap()
uuidsIn := []pgtype.UUID{
{Bytes: [16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, Valid: true},
{Bytes: [16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, Valid: true},
}
var uuidsOut []pgtype.UUID
err = db.QueryRow("select $1::uuid[]", uuidsIn).Scan(m.SQLScanner(&uuidsOut))
if err != nil {
log.Fatal(err)
}
log.Println(uuidsOut)
} Output:
|
Got it! @jackc Do you have any plans to avoid using SQLScanner in future? It makes the data model layer not interoperable if different SQL drivers are in place. |
pgx supports |
Maybe the following code could help smbd: type Array[T any] []T
func (a *Array[T]) Scan(src any) error {
m := pgtype.NewMap()
v := (*[]T)(a)
t, ok := m.TypeForValue(v)
if !ok {
return fmt.Errorf("cannot convert to sql.Scanner: cannot find registered type for %T", a)
}
var bufSrc []byte
if src != nil {
switch src := src.(type) {
case string:
bufSrc = []byte(src)
case []byte:
bufSrc = src
default:
bufSrc = []byte(fmt.Sprint(bufSrc))
}
}
return m.Scan(t.OID, pgtype.TextFormatCode, bufSrc, v)
} |
Thanks @regeda, this works great for
|
I have queries that use |
Candidate solution: #2020 |
The documentation declares the following:
I'm trying to use the following:
However, I'm getting the following:
How to use arrays in both ways
Valuer
andScanner
?The text was updated successfully, but these errors were encountered: