hasura: treat empty strings as nulls

Viewed 155

I'm using Hasura as backend for react app.

In my SQL table I set up a field, let's say "identification_number" as [text, unique, nullable]. So identification_number might be null, but if it is not null, it should be unique across the table.

But sometimes fronted sends me data with an empty string as a value of my field.

{
  name: "asdfomw",
  year: "2010",
  identification_number: "",
  description: "some description"
}

In this situation Hasura successfully adds record to database. But if an empty string is present in the payload for some other record, I get an error of "unique violation", because there are two records with equal identification_number having values of "".

So I think of two possible solutions for this problem:

  1. Automatic conversion of empty-strings to nulls.
  2. Adding constraints to Hasura scheme, not allowing empty strings for certain columns.

And I don't have answers for any of this questions.

1 Answers

You can add constraints like that in permissions if you'd like. That might be a bit too hacky of a solution.

The real question here is why are you allowing the frontend to upload values with an empty string if the backend does not accept that? Fail early. In your front end you can do the conversion or throw an error.

If you must do the conversion server side, you can write an event trigger to listen for insert/updates to this table and convert those values as they are inserted. I imagine you might still have issues if you try to insert several in one transaction with the same empty string value. You can also run into race conditions but I don't know for certain...

Related