Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Check Constraints #1711

Closed
evantrimboli opened this issue Apr 22, 2021 · 1 comment
Closed

Check Constraints #1711

evantrimboli opened this issue Apr 22, 2021 · 1 comment
Labels
enhancement New feature or request

Comments

@evantrimboli
Copy link
Contributor

Is your feature request related to a problem? Please describe.
To keep data layer logic centralized, it would be nice to be able to specify check constraints on fields.

Describe the solution you'd like

@Entity()
class Product {
  @Property({
    check: (productMeta) => `${productMeta.price.dbName} >= 0`,
  })
  price!: number
}

The sql generated should be something like:

CREATE TABLE products (
    price numeric CHECK (price >= 0)
);

The productMeta would be some sort of construct to access the underlying column names to be able to construct the constraint according to the naming strategy. There are a few ways this could go down, not sure what would be most idiomatic.

Describe alternatives you've considered

  • They could be manually added to migrations
  • Handle these at the API layer

Additional context
N/A

@evantrimboli evantrimboli added the enhancement New feature or request label Apr 22, 2021
@DASPRiD
Copy link
Contributor

DASPRiD commented Jan 27, 2022

Check constraints can also be added to a table directly. This is actually how TypeORM did implement them. The resulting SQL from that usually looks something like this:

CREATE TABLE foo (
  price numeric NOT NULL,
  CONSTRAINT foo_bar CHECK (price >= 0)
)

This should be fairly easy to implement as a @Check annotation to the @Entity. We could basically allow the developer to write any SQL check expression, and then diff on the expression for migrations. This would also be the most flexible approach. For instance:

@Entity()
@Check('price >= 0')
class Foo {
  @Property()
  price : number;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants