Given a table foos
created via the below query:
We write an insert query to confirm the test default uuid generation behaves correctly:
Running a select query to confirms the insert works as expected:
Excited this works we start writing the client code via our ORM of choice(ecto
for example) and find the below:
:o Woohoo why is foo.ref_id
nil
, well the ORM sends null
for properties not supplied.
In this post we would examine 2 possible approaches to solving this problem:
- Generate a uuid by hand and pass in the
ref_id
e.g:
- Write a database trigger that overrides
ref_id
if it is null
and sets it to a uuid
as expected, e.g:
BEFORE INSERT
guarantees that this trigger runs before the record is committed. So running the client code again:
Boom! now our client code behaves just as expected.
The solutions would work with ref_id
being NOT NULL
Thanks for reading!
PS: The queries above are all postgres specific but the idea should work across databases that comply with the sql standard.