Search code examples
postgresqlgoprepared-statement

IN Lookup Postgres query in prepared statement, Golang


The use case requires running of exclusion queries. Something like:

select col1 
from awesome_table 
where col2 not in (a,b,c,d) 
and col3 not in (a1,a2,a3,a4);

As the set of excluded col1 values and excluded col2 values is variable sized, what is a good way to generate the prepared statement? One hack that I can think of is to define an upper limit on the set say 15 and fill all placeholders with repeated values if number of query set size input by user is less than max value, is there a better way? And how are prepared statements suppose to handle this, as per the philosophy of the community?


Solution

  • Adding to @a_horse_with_no_name's answer, In Golang, the psql driver github.com/lib/pq contains a method Array() that can be used to convert a Golang slice into a psql Array.

    ...
    
    import (
    "github.com/lib/pq"
    )
    
    ...
    
    select col1 
    from awesome_table 
    where col2 <> ALL ($1) 
      and col3 <> ALL ($2);
    
    
    

    where

    slice1 := []string{val1, val2}
    slice2 := []string{val3, val4}
    

    pq.Array(slice1) can be passed for $1 and pq.Array(slice2) can be passed for $2 placeholder while passing the values in the prepared statements.

    More about ANY and ALL functions can be found at here