leafo/pgmoon

Attempting to encode an empty array results in "]"

Closed this issue · 3 comments

slice commented

I'm not sure if this is intentional, but encode_array simply returns "]" when the passed in table is empty, which causes an error in Postgresql.

I came across this error when trying to update a Postgresql array column in lapis:

-- ...
import array from require "lapis.db"

class Something extends Model
  some_method: =>
    @the_arr_column = array { } -- "["
    @update "the_arr_column" -- syntax error because "["

Instead, I had to do something like this:

  some_method: =>
    do_something!
    -- ...
    -- cannot do:
    -- @the_arr_column = array new_arr_column
    -- workaround: we know it's empty, but encode_array can't take empty tables.
    @the_arr_column = "{ }" if #new_arr_column == 0
    @update "the_arr_column"
leafo commented

It's definitely a bug. The reason why I held off adding an implementation is that there's no way to make an empty array literal without providing some kind of type. The string array notation auto-casting could would for inserts/updates, but would break in many other situations.

Is this something that users just need to know about, inherent in using PostgreSQL (or most typed databases for that matter)?

I can't speak to Lapis, but appending "::foo[]" is pretty common in queries.

leafo commented

Yup that would work for casting the string, but that doesn't solve the problem. An empty array has nothing in it to infer the type from, so wouldn't be able to provide a type for foo. I'm not sure if there is a clean fix for this. Minimally throwing an error on empty array instead of generating invalid sql seems like a good first step. The array constructor could optionally take a type as well