本文整理匯總了Golang中github.com/cockroachdb/cockroach/sql/parser.Name函數的典型用法代碼示例。如果您正苦於以下問題:Golang Name函數的具體用法?Golang Name怎麽用?Golang Name使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Name函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: runLsZones
func runLsZones(cmd *cobra.Command, args []string) error {
if len(args) > 0 {
mustUsage(cmd)
return nil
}
conn := makeSQLClient()
defer conn.Close()
zones, err := queryZones(conn)
if err != nil {
return err
}
if len(zones) == 0 {
fmt.Printf("No zones found\n")
return nil
}
// TODO(pmattis): This is inefficient. Instead of querying for all of the
// descriptors in the system, we could query for only those identified by
// zones. We'd also need to do a second query to retrieve all of the database
// descriptors referred to by table descriptors.
descs, err := queryDescriptors(conn)
if err != nil {
return err
}
// Loop over the zones and determine the name for each based on the name of
// the corresponding descriptor.
var output []string
for id := range zones {
if id == 0 {
// We handle the default zone below.
continue
}
desc, ok := descs[id]
if !ok {
continue
}
var name string
if tableDesc := desc.GetTable(); tableDesc != nil {
dbDesc, ok := descs[tableDesc.ParentID]
if !ok {
continue
}
name = parser.Name(dbDesc.GetName()).String() + "."
}
name += parser.Name(desc.GetName()).String()
output = append(output, name)
}
sort.Strings(output)
// Ensure the default zone is always printed first.
if _, ok := zones[0]; ok {
fmt.Println(".default")
}
for _, o := range output {
fmt.Println(o)
}
return nil
}
示例2: getTableNames
// getTableNames implements the SchemaAccessor interface.
func (p *planner) getTableNames(dbDesc *sqlbase.DatabaseDescriptor) (parser.TableNames, error) {
if e, ok := getVirtualSchemaEntry(dbDesc.Name); ok {
return e.tableNames(), nil
}
prefix := sqlbase.MakeNameMetadataKey(dbDesc.ID, "")
sr, err := p.txn.Scan(prefix, prefix.PrefixEnd(), 0)
if err != nil {
return nil, err
}
var tableNames parser.TableNames
for _, row := range sr {
_, tableName, err := encoding.DecodeUnsafeStringAscending(
bytes.TrimPrefix(row.Key, prefix), nil)
if err != nil {
return nil, err
}
tn := parser.TableName{
DatabaseName: parser.Name(dbDesc.Name),
TableName: parser.Name(tableName),
}
tableNames = append(tableNames, tn)
}
return tableNames, nil
}
示例3: upsertExprsAndIndex
// upsertExprsAndIndex returns the upsert conflict index and the (possibly
// synthetic) SET expressions used when a row conflicts.
func upsertExprsAndIndex(
tableDesc *sqlbase.TableDescriptor,
onConflict parser.OnConflict,
insertCols []sqlbase.ColumnDescriptor,
) (parser.UpdateExprs, *sqlbase.IndexDescriptor, error) {
if onConflict.IsUpsertAlias() {
// The UPSERT syntactic sugar is the same as the longhand specifying the
// primary index as the conflict index and SET expressions for the columns
// in insertCols minus any columns in the conflict index. Example:
// `UPSERT INTO abc VALUES (1, 2, 3)` is syntactic sugar for
// `INSERT INTO abc VALUES (1, 2, 3) ON CONFLICT a DO UPDATE SET b = 2, c = 3`.
conflictIndex := &tableDesc.PrimaryIndex
indexColSet := make(map[sqlbase.ColumnID]struct{}, len(conflictIndex.ColumnIDs))
for _, colID := range conflictIndex.ColumnIDs {
indexColSet[colID] = struct{}{}
}
updateExprs := make(parser.UpdateExprs, 0, len(insertCols))
for _, c := range insertCols {
if _, ok := indexColSet[c.ID]; !ok {
names := parser.UnresolvedNames{
parser.UnresolvedName{parser.Name(c.Name)},
}
expr := &parser.ColumnItem{
TableName: upsertExcludedTable,
ColumnName: parser.Name(c.Name),
}
updateExprs = append(updateExprs, &parser.UpdateExpr{Names: names, Expr: expr})
}
}
return updateExprs, conflictIndex, nil
}
indexMatch := func(index sqlbase.IndexDescriptor) bool {
if !index.Unique {
return false
}
if len(index.ColumnNames) != len(onConflict.Columns) {
return false
}
for i, colName := range index.ColumnNames {
if sqlbase.ReNormalizeName(colName) != sqlbase.NormalizeName(onConflict.Columns[i]) {
return false
}
}
return true
}
if indexMatch(tableDesc.PrimaryIndex) {
return onConflict.Exprs, &tableDesc.PrimaryIndex, nil
}
for _, index := range tableDesc.Indexes {
if indexMatch(index) {
return onConflict.Exprs, &index, nil
}
}
return nil, nil, fmt.Errorf("there is no unique or exclusion constraint matching the ON CONFLICT specification")
}
示例4: tableNames
func (e virtualSchemaEntry) tableNames() parser.TableNames {
var res parser.TableNames
for _, tableName := range e.orderedTableNames {
tn := parser.TableName{
DatabaseName: parser.Name(e.desc.Name),
TableName: parser.Name(tableName),
}
res = append(res, tn)
}
return res
}
示例5: testInitDummySelectNode
func testInitDummySelectNode(desc *sqlbase.TableDescriptor) *selectNode {
scan := &scanNode{}
scan.desc = *desc
scan.initDescDefaults(publicColumns)
sel := &selectNode{}
sel.qvals = make(qvalMap)
sel.source.plan = scan
testName := parser.TableName{TableName: parser.Name(desc.Name), DatabaseName: parser.Name("test")}
sel.source.info = newSourceInfoForSingleTable(testName, scan.Columns())
sel.sourceInfo = multiSourceInfo{sel.source.info}
return sel
}
示例6: getTableNames
func (p *planner) getTableNames(dbDesc *DatabaseDescriptor) (parser.QualifiedNames, *roachpb.Error) {
prefix := MakeNameMetadataKey(dbDesc.ID, "")
sr, pErr := p.txn.Scan(prefix, prefix.PrefixEnd(), 0)
if pErr != nil {
return nil, pErr
}
var qualifiedNames parser.QualifiedNames
for _, row := range sr {
_, tableName, err := encoding.DecodeStringAscending(
bytes.TrimPrefix(row.Key, prefix), nil)
if err != nil {
return nil, roachpb.NewError(err)
}
qname := &parser.QualifiedName{
Base: parser.Name(dbDesc.Name),
Indirect: parser.Indirection{parser.NameIndirection(tableName)},
}
if err := qname.NormalizeTableName(""); err != nil {
return nil, roachpb.NewError(err)
}
qualifiedNames = append(qualifiedNames, qname)
}
return qualifiedNames, nil
}
示例7: findColumn
// findColumn looks up the column described by a QualifiedName. The qname will be normalized.
func (qt qvalResolver) findColumn(qname *parser.QualifiedName) (columnRef, error) {
ref := columnRef{colIdx: invalidColIdx}
if err := qname.NormalizeColumnName(); err != nil {
return ref, err
}
// We can't resolve stars to a single column.
if qname.IsStar() {
err := fmt.Errorf("qualified name \"%s\" not found", qname)
return ref, err
}
// TODO(radu): when we support multiple FROMs, we will find the node with the correct alias; if
// no alias is given, we will search for the column in all FROMs and make sure there is only
// one. For now we just check that the name matches (if given).
if qname.Base == "" {
qname.Base = parser.Name(qt.table.alias)
}
if equalName(qt.table.alias, string(qname.Base)) {
colName := qname.Column()
for idx, col := range qt.table.columns {
if equalName(col.Name, colName) {
ref.table = qt.table
ref.colIdx = idx
return ref, nil
}
}
}
err := fmt.Errorf("qualified name \"%s\" not found", qname)
return ref, err
}
示例8: DatabaseDetails
// DatabaseDetails is an endpoint that returns grants and a list of table names
// for the specified database.
func (s *adminServer) DatabaseDetails(_ context.Context, req *DatabaseDetailsRequest) (*DatabaseDetailsResponse, error) {
var session sql.Session
user := s.getUser(req)
// Placeholders don't work with SHOW statements, so we need to manually
// escape the database name.
//
// TODO(cdo): Use placeholders when they're supported by SHOW.
escDBName := parser.Name(req.Database).String()
query := fmt.Sprintf("SHOW GRANTS ON DATABASE %s; SHOW TABLES FROM %s;", escDBName, escDBName)
r := s.sqlExecutor.ExecuteStatements(user, &session, query, nil)
if pErr := s.firstNotFoundError(r.ResultList); pErr != nil {
return nil, grpc.Errorf(codes.NotFound, "%s", pErr)
}
if err := s.checkQueryResults(r.ResultList, 2); err != nil {
return nil, s.serverError(err)
}
// Marshal grants.
var resp DatabaseDetailsResponse
{
const (
userCol = "User"
privilegesCol = "Privileges"
)
scanner := newResultScanner(r.ResultList[0].Columns)
for _, row := range r.ResultList[0].Rows {
// Marshal grant, splitting comma-separated privileges into a proper slice.
var grant DatabaseDetailsResponse_Grant
var privileges string
if err := scanner.Scan(row, userCol, &grant.User); err != nil {
return nil, err
}
if err := scanner.Scan(row, privilegesCol, &privileges); err != nil {
return nil, err
}
grant.Privileges = strings.Split(privileges, ",")
resp.Grants = append(resp.Grants, &grant)
}
}
// Marshal table names.
{
const tableCol = "Table"
scanner := newResultScanner(r.ResultList[1].Columns)
if a, e := len(r.ResultList[1].Columns), 1; a != e {
return nil, s.serverErrorf("show tables columns mismatch: %d != expected %d", a, e)
}
for _, row := range r.ResultList[1].Rows {
var tableName string
if err := scanner.Scan(row, tableCol, &tableName); err != nil {
return nil, err
}
resp.TableNames = append(resp.TableNames, tableName)
}
}
return &resp, nil
}
示例9: ShowTables
// ShowTables returns all the tables.
// Privileges: None.
// Notes: postgres does not have a SHOW TABLES statement.
// mysql only returns tables you have privileges on.
func (p *planner) ShowTables(n *parser.ShowTables) (planNode, error) {
// TODO(pmattis): This could be implemented as:
//
// SELECT name FROM system.namespace
// WHERE parentID = (SELECT id FROM system.namespace
// WHERE parentID = 0 AND name = <database>)
if n.Name == nil {
if p.session.Database == "" {
return nil, errNoDatabase
}
n.Name = &parser.QualifiedName{Base: parser.Name(p.session.Database)}
}
dbDesc, err := p.getDatabaseDesc(string(n.Name.Base))
if err != nil {
return nil, err
}
tableNames, err := p.getTableNames(dbDesc)
if err != nil {
return nil, err
}
v := &valuesNode{columns: []string{"Table"}}
for _, name := range tableNames {
v.rows = append(v.rows, []parser.Datum{parser.DString(name.Table())})
}
return v, nil
}
示例10: quoteNames
// quoteName quotes based on Traditional syntax and adds commas between names.
func quoteNames(names ...string) string {
nameList := make(parser.NameList, len(names))
for i, n := range names {
nameList[i] = parser.Name(n)
}
return parser.AsString(nameList)
}
示例11: queryNamespace
func queryNamespace(conn *sqlConn, parentID sqlbase.ID, name string) (sqlbase.ID, error) {
rows, err := makeQuery(
`SELECT id FROM system.namespace WHERE parentID = $1 AND name = $2`,
parentID, sqlbase.NormalizeName(parser.Name(name)))(conn)
if err != nil {
return 0, err
}
defer func() { _ = rows.Close() }()
if err != nil {
return 0, fmt.Errorf("%s not found: %v", name, err)
}
if len(rows.Columns()) != 1 {
return 0, fmt.Errorf("unexpected result columns: %d", len(rows.Columns()))
}
vals := make([]driver.Value, 1)
if err := rows.Next(vals); err != nil {
return 0, err
}
switch t := vals[0].(type) {
case int64:
return sqlbase.ID(t), nil
default:
return 0, fmt.Errorf("unexpected result type: %T", vals[0])
}
}
示例12: GetTableSpan
// GetTableSpan gets the key span for a SQL table, including any indices.
func (ie InternalExecutor) GetTableSpan(user string, txn *client.Txn, dbName, tableName string) (roachpb.Span, error) {
// Lookup the table ID.
p := makeInternalPlanner(txn, user)
p.leaseMgr = ie.LeaseManager
tn := parser.TableName{DatabaseName: parser.Name(dbName), TableName: parser.Name(tableName)}
tableID, err := getTableID(p, &tn)
if err != nil {
return roachpb.Span{}, err
}
// Determine table data span.
tablePrefix := keys.MakeTablePrefix(uint32(tableID))
tableStartKey := roachpb.Key(tablePrefix)
tableEndKey := tableStartKey.PrefixEnd()
return roachpb.Span{Key: tableStartKey, EndKey: tableEndKey}, nil
}
示例13: Format
// Format pretty-prints the orderingInfo to a stream.
// If columns is not nil, column names are printed instead of column indexes.
func (ord orderingInfo) Format(buf *bytes.Buffer, columns []ResultColumn) {
sep := ""
// Print the exact match columns. We sort them to ensure
// a deterministic output order.
cols := make([]int, 0, len(ord.exactMatchCols))
for i := range ord.exactMatchCols {
cols = append(cols, i)
}
sort.Ints(cols)
for _, i := range cols {
buf.WriteString(sep)
sep = ","
buf.WriteByte('=')
if columns == nil || i >= len(columns) {
fmt.Fprintf(buf, "%d", i)
} else {
parser.Name(columns[i].Name).Format(buf, parser.FmtSimple)
}
}
// Print the ordering columns and for each their sort order.
for _, o := range ord.ordering {
buf.WriteString(sep)
sep = ","
prefix := byte('+')
if o.Direction == encoding.Descending {
prefix = '-'
}
buf.WriteByte(prefix)
if columns == nil || o.ColIdx >= len(columns) {
fmt.Fprintf(buf, "%d", o.ColIdx)
} else {
parser.Name(columns[o.ColIdx].Name).Format(buf, parser.FmtSimple)
}
}
if ord.unique {
buf.WriteString(sep)
buf.WriteString("unique")
}
}
示例14: makeReturningHelper
func (p *planner) makeReturningHelper(
r parser.ReturningExprs,
desiredTypes []parser.Datum,
alias string,
tablecols []sqlbase.ColumnDescriptor,
) (returningHelper, error) {
rh := returningHelper{
p: p,
}
if len(r) == 0 {
return rh, nil
}
for _, e := range r {
if p.parser.AggregateInExpr(e.Expr) {
return rh, fmt.Errorf("aggregate functions are not allowed in RETURNING")
}
}
rh.columns = make([]ResultColumn, 0, len(r))
aliasTableName := parser.TableName{TableName: parser.Name(alias)}
rh.source = newSourceInfoForSingleTable(aliasTableName, makeResultColumns(tablecols))
rh.qvals = make(qvalMap)
rh.exprs = make([]parser.TypedExpr, 0, len(r))
for i, target := range r {
// Pre-normalize VarNames at the top level so that checkRenderStar can see stars.
if err := target.NormalizeTopLevelVarName(); err != nil {
return returningHelper{}, err
}
if isStar, cols, typedExprs, err := checkRenderStar(target, rh.source, rh.qvals); err != nil {
return returningHelper{}, err
} else if isStar {
rh.exprs = append(rh.exprs, typedExprs...)
rh.columns = append(rh.columns, cols...)
continue
}
// When generating an output column name it should exactly match the original
// expression, so determine the output column name before we perform any
// manipulations to the expression.
outputName := getRenderColName(target)
desired := parser.NoTypePreference
if len(desiredTypes) > i {
desired = desiredTypes[i]
}
typedExpr, err := rh.p.analyzeExpr(target.Expr, multiSourceInfo{rh.source}, rh.qvals, desired, false, "")
if err != nil {
return returningHelper{}, err
}
rh.exprs = append(rh.exprs, typedExpr)
rh.columns = append(rh.columns, ResultColumn{Name: outputName, Typ: typedExpr.ReturnType()})
}
return rh, nil
}
示例15: ColumnsSelectors
// ColumnsSelectors generates Select expressions for cols.
func ColumnsSelectors(cols []ColumnDescriptor) parser.SelectExprs {
exprs := make(parser.SelectExprs, len(cols))
colItems := make([]parser.ColumnItem, len(cols))
for i, col := range cols {
colItems[i].ColumnName = parser.Name(col.Name)
exprs[i].Expr = &colItems[i]
}
return exprs
}