diff --git a/pkg/sql/create_table.go b/pkg/sql/create_table.go index 69954750b5d1..8fafc599f905 100644 --- a/pkg/sql/create_table.go +++ b/pkg/sql/create_table.go @@ -39,6 +39,7 @@ import ( "github.com/cockroachdb/cockroach/pkg/sql/catalog/resolver" "github.com/cockroachdb/cockroach/pkg/sql/catalog/schemaexpr" "github.com/cockroachdb/cockroach/pkg/sql/catalog/tabledesc" + "github.com/cockroachdb/cockroach/pkg/sql/catalog/typedesc" "github.com/cockroachdb/cockroach/pkg/sql/paramparse" "github.com/cockroachdb/cockroach/pkg/sql/parser" "github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode" @@ -1223,6 +1224,27 @@ func newTableDescIfAs( } } + // Check if there is any reference to a user defined type that belongs to + // another database which is not allowed. + for _, def := range p.Defs { + if d, ok := def.(*tree.ColumnTableDef); ok { + // In CTAS, ColumnTableDef are generated from resultColumns which are + // resolved already. So we may cast it to *types.T directly without + // resolving it again. + typ := d.Type.(*types.T) + if typ.UserDefined() { + tn, typDesc, err := params.p.GetTypeDescriptor(params.ctx, typedesc.UserDefinedTypeOIDToID(typ.Oid())) + if err != nil { + return nil, err + } + if typDesc.GetParentID() != db.GetID() { + return nil, pgerror.Newf( + pgcode.FeatureNotSupported, "cross database type references are not supported: %s", tn.String()) + } + } + } + } + desc, err = newTableDesc( params, p, diff --git a/pkg/sql/logictest/testdata/logic_test/create_as b/pkg/sql/logictest/testdata/logic_test/create_as index 2aeb3b033081..6c74254bea15 100644 --- a/pkg/sql/logictest/testdata/logic_test/create_as +++ b/pkg/sql/logictest/testdata/logic_test/create_as @@ -382,3 +382,29 @@ query I SELECT * FROM tab_from_seq ---- 2 + +# Regression test for #105393 +subtest regression_105393 + +statement ok +CREATE DATABASE db105393_1; +CREATE DATABASE db105393_2; +USE db105393_1; +CREATE TYPE e105393 AS ENUM ('a'); +CREATE TABLE t105393 (a INT PRIMARY KEY, b e105393); +USE db105393_2; + +statement error pq: cross database type references are not supported: db105393_1.public.e105393 +CREATE TABLE e105393 AS TABLE db105393_1.public.t105393; + +statement error pq: cross database type references are not supported: db105393_1.public.e105393 +CREATE TABLE e105393 AS SELECT * FROM db105393_1.public.t105393; + +statement error pq: cross database type references are not supported: db105393_1.public.e105393 +CREATE TABLE e105393 AS SELECT b FROM db105393_1.public.t105393; + +statement error pq: cross database type references are not supported: db105393_1.public.e105393 +CREATE TABLE e105393 (a PRIMARY KEY, b) AS TABLE db105393_1.public.t105393; + +statement error pq: cross database type references are not supported: db105393_1.public.e105393 +CREATE TABLE e105393 (b) AS SELECT b FROM db105393_1.public.t105393;