From 6073b0ed81ffbe56b49423b8a9f206bdd0eebe09 Mon Sep 17 00:00:00 2001 From: Rafi Shamim Date: Sat, 25 Feb 2023 00:18:49 -0500 Subject: [PATCH] pg_catalog: handle temp tables in lookup joins The included test previously would have failed with an error like `unknown schema "[151]"`. In Postgres, temporary tables from other sessions are visible in pg_catalog, so we match that behavior. Release note (bug fix): Fixed an error that could occur when querying a pg_catalog table that included information about a temporary table created in another session. --- .../logictest/testdata/logic_test/temp_table | 24 +++++++++++++++++++ pkg/sql/pg_catalog.go | 23 +++++++++++++++--- 2 files changed, 44 insertions(+), 3 deletions(-) diff --git a/pkg/sql/logictest/testdata/logic_test/temp_table b/pkg/sql/logictest/testdata/logic_test/temp_table index 762d099916d8..774a51dc44a6 100644 --- a/pkg/sql/logictest/testdata/logic_test/temp_table +++ b/pkg/sql/logictest/testdata/logic_test/temp_table @@ -397,3 +397,27 @@ SELECT * FROM pg_temp.t statement ok USE defaultdb; DROP DATABASE to_drop CASCADE; + +subtest end + +subtest temp_table_in_other_session + +user testuser + +statement ok +USE defaultdb; +CREATE TEMPORARY TABLE from_other_session(i INT PRIMARY KEY) + +user root + +statement ok +USE defaultdb + +query TT +SELECT c.relname, a.attname FROM pg_attribute a +INNER LOOKUP JOIN pg_class c ON c.oid = a.attrelid +WHERE c.relname = 'from_other_session' +---- +from_other_session i + +subtest end diff --git a/pkg/sql/pg_catalog.go b/pkg/sql/pg_catalog.go index a91c755c5b5d..96d644d67269 100644 --- a/pkg/sql/pg_catalog.go +++ b/pkg/sql/pg_catalog.go @@ -1142,9 +1142,26 @@ func makeAllRelationsVirtualTableWithDescriptorIDIndex( } h := makeOidHasher() scResolver := oneAtATimeSchemaResolver{p: p, ctx: ctx} - sc, err := p.Descriptors().ByIDWithLeased(p.txn).WithoutNonPublic().Get().Schema(ctx, table.GetParentSchemaID()) - if err != nil { - return false, err + var sc catalog.SchemaDescriptor + if table.IsTemporary() { + // Temp tables from other sessions should still be visible here. + // Ideally, the catalog API would be able to return the temporary + // schemas from other sessions, but it cannot right now. See + // https://github.com/cockroachdb/cockroach/issues/97822. + if err := forEachSchema(ctx, p, db, false /* requiresPrivileges*/, func(schema catalog.SchemaDescriptor) error { + if schema.GetID() == table.GetParentSchemaID() { + sc = schema + } + return nil + }); err != nil { + return false, err + } + } + if sc == nil { + sc, err = p.Descriptors().ByIDWithLeased(p.txn).WithoutNonPublic().Get().Schema(ctx, table.GetParentSchemaID()) + if err != nil { + return false, err + } } if err := populateFromTable(ctx, p, h, db, sc, table, scResolver, addRow); err != nil {