sql.Scan error with PostgreSQL TEXT[] array: "unsupported Scan, storing driver.Value type string into type *[]string" when using pgx/v4 with database/sql
#2397
-
|
I'm getting a scan error when trying to retrieve a PostgreSQL Error: {
"error": "sql: Scan error on column index 4, name \"tags\": unsupported Scan, storing driver.Value type string into type *[]string"
}Database Schema: CREATE TABLE IF NOT EXISTS posts (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL,
title VARCHAR(255) NOT NULL,
content TEXT NOT NULL,
tags TEXT[],
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP NOT NULL,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP NOT NULL
);Go Struct: type Post struct {
ID int64 `json:"id"`
Title string `json:"title"`
Content string `json:"content"`
UserID int64 `json:"user_id"`
Tags []string `json:"tags"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}Code that fails (GetByID method): func (s *PostStore) GetByID(ctx context.Context, id int64) (*Post, error) {
query := `
SELECT id, title, content, user_id, tags, created_at, updated_at
FROM posts
WHERE id = $1
`
post := &Post{}
err := s.db.QueryRowContext(ctx, query, id).Scan(
&post.ID,
&post.Title,
&post.Content,
&post.UserID,
&post.Tags,
&post.CreatedAt,
&post.UpdatedAt,
)
if err != nil {
return nil, err
}
return post, nil
}What I've tried:
How can I properly scan PostgreSQL Any help would be greatly appreciated! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
In Unfortunately, in neither version can you directly scan to a |
Beta Was this translation helpful? Give feedback.
v4is no longer supported and I would recommend upgrading tov5. But if I recall correctly, the way you would do this inv4is with thepgtype.TextArray.In
v5you would use https://pkg.go.dev/github.com/jackc/pgx/v5@v5.7.6/pgtype#Map.SQLScanner.Unfortunately, in neither version can you directly scan to a
[]string. However, thanks to golang/go#67546, in future versions of Go and pgx you will be able to directly scan to[]stringand other slice types directly with database/sql / stdlib.