github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/sql/opt/optbuilder/create_view.go (about) 1 // Copyright 2019 The Cockroach Authors. 2 // 3 // Use of this software is governed by the Business Source License 4 // included in the file licenses/BSL.txt. 5 // 6 // As of the Change Date specified in that file, in accordance with 7 // the Business Source License, use of this software will be governed 8 // by the Apache License, Version 2.0, included in the file 9 // licenses/APL.txt. 10 11 package optbuilder 12 13 import ( 14 "github.com/cockroachdb/cockroach/pkg/sql/opt/memo" 15 "github.com/cockroachdb/cockroach/pkg/sql/sem/tree" 16 "github.com/cockroachdb/cockroach/pkg/sql/sqlbase" 17 "github.com/cockroachdb/cockroach/pkg/util" 18 ) 19 20 func (b *Builder) buildCreateView(cv *tree.CreateView, inScope *scope) (outScope *scope) { 21 b.DisableMemoReuse = true 22 sch, _ := b.resolveSchemaForCreate(&cv.Name) 23 schID := b.factory.Metadata().AddSchema(sch) 24 25 // We build the select statement to: 26 // - check the statement semantically, 27 // - get the fully resolved names into the AST, and 28 // - collect the view dependencies in b.viewDeps. 29 // The result is not otherwise used. 30 b.insideViewDef = true 31 b.trackViewDeps = true 32 b.qualifyDataSourceNamesInAST = true 33 defer func() { 34 b.insideViewDef = false 35 b.trackViewDeps = false 36 b.viewDeps = nil 37 b.qualifyDataSourceNamesInAST = false 38 }() 39 40 b.pushWithFrame() 41 defScope := b.buildStmtAtRoot(cv.AsSource, nil /* desiredTypes */, inScope) 42 b.popWithFrame(defScope) 43 44 p := defScope.makePhysicalProps().Presentation 45 if len(cv.ColumnNames) != 0 { 46 if len(p) != len(cv.ColumnNames) { 47 panic(sqlbase.NewSyntaxErrorf( 48 "CREATE VIEW specifies %d column name%s, but data source has %d column%s", 49 len(cv.ColumnNames), util.Pluralize(int64(len(cv.ColumnNames))), 50 len(p), util.Pluralize(int64(len(p)))), 51 ) 52 } 53 // Override the columns. 54 for i := range p { 55 p[i].Alias = string(cv.ColumnNames[i]) 56 } 57 } 58 59 outScope = b.allocScope() 60 outScope.expr = b.factory.ConstructCreateView( 61 &memo.CreateViewPrivate{ 62 Schema: schID, 63 ViewName: cv.Name.Table(), 64 IfNotExists: cv.IfNotExists, 65 Replace: cv.Replace, 66 Temporary: cv.Temporary, 67 ViewQuery: tree.AsStringWithFlags(cv.AsSource, tree.FmtParsable), 68 Columns: p, 69 Deps: b.viewDeps, 70 }, 71 ) 72 return outScope 73 }