knex: Support Typecasting Function Parameters (Postgis ST_Transform Bug)

I have come across a problem, with different solutions, but I would like to propose a feature that would allow the calling of functions to be typecasted in the parameterization.

First the code:

function ST_Transform(shape, srid)
    {
        let sridParam = '?';

        if (_.isNumber(srid))
        {
            sridParam += '::integer';
        }

        return knex.raw(`st_transform(?, ${sridParam})`, [shape, srid]);
    };

The Problem:

This is in a file called ‘postgis.js’ in my architecture. What it allows me to do is import postgis and call postgis.ST_Transform(geom, 4326). Originally this code was 1 line long that got wrapped up in a convenience function. That was until Postgis 2.3.0 dropped and they changed it so that ST_Transform now takes a string or an integer. This causes an error because parameterized raw statements do not get typecasted naturally.

The Solution:

If knex had a property that was .executeFunction() that:

  • Took a string representation of a function name.
  • An array of values to be passed in.
  • An array of typecastings to be used.

It could be a very clean implementation for executing functions with correct types which has been requested multiple times from other issues. If we could start a discussion about a good way to accomplish this via code it would be appreciated and I would happily help with the implementation.

About this issue

  • Original URL
  • State: open
  • Created 7 years ago
  • Reactions: 2
  • Comments: 17 (6 by maintainers)

Most upvoted comments

Didn’t want to just disappear on this issue or have it go cold. I will try and get some work in this weekend on a good proposal for changes (maybe even a pull request Chronos willing).

But in defense of @elhigu point wrapping this in your own Knex.raw helper class works just as well.

This discussion is mainly for “Is there a clean implementation that could be adapted to meet Knex’s standards and fit the overall model?” Which is actually fairly non-trivial when consideration is given to the different databases, typecastings, and syntactic sugars that can take place.

Sure. Give me a bit to work on it some more. I want to make sure I include the weird dichotomy between PLPGSQL and T-SQL function execution. So i’ll work up some good examples for you. Thanks for discussing this feature request.

@cprieger could you provide an example how the syntax would be when one uses this SQL function call wrapper?

I have thought about it many times, but I’ve always ended up thinking that it is not worth of effort, because in this case knex.raw syntax would have been easier and more flexible than using some other wrapper method.

So I’m interested to see how some real world query would look like the way you have thought this feature.