2

I have this function in PostgreSQL:

CREATE FUNCTION it_exists(
  email text,
  name text
) RETURNS boolean AS $$
DECLARE
  _eva1 boolean;
  _eva2 boolean;
BEGIN
  _eva1 := EXISTS(SELECT * FROM tableA AS A WHERE A.email = $1::citext);
  _eva2 := EXISTS(SELECT * FROM tableB AS A WHERE A.name::citext = $2::citext);
  RETURN _eva1 OR _eva2;
END;
$$ LANGUAGE plpgsql STRICT SECURITY DEFINER;

It is translated into Postgraphile like this:

mutation MyMutation($email: String!, $name: String!) {
  itExists(
    input: { email: $email, name: $name }
  ) {
    boolean
  }
}

I'd wish to change "boolean" name to something like "result", any suggestion? Consider I have many functions with different return values.

2 Answers2

5

I think that Postgraphile does this to have its custom mutations follow the Relay specification which says

By convention, mutations are named as verbs, their inputs are the name with "Input" appended at the end, and they return an object that is the name with "Payload" appended.

So your custom mutation creates an ItExistsPayload type with only a single field on it instead of returning a GraphQL Boolean. In the future you might want to extend this payload object with more fields.

It is possible to rename that field by using the @resultFieldName smart tag. In your case:

COMMENT ON FUNCTION it_exists(text, text) IS '@resultFieldName result';
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

Try returning a table instead:

CREATE FUNCTION it_exists(
  email text,
  name text
) RETURNS TABLE (result boolean) AS $$ -- return TABLE type
DECLARE
  _eva1 boolean;
  _eva2 boolean;
BEGIN
  _eva1 := EXISTS(SELECT * FROM tableA AS A WHERE A.email = $1::citext);
  _eva2 := EXISTS(SELECT * FROM tableB AS A WHERE A.name::citext = $2::citext);
  RETURN QUERY SELECT _eva1 OR _eva2; -- modify RETURN to suit TABLE type
END;
$$ LANGUAGE plpgsql STRICT SECURITY DEFINER;
Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • [The docs](https://www.graphile.org/postgraphile/custom-mutations/) say "*A note on anonymous types: if you have a function that `RETURNS SETOF TABLE(a int, b text)` (an anonymous record type) then PostGraphile will not currently pick it up*" but this might be out of date since it's no longer listed in the function restrictions – Bergi Sep 28 '21 at 23:50