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

Constraint columns not ordered #41

Open
TravisCardwell opened this issue May 27, 2022 · 0 comments
Open

Constraint columns not ordered #41

TravisCardwell opened this issue May 27, 2022 · 0 comments

Comments

@TravisCardwell
Copy link
Contributor

TravisCardwell commented May 27, 2022

Currently, TableConstrint columns are stored using Set, so the order is determined by Set.toList.

data TableConstraint
  = PrimaryKey ConstraintName (Set ColumnName)
  | ForeignKey ConstraintName TableName (Set (ColumnName, ColumnName)) ReferenceAction {- onDelete -} ReferenceAction {- onUpdate -}
  | Unique ConstraintName (Set ColumnName)
  deriving (Show, Eq, Ord, Generic)

This is a critical issue for PrimaryKey and Unique constraints because these constraints create indexes, for which column order is very important. For example, a primary key PRIMARY KEY (a, b, c) creates a unique index that behaves like Haskell type Map A (Map B (Map C Value)). Due to the use of Set, the columns may be out of order. In my project, I saw primary keys in reverse order, equivalent to Haskell type Map C (Map B (Map A Value)). A query to select all values for a given A and B performs well with the correct primary key order, but it performs terribly with the incorrect primary key order.

The use of Set for ForeignKey constraints does not result in incorrect constraints because PostgreSQL supports foreign key constraints with columns in any order. It is best practice to put the columns in natural order, however, so use of Set results in inelegant constraints in the schema.

To fix this issue, I changed all of the TableConstraint constructors to use Vector instead of Set to store the column information. With ordered columns, primary key and unique constraints are correct, and foreign key constraints maintain elegant column order. This is a breaking change; it may change the order of columns in constraints that have more than one column. I will submit a pull request with the fix.


tc-develop Documentation

TravisCardwell added a commit to TravisCardwell/beam-automigrate that referenced this issue May 27, 2022
This changes constraints to store columns using `Vector` instead of
`Set`, so that the order is maintained.  This is critically important
for primary key and unique constraints, and it improves the elegance of
foreign key constraints.  This is a breaking change.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant