Skip to content

Instantly share code, notes, and snippets.

@pyramation
Last active October 9, 2020 15:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pyramation/aca86a2ef6893f195d3dd97a51a25c91 to your computer and use it in GitHub Desktop.
Save pyramation/aca86a2ef6893f195d3dd97a51a25c91 to your computer and use it in GitHub Desktop.

Let's say I have a table with a NOT NULL field.

The client does not need to set the property, because it will happen in a trigger before insert. While this works in postgres, we cannot do it yet with graphile (to my knowledge):

Example table:

CREATE SCHEMA awesome_schema;
CREATE TABLE awesome_schema.products (
  id uuid PRIMARY KEY DEFAULT uuid_generate_v4 (),
  name text NOT NULL,
  verified boolean NOT NULL
);

And here's a query where I only want to supply name, since verfied, while an important field, isn't something client should be setting:

mutation CreateProductMutation($name: String!) {
  createProduct(input: {product: {name: $name}}) {
    product {
      rowId
    }
  }
}

Problem

As you can imagine, this error happens: Field ProductInput.verified of required type Boolean! was not provided.

Option 1 - Use Default

CREATE TABLE awesome_schema.products (
  id uuid PRIMARY KEY DEFAULT uuid_generate_v4 (),
  name text NOT NULL,
  verified boolean NOT NULL DEFAULT FALSE
);

Problem with this solution: This may not always be possible, depending on the use case, like unique string that the db should create or some field that can safely be set on backend, but not client.

Option 2 - use @omit

comment on column awesome_schema.products.verified is
  E'@omit';

Problem with this solution: Now the client cannot even see it.

question, is there an Option 3?

is there another option that allows me to have my cake and eat it to? In other words, can I create a NOT NULL field that has:

  • ability for client to see and query for the field
  • prevent client from needing to supply it in a creation mutation
  • no default value set
CREATE SCHEMA my_schema;
CREATE TABLE my_schema.products (
id uuid PRIMARY KEY DEFAULT uuid_generate_v4 (),
name text NOT NULL,
verified boolean NOT NULL
);
comment on column my_schema.products.verified is
E'@omit insert';
CREATE FUNCTION my_schema.before_insert_trigger()
RETURNS TRIGGER
AS $$
BEGIN
NEW.verified = FALSE;
RETURN NEW;
END;
$$
LANGUAGE 'plpgsql';
CREATE TRIGGER before_insert_trigger BEFORE
INSERT
ON my_schema.products FOR EACH ROW
EXECUTE PROCEDURE my_schema.before_insert_trigger ();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment