pgroll/examples/23_drop_check_constraint.json
Andrew Farries 31402f9f7a
Implement the drop_constraint operation (#103)
Implement the `drop_constraint` operation for dropping constraints
defined on single columns.

An example of the operation looks like:

```json
{
  "name": "23_drop_check_constraint",
  "operations": [
    {
      "drop_constraint": {
        "table": "posts",
        "column": "title",
        "name": "title_length",
        "up": "title",
        "down": "(SELECT CASE WHEN length(title) <= 3 THEN LPAD(title, 4, '-') ELSE title END)"
      }
    }
  ]
}
```

for dropping a `CHECK` constraint. And like this for dropping a `FOREIGN
KEY` constraint:


```json
{
  "name": "24_drop_foreign_key_constraint",
  "operations": [
    {
      "drop_constraint": {
        "table": "posts",
        "column": "user_id",
        "name": "fk_users_id",
        "up": "user_id",
        "down": "(SELECT CASE WHEN EXISTS (SELECT 1 FROM users WHERE users.id = user_id) THEN user_id ELSE NULL END)"
      }
    }
  ]
}
```

The operation works very similarly to the inverse operation of adding
`CHECK` and `FOREIGN KEY` constraints to a single column.

* On `Start`:
* a new column without the constraint is added to the underlying table.
* triggers are created using the `up` and `down` SQL. The `down` SQL
needs to ensure that rows inserted into the new view that don't meet the
constraint are converted into rows that do meet the constraint.
* On `Complete`
* Triggers are removed, the old column is deleted and the new column is
renamed.
* On `Rollback`
  * The new column and the triggers are removed.  

## Improvements
* The `drop_constraint` operation requires that the column on which the
constraint is defined is named in the migration `json` file. If
`pg-roll`'s internal schema representation knew about the constraints
defined on a table it would be possible to delete constraints by
constraint name only; the schema representation would know on which
column the constraint was defined.
* `pg-roll` currently only allows for creating `CHECK` and `FOREIGN KEY`
constraints on single columns; this limitation also applies to the
`drop_constraint` operation.
2023-09-19 05:32:53 +01:00

15 lines
315 B
JSON

{
"name": "23_drop_check_constraint",
"operations": [
{
"drop_constraint": {
"table": "posts",
"column": "title",
"name": "title_length",
"up": "title",
"down": "(SELECT CASE WHEN length(title) <= 3 THEN LPAD(title, 4, '-') ELSE title END)"
}
}
]
}