Search code examples
pg-promise

{pg-promise} postgres - how to convert type int[] to be compatible with POINT()


So I'm using pg-promise to insert into a type POINT column. But it's giving me the following error:

function point(integer[]) does not exist

I'm passing the values as an array. What should I change to make it work?

Some code (not sure if useful):

simplified_query = `$${counter++}:name = POINT($${counter++})`

fields =
[
    "geolocation",
    [10, 10]
]

Solution

  • As per Custom Type Formatting, if your field is ['geolocation', [10, 10]], with the first value being the column name, you can use the following function:

    function asPoint(field) {
        return {
            rawType: true,
            toPostgres: () => pgp.as.format('$1:name = POINT($2:csv)', field)
        };
    }
    

    Then you can use asPoint(field) as a query-formatting parameter:

    const field = ['geolocation', [10, 10]];
    db.any('SELECT * FROM table WHERE $1', [asPoint(field)])
    //=> SELECT * FROM table WHERE "geolocation" = POINT(10, 10)
    

    Alternatively, your field can be a custom-type class that implements Custom Type Formatting either explicitly or via the prototype, in which case it can be used as a formatting parameter directly.