Skip to content

fix: drop and recreate views that read a column whose type changes (#707) - #716

Open
Staberman wants to merge 1 commit into
pgplex:mainfrom
Staberman:fix/alter-type-dependent-views
Open

Staberman wants to merge 1 commit into
pgplex:mainfrom
Staberman:fix/alter-type-dependent-views

Conversation

@Staberman

Copy link
Copy Markdown

Summary

ALTER COLUMN ... TYPE fails at apply with SQLSTATE 0A000 ("cannot alter type of a column used by a view or rule") when a view or materialized view reads the column. This happens even for a plain widening such as numeric(10,2) -> numeric(12,2) or varchar(50) -> varchar(100), and even when the view text does not change, because such a view was never in modifiedViews.

The plan now drops the dependent views first, alters the column, then recreates them.

Fixes #707

Changes

  • internal/diff/column.go: extract columnTypeChanged, the same check generateColumnSQL already uses to decide whether to emit ALTER COLUMN ... TYPE (type with modifiers, or collation).
  • internal/diff/table.go, internal/diff/diff.go: record TypeChangedColumns on the table diff. A view that reads such a column is marked RequiresRecreate, the same way views reading a re-created generated column are (GENERATED ALWAYS AS expression changes are ignored by plan #591). The pre-drop of regular views now also runs for tables with type changes, not only for dropped tables or columns (Bug: DROP COLUMN ordered before dependent view's DROP within same group, apply fails #444). Dependent views are dropped in dependency order and recreated by the existing modify-views phase, which also restores comments and grants.
  • New test testdata/diff/dependency/issue_707_alter_column_type_with_dependent_views: numeric and varchar widening, a join view, a view on a view, and a materialized view, with a comment and a grant.

Testing

  • The new case fails on main (diff mismatch, and apply fails with SQLSTATE 0A000) and passes with the fix:
    PGSCHEMA_TEST_FILTER="dependency/issue_707" go test ./internal/diff -run TestDiffFromFiles
    PGSCHEMA_TEST_FILTER="dependency/issue_707" go test ./cmd -run TestPlanAndApply
  • go test ./internal/diff ./internal/plan ./ir/..., the dependency/ plan-and-apply category, go vet ./... and gofmt pass.

Known limits: a view is matched textually (table name plus column name), so a same-named column of another table can cause a redundant drop and recreate. Type changes on inherited columns, and objects other than views that bind to the column, are not covered.

@greptile-apps

greptile-apps Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 2/5

[Medium impact] The change affects migration plans for schemas with column type changes and dependent views.

The PR needs fixes to the order of view drops and creates before merging.

Findings

  1. P1 Materialized view dependents block apply ▶
  2. P1 New views lose their source ▶
  3. P1 Old dependencies block view drops ▶

Summary

The PR records column type and collation changes, then recreates views that read those columns.

  • Views that read changed columns are recreated around the type change.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A[Find changed column types] --> B[Mark dependent views for recreation]
  B --> C[Drop views before their sources]
  C --> D[Alter column types]
  D --> E[Recreate source views]
  E --> F[Recreate dependent views]
  F --> G[Restore grants]
Loading

Reviews (1) · Last reviewed commit: "fix: drop and recreate views that read a..." · Reviewed by Greptile

Comment thread internal/diff/diff.go
if !viewDependsOnTable(view, td.Table.Schema, td.Table.Name) {
continue
}
if exprReferencesAnyColumn(view.Definition, td.RecreatedColumns) || exprReferencesAnyColumn(view.Definition, td.TypeChangedColumns) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Materialized view dependents block apply

A type change still fails when another view reads the affected materialized view. For example, with mv AS SELECT sum(total) FROM orders and v AS SELECT * FROM mv, the pre-drop phase emits DROP MATERIALIZED VIEW mv RESTRICT while v still exists. PostgreSQL rejects that drop before the column can change.

Only regular roots use preDropViewsWithDependents; materialized roots are dropped directly. Send both kinds through the ordered drop path so dependent views leave first.

Knowledge Base Used: Migration dependency ordering

Comment thread internal/diff/diff.go
destructiveTables = append(destructiveTables, d.droppedTables...)
for _, tableDiff := range d.modifiedTables {
if len(tableDiff.DroppedColumns) > 0 {
if len(tableDiff.DroppedColumns) > 0 || len(tableDiff.TypeChangedColumns) > 0 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 New views lose their source

A newly added view that reads a recreated view is created too early. For example, widening orders.total, keeping totals AS SELECT sum(total) FROM orders, and adding summary AS SELECT * FROM totals now drops totals before the create phase. That phase then tries to create summary while totals is missing, so apply fails.

Defer new views that read recreated views, including their chains, until those source views exist again.

Knowledge Base Used: Migration planning and diffing

Comment thread internal/diff/diff.go
destructiveTables = append(destructiveTables, d.droppedTables...)
for _, tableDiff := range d.modifiedTables {
if len(tableDiff.DroppedColumns) > 0 {
if len(tableDiff.DroppedColumns) > 0 || len(tableDiff.TypeChangedColumns) > 0 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Old dependencies block view drops

The new pre-drop path misses existing dependent views whose desired definition stops reading the recreated view. For example, if b currently reads a, but the migration changes b to return a constant while changing a column type read by a, the desired-state graph no longer lists b as a dependent. The plan tries to drop a while the live b still reads it, so RESTRICT fails.

Find and order drops from the old definitions, then recreate from the desired definitions.

Knowledge Base Used: Migration dependency ordering

…gplex#707)

ALTER COLUMN ... TYPE fails with SQLSTATE 0A000 while a view reads the column. Record the columns whose type or collation changes on the table diff and treat them like the columns re-created in pgplex#591: dependent views and materialized views (and views built on them) go through the existing pre-drop/recreate cycle.

Fixes pgplex#707
@Staberman
Staberman force-pushed the fix/alter-type-dependent-views branch from aa5260c to 4a63015 Compare November 24, 2026 12:55
@tianzhou
tianzhou requested a balanced review from Copilot November 24, 2026 14:51

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Critical dependency-ordering gaps can make migrations fail by creating views before their sources are rebuilt or dropping regular or materialized views while live dependents still reference them.

3 open issues
What changed in this PR

This PR addresses #707 by extending pgschema’s migration planning to drop and recreate dependent views around column type changes, including widening changes that leave view definitions unchanged.

Changes:

  • Shares type and collation change detection between column SQL generation and table comparison.
  • Marks affected views for recreation and enables early drops before type changes.
  • Adds regression fixtures covering regular, joined, nested, and materialized views, plus comment and grant restoration.
File Description
testdata/​diff/​dependency/​issue_707_alter_column_type_with_dependent_views/​plan.txt Expected human-readable migration plan.
testdata/​diff/​dependency/​issue_707_alter_column_type_with_dependent_views/​plan.sql Expected executable plan SQL.
testdata/​diff/​dependency/​issue_707_alter_column_type_with_dependent_views/​plan.json Expected structured migration steps.
testdata/​diff/​dependency/​issue_707_alter_column_type_with_dependent_views/​old.sql Initial columns and dependent views.
testdata/​diff/​dependency/​issue_707_alter_column_type_with_dependent_views/​new.sql Desired schema with widened columns.
testdata/​diff/​dependency/​issue_707_alter_column_type_with_dependent_views/​diff.sql Expected drop, alter, and recreate sequence.
internal/​diff/​table.go Records columns whose types change.
internal/​diff/​diff.go Extends view recreation and early-drop detection.
internal/​diff/​column.go Extracts shared type and collation comparison.

Review effort: Balanced

Comment thread internal/diff/diff.go
destructiveTables = append(destructiveTables, d.droppedTables...)
for _, tableDiff := range d.modifiedTables {
if len(tableDiff.DroppedColumns) > 0 {
if len(tableDiff.DroppedColumns) > 0 || len(tableDiff.TypeChangedColumns) > 0 {
Comment thread internal/diff/diff.go
destructiveTables = append(destructiveTables, d.droppedTables...)
for _, tableDiff := range d.modifiedTables {
if len(tableDiff.DroppedColumns) > 0 {
if len(tableDiff.DroppedColumns) > 0 || len(tableDiff.TypeChangedColumns) > 0 {
Comment thread internal/diff/diff.go
destructiveTables = append(destructiveTables, d.droppedTables...)
for _, tableDiff := range d.modifiedTables {
if len(tableDiff.DroppedColumns) > 0 {
if len(tableDiff.DroppedColumns) > 0 || len(tableDiff.TypeChangedColumns) > 0 {

This branch has not been deployed

No deployments
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

Successfully merging this pull request may close these issues.

Changing a column's type fails at apply when a view reads the column

2 participants