简体   繁体   English

如何在多租户数据库中使字段NOT NULL

[英]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. 所有记录都有一个客户ID,以分隔客户数据。 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. 因此,将整个字段设置为非null无效。 I need to set a field null for a specific client id. 我需要为特定的客户端ID设置一个字段为null。

I am currently querying the database to check if the value is null. 我目前正在查询数据库,以检查该值是否为null。 On INSERT I check if the inserting value is null if so I throw an error. 在INSERT上,我检查插入值是否为null,否则抛出错误。 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. 另外,我需要有关SQL Server,oracle和postgresql的建议。 Thanks 谢谢

With Postgresql at least you could do this with table inheritance . 至少在Postgresql中,您可以通过表继承做到这一点。

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. 在这种情况下,表“ b”继承自“ a”,但对列“ foo”具有不同的定义,包括非空约束。 Also note that I have used a check constraint to ensure that only records for client 1 can go into this table. 还要注意,我使用了检查约束来确保只有客户端1的记录才能进入该表。

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. 您的应用程序仍然可以对父表(在我的示例中为“ a”)进行查询,并获取所有客户端的记录,包括子表中的任何记录。

You won't be able to do this with a column constraint. 您将无法使用列约束来执行此操作。 Think you're going to have to write a trigger . 认为您将不得不编写触发器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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