I have a main, parent table 'transaction_', which I would like to partition. I know that I can easily partition based on any of the fields listed in transaction_, including foreign keys, using the check constraint within any child table. Essentially what I would like to know is whether, in my check constraint, I can somehow refer to other fields in a table for which I have a foreign key. I would like to avoid having too many foreign keys from the seller and client tables in my transaction_ table as that seems like a lot of unnecessary duplication.

CREATE SEQUENCE transaction_id_seq;
CREATE TABLE transaction_ (
    transaction_id    bigint      PRIMARY KEY   DEFAULT nextval('transaction_id_seq'),
    seller_id         int         REFERENCES seller(id),
    client_id         int         REFERENCES client(id),
    purchase_date     date,
    purchase_time     time,
    price             real,
    quantity          int
);

CREATE TABLE seller (
    id                int         PRIMARY KEY,
    name              text,
    location          text,
    open_time         time,
    close_time        time
);

CREATE TABLE client (
    id                int         PRIMARY KEY,
    name              text,
    billing_suburb    text,
    billing_zipcode   int
);

So for example, I think that I can do the following:

CREATE TABLE transaction_client1_20130108 (
    CHECK ( client_id = 1 AND purchase_date = DATE '2013-01-08')
) INHERITS (transaction_);

I would like to do something like the following:

CREATE TABLE transaction_sellerZip90210_20130108 (
    CHECK ( client(billing_zipcode) = 90210 AND purchase_date = DATE '2013-01-08')
) INHERITS (transaction_);

Using the following but happy to update if that provides a better solution:

mydb=#SELECT version();
PostgreSQL 9.1.11 on x86_64-unknown-linux-gnu, compiled by gcc (Ubuntu/Linaro 4.8.1-10ubuntu9) 4.8.1, 64-bit
有帮助吗?

解决方案

whether, in my check constraint, I can somehow refer to other fields in a table for which I have a foreign key

Not directly. CHECK constraints may not contain subqueries. However, you can work around that by declaring a LANGUAGE SQL function that does the work you want and using that from the CHECK constraint.

This isn't safe, though. The query planner expects that a CHECK constraint will be accurate and truthful, and may make optimization decisions based on it. So it's not a good idea to trick the system by adding a roundabout constraint on another table.

Instead, I recommend using triggers to sanity-check things like this, enforcing the check at the time any DML is run.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top