postgresqlgosqlx

Go SQLX sqlx.DB Get("sql_function") does not return any value


This is my function:

func (a *AirlinesRepository) Get(id int) *models.Airline {
   airline := models.Airline{}

   a.DB.Get(&airline, "SELECT * FROM fn_airlines_getby_id(?)", id)

   return &airline
}

After executing DB.Get, airline has all the properties set with zero value instead of being populated with the sql function result. I Also tried with "SELECT fn_airlines_getby_id(?)" and "fn_airlines_getby_id(?)"

Airline has the properties:

type Airline struct {
  Id   int64  `db:"id"`
  Name string `db:"name"`
}

And the function is as follows:

CREATE OR REPLACE FUNCTION fn_airlines_getby_id(p_id INT)
RETURNS TABLE (id INT, name VARCHAR) AS
$$
BEGIN
    RETURN QUERY
    SELECT a.id AS id, a.name AS name FROM airlines as a WHERE a.id = p_id;
END
$$ LANGUAGE plpgsql;

UPDATE: Looking at the Postgres's logs I found the next:

ERROR:  syntax error at or near ")" at character 30
STATEMENT:  SELECT fn_airlines_getby_id(?)

So seems that sqlx is not parsing the value that should go instead of ? (It works well with normal queries)

This is a Postgres database and the function exists.


Solution

  • Use Postgres's parameter placeholder instead of sqlx one. Change from

    SELECT fn_airlines_getby_id(?)
    

    To:

    SELECT * FROM fn_airlines_getby_id($1)