How to put a not null constraint on a custom type?

Viewed 36

A lot of my tables must be timestamped, so my idea was to define a custom type, and to create my tables with columns from this type:

CREATE TYPE timestamped AS (
    created_at timestamp NOT NULL,
    updated_at timestamp NOT NULL,
    deleted_at timestamp
);

CREATE TABLE IF NOT EXISTS objects (
    LIKE timestamped INCLUDING ALL,
    id uuid NOT NULL PRIMARY KEY,
    -- etc.
);

There is a syntax error on the NOT NULL:

LINE 2:     created_at timestamp NOT NULL,
                                 ^

How can I say that this value must be defined?

1 Answers

Unfortunately, user-defined types don't allow constraints.

But, user-defined domains do. So you can do what you want as:

CREATE DOMAIN required_timestamp as timestamp
    check (value is not null);

CREATE TYPE timestamped AS (
    created_at required_timestamp,
    updated_at required_timestamp,
    deleted_at timestamp
);
Related