Skip to content
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

export ParseArray #898

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open

Conversation

bleakley
Copy link

Fixes #602

This function is needed for writing custom Scan functions to parse a JSONB[] column.

@cbandy
Copy link
Contributor

cbandy commented Sep 24, 2019

Can you give an example of what you're trying to scan into? pq.Array() can be used if you are scanning into an array or slice.

@bleakley
Copy link
Author

What I'm trying to do is scan an array of arbitrary types. I'm representing it in the DB as JSONB[] column because it might be strings or floats or another type, so each element is a JSON scalar in an array.

@cbandy
Copy link
Contributor

cbandy commented Sep 26, 2019

When array support was added in #466, the parseArray implementation was the least desired aspect. I don't expect we should commit to it further by exporting it as-is.

The unexported parseArray function returns a slice of byte slices. You can achieve a similar result with the exported Array function and a small Scanner implementation. For example,

type Bytes []byte
func (b *Bytes) Scan(src interface{}) error {
  *b = append(*b, src.([]byte)...)
  return nil
}

var result []Bytes
err := db.QueryRow(`SELECT ARRAY['{}', '"a"', '9']::jsonb[]`).Scan(pq.Array(&result))

In your case, something like json.RawMessage might be more appropriate?

type JSONB json.RawMessage
func (j *JSONB) Scan(src interface{}) error {
  *j = append(*j, src.([]byte)...)
  return nil
}

var result []JSONB
err := db.QueryRow(`SELECT ARRAY['{}', '"a"', '9']::jsonb[]`).Scan(pq.Array(&result))

Keep in mind that all PostgreSQL arrays can contain nulls... You might be happiest with the built-in types:

var result []sql.NullString
err := db.QueryRow(`SELECT ARRAY['{}', '"a"', '9', NULL]::jsonb[]`).Scan(pq.Array(&result))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Export the function parseArray
2 participants