Skip to content

Allow for check constraints in shorthands #1183

@Apreche

Description

@Apreche

Description

Consider this check constraint example from the postgres documentation.

CREATE TABLE products (
    product_no integer,
    name text,
    price numeric CONSTRAINT positive_price CHECK (price > 0)
);

You can make this table in node-pg-migrate like so:

pgm.createTable("mytable", {
    product_no: "integer",
    name: "text",
    price: {
        type: "numeric",
        check: "price > 0"
    }
});

But what if you wanted to have price fields with the same constraint on many tables? That's a perfect case for creating a shorthand for the price column.

exports.shorthands = {
    price: {
        type: "numeric",
        check: "price > 0"
    }
};

There's a huge problem here. What if someone wants to make a column of type price, but the column name isn't literally price?

pgm.createTable("mytable", {
    retail_price: "price"
});

This isn't going to work because you would need check: "retail_price > 0", but the shorthand just has price > 0

Suggested solution

When writing a check constraint in a shorthand, there should be some way to template the column name. I don't know what the syntax would be, this is just the first thing that came to mind without putting much thought into it.

exports.shorthands = {
    price: {
        type: "numeric",
        check: "${columnname} > 0"
    }
};

Alternative

Maybe the shorthands could be written using the shorthand, but then node-pg-migrate will intelligently replace the shorthand name in the constraint with the actual column name. Then this original example would actually work.

exports.shorthands = {
    price: {
        type: "numeric",
        check: "price > 0"
    }
};

It seems like this would be complicated and prone to danger, however, because you might have a situation like this

exports.shorthands = {
    price: {
        type: "numeric",
        check: "prices > 0"
    }
};

In which you do not want to replace price.

Additional context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions