diff --git a/pkg/sql/opt/memo/memo.go b/pkg/sql/opt/memo/memo.go index 291c21d29b1d..6dab468075f2 100644 --- a/pkg/sql/opt/memo/memo.go +++ b/pkg/sql/opt/memo/memo.go @@ -363,6 +363,11 @@ func (m *Memo) NextID() opt.ScalarID { return m.curID } +// CopyNextIDFrom copies the next ScalarID from the other memo. +func (m *Memo) CopyNextIDFrom(other *Memo) { + m.curID = other.curID +} + // RequestColStat calculates and returns the column statistic calculated on the // relational expression. func (m *Memo) RequestColStat( diff --git a/pkg/sql/opt/norm/factory.go b/pkg/sql/opt/norm/factory.go index c0b744db9c4c..ba799e6c8e65 100644 --- a/pkg/sql/opt/norm/factory.go +++ b/pkg/sql/opt/norm/factory.go @@ -215,6 +215,11 @@ func (f *Factory) CopyAndReplace( panic(errors.AssertionFailedf("destination memo must be empty")) } + // Copy the next scalar ID to the target memo so that new scalar expressions + // built with the new memo will not share scalar IDs with existing + // expressions. + f.mem.CopyNextIDFrom(from.Memo()) + // Copy all metadata to the target memo so that referenced tables and // columns can keep the same ids they had in the "from" memo. Scalar // expressions in the metadata cannot have placeholders, so we simply copy diff --git a/pkg/sql/opt/norm/testdata/rules/select b/pkg/sql/opt/norm/testdata/rules/select index 8abbfb7c2977..dba4158db251 100644 --- a/pkg/sql/opt/norm/testdata/rules/select +++ b/pkg/sql/opt/norm/testdata/rules/select @@ -549,6 +549,28 @@ select ├── (u:1 = 10) OR (v:2 = 20) [outer=(1,2)] └── (v:2 = 20) OR (u:1 = 10) [outer=(1,2)] +# Regression test for #71002. DeduplicateSelectFilters should not remove filters +# that are not duplicated. +exec-ddl +create table t71002 ( + a BOOL, + b BOOL, + c BOOL +) +---- + +assign-placeholders-norm query-args=(false) +SELECT * FROM t71002 WHERE a AND (b OR ($1 OR c)) +---- +select + ├── columns: a:1!null b:2 c:3 + ├── fd: ()-->(1) + ├── scan t71002 + │ └── columns: a:1 b:2 c:3 + └── filters + ├── a:1 [outer=(1), constraints=(/1: [/true - /true]; tight), fd=()-->(1)] + └── b:2 OR c:3 [outer=(2,3)] + # -------------------------------------------------- # MergeSelects # --------------------------------------------------