graphql-engine

This note is in Hasura.GraphQL.Schema.BoolExp.

Nullability in comparison operators

In comparisonExps, we hardcode most operators with Nullability False when calling column, which might seem a bit sketchy. Shouldn’t the nullability depend on the nullability of the underlying Postgres column?

No. If we did that, then we would allow boolean expressions like this:

delete_users(where: {status: {eq: null}})

which in turn would generate a SQL query along the lines of:

DELETE FROM users WHERE users.status = NULL

but = NULL might not do what they expect. For instance, on Postgres, it always evaluates to False!

Even operators for which null is a valid value must be careful in their implementation. An explicit null must always be handled explicitly! If, instead, an explicit null is ignored:

foo <- fmap join $ fieldOptional "_foo_level" $ nullable int

then

   delete_users(where: {_foo_level: null})
=> delete_users(where: {})
=> delete_users()

Now we’ve gone and deleted every user in the database. Whoops! Hopefully the user had backups!

In most cases, as mentioned above, we avoid this problem by making the column value non-nullable (which is correct, since we never treat a null value as a SQL NULL), then creating the field using ‘fieldOptional’. This creates a parser that rejects nulls, but won’t be called at all if the field is not specified, which is permitted by the GraphQL specification. See Note [The value of omitted fields] in Hasura.GraphQL.Parser.Internal.Parser for more details.

Additionally, it is worth nothing that the column parser does handle explicit nulls, by creating a Null column value.

But… the story doesn’t end there. Some of our users WANT this peculiar behaviour. For instance, they want to be able to express the following:

query($isVerified: Boolean) {
  users(where: {_isVerified: {_eq: $isVerified}}) {
    name
  }
}

$isVerified is True  -> return users who are verified
$isVerified is False -> return users who aren't
$isVerified is null  -> return all users

In the future, we will likely introduce a separate group of operators that do implement this particular behaviour explicitly; but for now we have an option that reverts to the previous behaviour.

To do so, we have to treat explicit nulls as implicit one: this is what the ‘nullable’ combinator does: it treats an explicit null as if the field has never been called at all.