简体   繁体   中英

How to make a field NOT NULL in a multi-tenant database

This is a muti-tenant app. All records have a client id to separate client data. Customers can insert their own data in this table and set their own field nullable or not null. Therefore, setting the whole field not null will not work. I need to set a field null for a specific client id.

I am currently querying the database to check if the value is null. On INSERT I check if the inserting value is null if so I throw an error. I would like the database to do all these checks. is this possible in a multi tenant database like this?

Also, I need suggestions for SQL Server, oracle and postgresql. Thanks

With Postgresql at least you could do this with table inheritance .

You could define an inherited table for this specific client which included the required constraint.

Consider the following example:

psql=> CREATE TABLE a(client INT NOT NULL, id SERIAL, foo TEXT);
CREATE TABLE

psql=> CREATE TABLE b(foo TEXT NOT NULL, CHECK (CLIENT=1) ) INHERITS (a);
NOTICE:  moving and merging column "foo" with inherited definition
DETAIL:  User-specified column moved to the position of the inherited column.
CREATE TABLE

psql=> INSERT INTO b(client,foo) VALUES (1,'a');
INSERT 0 1

psql=> INSERT INTO b(client,foo) VALUES (1,NULL);
ERROR:  null value in column "foo" violates not-null constraint
DETAIL:  Failing row contains (1, 2, null).

The table 'b' in this case inherits from 'a' but has a different definition for column 'foo' including a not-null constraint. Also note that I have used a check constraint to ensure that only records for client 1 can go into this table.

For this to work, either your application would have to be updated to insert client records into the correct table, or you would need to write a trigger that does that automatically. Examples of how to do that are given in the manual section on partitioning .

Your application can still make queries against the parent table ('a' from my example) and get the records for all clients, including any in child tables.

You won't be able to do this with a column constraint. Think you're going to have to write a trigger .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM