ALTER TABLE rejected_events.rejected_events
ADD COLUMN tenant_id smallint NOT NULL DEFAULT 0;
ALTER TABLE rejected_events.rejected_events
ALTER COLUMN tenant_id DROP DEFAULT;
In my product, tenant_id is set to 0 and then removed in next command as well.
I wonder what would be the intention of this strange stuff.
2
Answers
Is this in a database migration/upgrade script?
The column is
tenant_id
so if previously there was only one user/tenant in the database it gives that tenant an id of 0.In the future though you want any queries to specify a tenant. So, you keep the
NOT NULL
but drop the default.This is done because:
A
DEFAULT
is always specified for a column, by default that value isNULL
per docs CREATE TABLEIf you ran:
you would get the error I showed above. Adding the
DEFAULT 0
satisfies theNOT NULL
constraint by adding0
to the field for each existing row in the table you are altering. ThenALTER COLUMN tenant_id DROP DEFAULT;
removes theDEFAULT
for subsequent INSERTs. At that point you have to make sure aNON-NULL
value is specified for the column.