Reputation: 283
I have a table with 3 columns A(, B, C) and have 2 constraints
e.g Data set
a1 : b1 : False
a1 : b2 : True
a1 : b3 : False
a2 : b1 : True
a2 : b2 : False
a2 : b3 : False
Upvotes: 3
Views: 1462
Reputation: 10260
I don't think this can be expressed in a database-portable way without changing the schema. Partial index can do this:
CREATE UNIQUE INDEX One_C_Per_A_Idx ON Table(A) WHERE C;
But it is only available on PostgreSQL and SQL Server (and simulated with functional index on Oracle). With PostgreSQL back-end you can use postgresql_where
keyword argument to Index
(see docs) to define partial index in SQLAlchemy.
A portable way is to split this into at least two tables, converting explicit boolean column into an implicit "present in the referencing table" expression. SQL:
CREATE TABLE my_table (
a integer NOT NULL,
b integer NOT NULL,
PRIMARY KEY (a, b)
);
CREATE TABLE flagged (
a integer NOT NULL PRIMARY KEY,
b integer NOT NULL,
FOREIGN KEY (a, b) REFERENCES my_table(a, b)
);
Query to get equivalent of the original table:
SELECT t.a, t.b, f.a IS NOT NULL AS c
FROM my_table t LEFT OUTER JOIN flagged f ON t.a = f.a AND t.b = f.b;
I'll omit SQLAlchemy model definitions for now, because I am not sure which solution suits your needs the best.
Upvotes: 3