-
Notifications
You must be signed in to change notification settings - Fork 88
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 pass an array as a one parameter? #22
Comments
Arrays are handles the same as any other type of parameter as far as the PostgreSQL server and the pgconn library are concerned. But pgconn is probably lower level than you want. I would suggest you might want to go up a layer and use https://github.com/jackc/pgx instead. With pgx you can do something like: ary := []string{"foo", "bar", "baz"}
... := conn.Query(ctx, "select * from table where value in ($1)", ary) |
@jackc the example above doesn't work. |
@zuckermanori Nothing has changed, but it looks look I made a mistake with the SQL. It should be |
Thanks @jackc I changed from |
I cant get this to work, however I want to do it. I'm using pgx I have tried the following:
in both cases I get the following error: Replacing What is weird that the same code works without // both prefix and suffix are empty strings in my testcases
builder.AddSlice(values, func(nums []int) string {
return fmt.Sprintf("%s%s = ARRAY[ %s ]%s", prefix, prop, strings.Join(util.SQLParams(nums), ","), suffix)
})
package util
import "strconv"
type SQLBuilder struct {
offset int
expr []string
params []any
}
func NewSQLBuilder(offset int) *SQLBuilder {
return &SQLBuilder{
offset: offset,
expr: make([]string, 0),
params: make([]any, 0),
}
}
func (b *SQLBuilder) Add(v any, expr func(int) string) {
b.expr = append(b.expr, expr(b.offset+len(b.params)))
b.params = append(b.params, v)
}
func (b *SQLBuilder) AddSlice(v []any, expr func([]int) string) {
l := len(b.params)
nums := make([]int, len(v))
for i := 0; i < len(nums); i++ {
nums[i] = b.offset + l + i
}
b.expr = append(b.expr, expr(nums))
b.params = append(b.params, v...)
}
func (b *SQLBuilder) Get() ([]string, []any) {
return b.expr, b.params
}
func SQLParam(num int) string {
return "$" + strconv.Itoa(num)
}
func SQLParams(nums []int) []string {
values := make([]string, len(nums))
for i := 0; i < len(nums); i++ {
values[i] = SQLParam(nums[i])
}
return values
} I'm a bit lost what to try out now, especially since it works without The full code can be viewed here: gw2auth/gw2auth.com-api@5cc4e98 most importantly the func |
Sorry for the confusion. I'm migrating from a Java project and it turns out anything in the chain I'm using on the Java side adds support for CockroachDB has a containment operator |
how to pass an array as a one parameter?
select * from table where value in ($1)
$1=['val1', 'val2'.....]
The text was updated successfully, but these errors were encountered: