If I have a table in Postgresql:
create table Education (
id integer references Profiles(id),
finished YearValue not null,
started YearValue,
qualification text,
schoolName text,
studiedAt integer references Organizations(id),
primary key (id)
);
I need to make a constraint so that either schoolName or studiedAt needs to not be null (one of them has to have information in it).
How do I do this?
You can use a check constraint e.g.
constraint chk_education check (schoolName is not null or studiedAt is not null)
From the manual:
A check constraint is the most generic constraint type. It allows you to specify that the value in a certain column must satisfy a Boolean (truth-value) expression.
Edit: Alternative to comply with Pithyless' interpretation:
constraint chk_education check ((schoolName is not null and studiedAt is null) or (schoolName is null and studiedAt is not null))
You can also use a trigger on update and insert to check that a rule is followed before allowing the data into the table. You would normally use this type of approach when the check constraint needs more complicated logic.
This is my solution for sequelize migration file in "up" function
queryInterface.addConstraint('Education', {
fields: ['schoolName', 'studiedAt'],
type: 'check',
name: 'schoolName_or_studiedAt_is_null',
where: { [Sequelize.Op.or]: [{ password: null }, { googleId: null }] },
}),
Related
I use this table in a PostgreSQL database:
create table if not exists "Service" (
_id uuid not null primary key,
service text not null,
"count" integer not null,
"date" timestamp with time zone,
team uuid,
organisation uuid,
"createdAt" timestamp with time zone not null,
"updatedAt" timestamp with time zone not null,
unique (service, "date", organisation),
foreign key ("team") references "Team"("_id"),
foreign key ("organisation") references "Organisation"("_id")
);
When I try an upsert with Sequelize with the following code, it throws an error:
Service.upsert({ team, date, service, organisation, count }, { returning: true })
Error is:
error: duplicate key value violates unique constraint "Service_service_date_organisation_key"
Key (service, date, organisation)= (xxx, 2022-12-30 01:00:00+01, 12345678-5f63-1bc6-3924-517713f97cc3) already exists.
But according to Sequelize documentation it should work: https://sequelize.org/docs/v6/other-topics/upgrade/#modelupsert
Note for Postgres users: If upsert payload contains PK field, then PK will be used as the conflict target. Otherwise first unique constraint will be selected as the conflict key.
How can I find this duplicate key error and get it work with the composite unique key: unique (service, "date", organisation)?
It looks like your problem is related to issue #13240.
If you're on Sequelize 6.12 or above, you should be able to use an explicit list of conflictFields:
Service.upsert(
{ team, date, service, organisation, count },
{ conflictFields: ["service", "date", "organisation"] },
{ returning: true }
)
References
Similar questions were asked on GitHub, see:
https://github.com/sequelize/sequelize/issues/13240
https://github.com/sequelize/sequelize/issues/13412
and they were not solved so far, so, as the time of this writing, this issue seems to be unresolved, so you will need to work-around it. Below I will provide a few ideas to solve this, but since I have never worked with Sequelize, it is possible that I have some syntax error or some misunderstanding. If so, please point it out and I'll fix it.
Approach 1: Querying by your unique key and inserting/updating by it
Post.findAll({
where: {
service: yourservice,
date: yourdate,
organization: yourorganization
}
});
And then insert if the result is empty, update otherwise.
Approach 2: Modifying your schema
Since your composite unique key is a candidate key, an option would be to remove your _id field and make your (service, "date", organization) unique.
Approach 3: Implement an insert trigger on your table
You could simply call insert from Sequelize and let a PostgreSQL trigger handle the upserting, see: How to write an upsert trigger in PostgreSQL?
Example trigger:
CREATE OR REPLACE FUNCTION on_before_insert_versions() RETURNS trigger
LANGUAGE plpgsql AS
$$BEGIN
IF pg_trigger_depth() = 1 THEN
INSERT INTO versions (key, version) VALUES (NEW.key, NEW.version)
ON CONFLICT (key)
DO UPDATE SET version = NEW.version;
RETURN NULL;
ELSE
RETURN NEW;
END IF;
END;$$;
You of course will need to change table and field names accordingly to your schema and command.
create table Game(
isOn boolean,
playHour int,
isOff boolean,
constraint ck_isOn_hour check ( ? )
);
Constraint : playHour is NULL when isOn = FALSE
Replace the '?' symbol with a valid check for the given constraint.
Any help is much appreciated.
This should do it:
constraint ck_isOn_hour check (isOn or (playHour is null and not isOn))
This can be simplified:
constraint ck_isOn_hour check (isOn or playHour is NULL)
First here's the relevant code:
create table customer(
customer_mail_address varchar(255) not null,
subscription_start date not null,
subscription_end date, check (subscription_end !< subcription start)
constraint pk_customer primary key (customer_mail_address)
)
create table watchhistory(
customer_mail_address varchar(255) not null,
watch_date date not null,
constraint pk_watchhistory primary key (movie_id, customer_mail_address, watch_date)
)
alter table watchhistory
add constraint fk_watchhistory_ref_customer foreign key (customer_mail_address)
references customer (customer_mail_address)
on update cascade
on delete no action
go
So i want to use a UDF to constrain the watch_date in watchhistory between the subscription_start and subscription_end in customer. I can't seem to figure it out.
Check constraints can't validate data against other tables, the docs say (emphasis mine):
[ CONSTRAINT constraint_name ]
{
...
CHECK [ NOT FOR REPLICATION ] ( logical_expression )
}
logical_expression
Is a logical expression used in a CHECK constraint and returns TRUE or
FALSE. logical_expression used with CHECK constraints cannot
reference another table but can reference other columns in the same
table for the same row. The expression cannot reference an alias data
type.
That being said, you can create a scalar function that validates your date, and use the scalar function on the check condition instead:
CREATE FUNCTION dbo.ufnValidateWatchDate (
#WatchDate DATE,
#CustomerMailAddress VARCHAR(255))
RETURNS BIT
AS
BEGIN
IF EXISTS (
SELECT
'supplied watch date is between subscription start and end'
FROM
customer AS C
WHERE
C.customer_mail_address = #CustomerMailAddress AND
#WatchDate BETWEEN C.subscription_start AND C.subscription_end)
BEGIN
RETURN 1
END
RETURN 0
END
Now add your check constraint so it validates that the result of the function is 1:
ALTER TABLE watchhistory
ADD CONSTRAINT CHK_watchhistory_ValidWatchDate
CHECK (dbo.ufnValidateWatchDate(watch_date, customer_mail_address) = 1)
This is not a direct link to the other table, but a workaround you can do to validate the date. Keep in mind that if you update the customer dates after the watchdate insert, dates will be inconsistent. The only way to ensure full consistency in this case would be with a few triggers.
I want to add a NOT NULL contstraint to one of my table fields but only when another field has a certain value.
So I have a services table:
services:
- id
- professional_id
- is_master
I want to write a SQL constraint that whenever is_master is false professional_id cannot be null. I've tried things like:
CREATE TABLE "services" (
"id" text NOT NULL,
"professional_id" text REFERENCES professionals ON DELETE CASCADE ON UPDATE CASCADE,
EXCLUDE USING gist (
professional_id WITH =,
) WHERE (NOT is_master),
"is_master" boolean NOT NULL DEFAULT false,
PRIMARY KEY ("id")
);
What is the correct way to write this SQL?
You can do this with a check constraint. A simple one is:
constraint chk_services_master_professions
check (is_master or professional_id is not null)
Note: This version assumes that is_master is never NULL -- or that NULL is equivalent to "false".
check (not is_master and professional_id is not null or is_master)
You could use CHECK constraint:
CREATE TABLE "services" (
"id" text NOT NULL,
"professional_id" text
CHECK (CASE WHEN "is_master" IS FALSE AND "professional_id" IS NULL
THEN FALSE ELSE TRUE END), -- and rest of FK
"is_master" boolean NOT NULL DEFAULT false,
PRIMARY KEY ("id")
);
Rextester Demo
INSERT INTO services
VALUES (1,1, FALSE);
INSERT INTO services
VALUES (2,1, true);
INSERT INTO services
VALUES (3, null, true);
INSERT INTO services
VALUES (4, null, false);
23514: new row for relation "services" violates check constraint "services_check"
I use SQL Server 2008
I use a CHECK CONSTRAINT on multiple columns in the same table to try to validate data input.
I receive an error:
Column CHECK constraint for column
'AAAA' references another column,
table 'XXXX'.
CHECK CONSTRAINT does not work in this way.
Any other way to implement this on a single table without using FK?
Thanks
Here an example of my code
CREATE TABLE dbo.Test
(
EffectiveStartDate dateTime2(2) NOT NULL,
EffectiveEndDate dateTime2(2) NOT NULL
CONSTRAINT CK_CmsSponsoredContents_EffectiveEndDate CHECK (EffectiveEndDate > EffectiveStartDate),
);
Yes, define the CHECK CONSTRAINT at the table level
CREATE TABLE foo (
bar int NOT NULL,
fred varchar(50) NOT NULL,
CONSTRAINT CK_foo_stuff CHECK (bar = 1 AND fred ='fish')
)
You are declaring it inline as a column constraint
...
fred varchar(50) NOT NULL CONSTRAINT CK_foo_fred CHECK (...)
...
Edit, easier to post than describe. Fixed your commas.
CREATE TABLE dbo.Test
(
EffectiveStartDate dateTime2(2) NOT NULL,
EffectiveEndDate dateTime2(2) NOT NULL, --need comma
CONSTRAINT CK_CmsSponsoredContents_EffectiveEndDate CHECK (EffectiveEndDate > EffectiveStartDate) --no comma
);
Of course, the question remains are you using a CHECK constraint where it should be an FK constraint...?
Check constraints can refer to a single column or to the whole record.
Use this syntax for record-level constraints:
ALTER TABLE MyTable
ADD CONSTRAINT MyCheck
CHECK (...your check expression...)
You can simply apply your validation in a trigger on the table especially that either way the operation will be rolled back if the check failed.
I found it more useful for CONSTRAINT using case statements.
ALTER TABLE dbo.ProductStock
ADD
CONSTRAINT CHK_Cost_Sales
CHECK ( CASE WHEN (IS_NOT_FOR_SALE=0 and SAL_CPU <= SAL_PRICE) THEN 1
WHEN (IS_NOT_FOR_SALE=1 ) THEN 1 ELSE 0 END =1 )