github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/sql/delegate/show_schemas.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 delegate
    12  
    13  import (
    14  	"fmt"
    15  
    16  	"github.com/cockroachdb/cockroach/pkg/sql/lex"
    17  	"github.com/cockroachdb/cockroach/pkg/sql/opt/cat"
    18  	"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
    19  )
    20  
    21  // delegateShowSchemas implements SHOW SCHEMAS which returns all the schemas in
    22  // the given or current database.
    23  // Privileges: None.
    24  func (d *delegator) delegateShowSchemas(n *tree.ShowSchemas) (tree.Statement, error) {
    25  	name, err := d.getSpecifiedOrCurrentDatabase(n.Database)
    26  	if err != nil {
    27  		return nil, err
    28  	}
    29  	getSchemasQuery := fmt.Sprintf(`
    30  			SELECT schema_name
    31  			FROM %[1]s.information_schema.schemata
    32  			WHERE catalog_name = %[2]s
    33  			ORDER BY schema_name`,
    34  		name.String(), // note: (tree.Name).String() != string(name)
    35  		lex.EscapeSQLString(string(name)),
    36  	)
    37  
    38  	return parse(getSchemasQuery)
    39  }
    40  
    41  // getSpecifiedOrCurrentDatabase returns the name of the specified database, or
    42  // of the current database if the specified name is empty.
    43  //
    44  // Returns an error if there is no current database, or if the specified
    45  // database doesn't exist.
    46  func (d *delegator) getSpecifiedOrCurrentDatabase(specifiedDB tree.Name) (tree.Name, error) {
    47  	var name cat.SchemaName
    48  	if specifiedDB != "" {
    49  		// Note: the schema name may be interpreted as database name,
    50  		// see name_resolution.go.
    51  		name.SchemaName = specifiedDB
    52  		name.ExplicitSchema = true
    53  	}
    54  
    55  	flags := cat.Flags{AvoidDescriptorCaches: true}
    56  	_, resName, err := d.catalog.ResolveSchema(d.ctx, flags, &name)
    57  	if err != nil {
    58  		return "", err
    59  	}
    60  	return resName.CatalogName, nil
    61  }