Skip to content

Commit

Permalink
sql: check replace view columns earlier
Browse files Browse the repository at this point in the history
Before this change, we could encounter internal errors while attempting
to add result columns during a `CREATE OR REPLACE VIEW` if the number of
columns in the new view was less than the number of columns in the old
view. This led to an inconsistency with postgres, which would only
return the error `cannot drop columns from view`.

This PR moves the check comparing the number of columns before and after
the view replacement earlier so that the correct error returns.

Co-authored-by: [email protected]

Fixes: #99000
Epic: None

Release note (bug fix): Fixes an internal error that can occur when
`CREATE OR REPLACE VIEW` replaces a view with fewer columns and another
entity depended on the view.
  • Loading branch information
craig[bot] authored and rharding6373 committed Mar 21, 2023
1 parent f0dfa0c commit b80feac
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
5 changes: 5 additions & 0 deletions pkg/sql/create_view.go
Original file line number Diff line number Diff line change
Expand Up @@ -596,6 +596,11 @@ func (p *planner) replaceViewDesc(
toReplace.ViewQuery = updatedQuery
}

// Check that the new view has at least as many columns as the old view before
// adding result columns.
if len(n.columns) < len(toReplace.ClusterVersion().Columns) {
return nil, pgerror.Newf(pgcode.InvalidTableDefinition, "cannot drop columns from view")
}
// Reset the columns to add the new result columns onto.
toReplace.Columns = make([]descpb.ColumnDescriptor, 0, len(n.columns))
toReplace.NextColumnID = 0
Expand Down
22 changes: 22 additions & 0 deletions pkg/sql/logictest/testdata/logic_test/views
Original file line number Diff line number Diff line change
Expand Up @@ -1813,3 +1813,25 @@ SELECT * FROM v;

statement ok
SET DATABASE = test;

# When replacing a view with fewer columns, an error about dropping columns from
# views preempts any errors about dependencies.
subtest regression_99000

statement ok
CREATE TABLE films (id int PRIMARY KEY, title text, kind text, classification CHAR(1));

statement ok
CREATE VIEW comedies AS
SELECT *
FROM films
WHERE kind = 'Comedy';

statement ok
CREATE VIEW pg_comedies AS
SELECT *
FROM comedies
WHERE classification = 'PG';

statement error pq: cannot drop columns from view
CREATE OR REPLACE VIEW comedies AS SELECT ARRAY[films.*]::string FROM films;

0 comments on commit b80feac

Please sign in to comment.