Skip to content

Arguments to SQL functions are nullable by default #940

Open
@breml

Description

@breml

While working on a solution for #364 which is based on SQL functions, I hit the following problem.

Arguments for SQL functions in PostgreSQL are nullable by default. With CALLED ON NULL INPUT, this can even be explicitly stated, but this is ignored by sqlc.

Given the following definition for PostgreSQL:

CREATE TABLE foo (
            id     INTEGER,
            bar    varchar(100)
);

INSERT INTO foo VALUES (null, 'foo'), (1, 'bar');

CREATE OR REPLACE FUNCTION select1(_id INTEGER)
  RETURNS SETOF foo as
$func$
BEGIN
  IF _id IS NULL THEN
    RETURN QUERY EXECUTE 'select * from foo where id IS NULL';
  ELSE
    RETURN QUERY EXECUTE FORMAT('select * from foo where id = %L', _id);
  END IF;
END
$func$ LANGUAGE plpgsql CALLED ON NULL INPUT;

the following SQL calls are valid:

select select1(null);
select select1(1);

With the query definition:

-- name: GetSelect1 :many
SELECT select1($1);

the following Go method signature is generated:

func (q *Queries) GetSelect1(ctx context.Context, ID int32) ([]interface{}, error) {

With this method signature it is not possible to pass nil (or SQL null) as argument for ID.

Update: fix typo

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions