github.com/cockroachdb/cockroachdb-parser@v0.23.3-0.20240213214944-911057d40c9a/pkg/sql/parser/sql.y (about)

     1  // Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group
     2  // Portions Copyright (c) 1994, Regents of the University of California
     3  
     4  // Portions of this file are additionally subject to the following
     5  // license and copyright.
     6  //
     7  // Licensed under the Apache License, Version 2.0 (the "License");
     8  // you may not use this file except in compliance with the License.
     9  // You may obtain a copy of the License at
    10  //
    11  //     http://www.apache.org/licenses/LICENSE-2.0
    12  //
    13  // Unless required by applicable law or agreed to in writing, software
    14  // distributed under the License is distributed on an "AS IS" BASIS,
    15  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    16  // implied. See the License for the specific language governing
    17  // permissions and limitations under the License.
    18  
    19  // Going to add a new statement?
    20  // Consider taking a look at our codelab guide to learn what is needed to add a statement.
    21  // https://github.com/cockroachdb/cockroach/blob/master/docs/codelabs/01-sql-statement.md
    22  
    23  %{
    24  package parser
    25  
    26  import (
    27      "fmt"
    28      "math"
    29      "strings"
    30  
    31      "go/constant"
    32  
    33      "github.com/cockroachdb/cockroach/pkg/geo/geopb"
    34      "github.com/cockroachdb/cockroach/pkg/security/username"
    35      "github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
    36      "github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
    37      "github.com/cockroachdb/cockroach/pkg/sql/privilege"
    38      "github.com/cockroachdb/cockroach/pkg/sql/scanner"
    39      "github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
    40      "github.com/cockroachdb/cockroach/pkg/sql/sem/tree/treebin"
    41      "github.com/cockroachdb/cockroach/pkg/sql/sem/tree/treecmp"
    42      "github.com/cockroachdb/cockroach/pkg/sql/sem/tree/treewindow"
    43      "github.com/cockroachdb/cockroach/pkg/sql/types"
    44      "github.com/cockroachdb/errors"
    45      "github.com/lib/pq/oid"
    46  )
    47  
    48  // MaxUint is the maximum value of an uint.
    49  const MaxUint = ^uint(0)
    50  // MaxInt is the maximum value of an int.
    51  const MaxInt = int(MaxUint >> 1)
    52  
    53  func unimplemented(sqllex sqlLexer, feature string) int {
    54      sqllex.(*lexer).Unimplemented(feature)
    55      return 1
    56  }
    57  
    58  func purposelyUnimplemented(sqllex sqlLexer, feature string, reason string) int {
    59      sqllex.(*lexer).PurposelyUnimplemented(feature, reason)
    60      return 1
    61  }
    62  
    63  func setErr(sqllex sqlLexer, err error) int {
    64      sqllex.(*lexer).setErr(err)
    65      return 1
    66  }
    67  
    68  func unimplementedWithIssue(sqllex sqlLexer, issue int) int {
    69      sqllex.(*lexer).UnimplementedWithIssue(issue)
    70      return 1
    71  }
    72  
    73  func unimplementedWithIssueDetail(sqllex sqlLexer, issue int, detail string) int {
    74      sqllex.(*lexer).UnimplementedWithIssueDetail(issue, detail)
    75      return 1
    76  }
    77  
    78  func processBinaryQualOp(
    79    sqllex sqlLexer,
    80    op tree.Operator,
    81    lhs tree.Expr,
    82    rhs tree.Expr,
    83  ) (tree.Expr, int) {
    84    switch op := op.(type) {
    85    case treebin.BinaryOperator:
    86      op.IsExplicitOperator = true
    87      return &tree.BinaryExpr{Operator: op, Left: lhs, Right: rhs}, 0
    88    case treecmp.ComparisonOperator:
    89      op.IsExplicitOperator = true
    90      return &tree.ComparisonExpr{Operator: op, Left: lhs, Right: rhs}, 0
    91    case tree.UnaryOperator:
    92      // We have a unary operator which have the same symbol as the binary
    93      // operator, so adjust accordingly.
    94      switch op.Symbol {
    95      case tree.UnaryComplement:
    96        return &tree.ComparisonExpr{
    97          Operator: treecmp.ComparisonOperator{
    98            Symbol: treecmp.RegMatch,
    99            IsExplicitOperator: true,
   100          },
   101          Left: lhs,
   102          Right: rhs,
   103        }, 0
   104      default:
   105        sqllex.Error(fmt.Sprintf("unknown binary operator %s", op))
   106        return nil, -1
   107      }
   108    default:
   109      sqllex.Error(fmt.Sprintf("unknown binary operator %s", op))
   110      return nil, 1
   111    }
   112  }
   113  
   114  func processUnaryQualOp(
   115    sqllex sqlLexer,
   116    op tree.Operator,
   117    expr tree.Expr,
   118  ) (tree.Expr, int) {
   119    e, code := processUnaryQualOpInternal(sqllex, op, expr)
   120    if code != 0 {
   121      return e, code
   122    }
   123    if e, ok := e.(*tree.UnaryExpr); ok {
   124      e.Operator.IsExplicitOperator = true
   125    }
   126    return e, code
   127  }
   128  
   129  func processUnaryQualOpInternal(
   130    sqllex sqlLexer,
   131    op tree.Operator,
   132    expr tree.Expr,
   133  ) (tree.Expr, int) {
   134    switch op := op.(type) {
   135    case tree.UnaryOperator:
   136      return &tree.UnaryExpr{Operator: op, Expr: expr}, 0
   137    case treebin.BinaryOperator:
   138      // We have some binary operators which have the same symbol as the unary
   139      // operator, so adjust accordingly.
   140      switch op.Symbol {
   141      case treebin.Plus:
   142        return &tree.UnaryExpr{
   143          Operator: tree.MakeUnaryOperator(tree.UnaryPlus),
   144          Expr: expr,
   145        }, 0
   146      case treebin.Minus:
   147        return &tree.UnaryExpr{
   148          Operator: tree.MakeUnaryOperator(tree.UnaryMinus),
   149          Expr: expr,
   150        }, 0
   151      }
   152    case treecmp.ComparisonOperator:
   153      switch op.Symbol {
   154      case treecmp.RegMatch:
   155        return &tree.UnaryExpr{
   156          Operator: tree.MakeUnaryOperator(tree.UnaryComplement),
   157          Expr: expr,
   158        }, 0
   159      }
   160    }
   161    sqllex.Error(fmt.Sprintf("unknown unary operator %s", op))
   162    return nil, 1
   163  }
   164  
   165  %}
   166  
   167  %{
   168  // sqlSymType is generated by goyacc, and implements the ScanSymType interface.
   169  var _ scanner.ScanSymType = &sqlSymType{}
   170  
   171  func (s *sqlSymType) ID() int32 {
   172  	return s.id
   173  }
   174  
   175  func (s *sqlSymType) SetID(id int32) {
   176  	s.id = id
   177  }
   178  
   179  func (s *sqlSymType) Pos() int32 {
   180  	return s.pos
   181  }
   182  
   183  func (s *sqlSymType) SetPos(pos int32) {
   184  	s.pos = pos
   185  }
   186  
   187  func (s *sqlSymType) Str() string {
   188  	return s.str
   189  }
   190  
   191  func (s *sqlSymType) SetStr(str string) {
   192  	s.str = str
   193  }
   194  
   195  func (s *sqlSymType) UnionVal() interface{} {
   196  	return s.union.val
   197  }
   198  
   199  func (s *sqlSymType) SetUnionVal(val interface{}) {
   200  	s.union.val = val
   201  }
   202  
   203  // sqlSymUnion represents a union of types, providing accessor methods
   204  // to retrieve the underlying type stored in the union's empty interface.
   205  // The purpose of the sqlSymUnion struct is to reduce the memory footprint of
   206  // the sqlSymType because only one value (of a variety of types) is ever needed
   207  // to be stored in the union field at a time.
   208  //
   209  // By using an empty interface, we lose the type checking previously provided
   210  // by yacc and the Go compiler when dealing with union values. Instead, runtime
   211  // type assertions must be relied upon in the methods below, and as such, the
   212  // parser should be thoroughly tested whenever new syntax is added.
   213  //
   214  // It is important to note that when assigning values to sqlSymUnion.val, all
   215  // nil values should be typed so that they are stored as nil instances in the
   216  // empty interface, instead of setting the empty interface to nil. This means
   217  // that:
   218  //     $$ = []String(nil)
   219  // should be used, instead of:
   220  //     $$ = nil
   221  // to assign a nil string slice to the union.
   222  type sqlSymUnion struct {
   223      val interface{}
   224  }
   225  
   226  // The following accessor methods come in three forms, depending on the
   227  // type of the value being accessed and whether a nil value is admissible
   228  // for the corresponding grammar rule.
   229  // - Values and pointers are directly type asserted from the empty
   230  //   interface, regardless of whether a nil value is admissible or
   231  //   not. A panic occurs if the type assertion is incorrect; no panic occurs
   232  //   if a nil is not expected but present. (TODO(knz): split this category of
   233  //   accessor in two; with one checking for unexpected nils.)
   234  //   Examples: bool(), tableIndexName().
   235  //
   236  // - Interfaces where a nil is admissible are handled differently
   237  //   because a nil instance of an interface inserted into the empty interface
   238  //   becomes a nil instance of the empty interface and therefore will fail a
   239  //   direct type assertion. Instead, a guarded type assertion must be used,
   240  //   which returns nil if the type assertion fails.
   241  //   Examples: expr(), stmt().
   242  //
   243  // - Interfaces where a nil is not admissible are implemented as a direct
   244  //   type assertion, which causes a panic to occur if an unexpected nil
   245  //   is encountered.
   246  //   Examples: tblDef().
   247  //
   248  func (u *sqlSymUnion) numVal() *tree.NumVal {
   249      return u.val.(*tree.NumVal)
   250  }
   251  func (u *sqlSymUnion) strVal() *tree.StrVal {
   252      if stmt, ok := u.val.(*tree.StrVal); ok {
   253          return stmt
   254      }
   255      return nil
   256  }
   257  func (u *sqlSymUnion) placeholder() *tree.Placeholder {
   258      return u.val.(*tree.Placeholder)
   259  }
   260  func (u *sqlSymUnion) auditMode() tree.AuditMode {
   261      return u.val.(tree.AuditMode)
   262  }
   263  func (u *sqlSymUnion) bool() bool {
   264      return u.val.(bool)
   265  }
   266  func (u *sqlSymUnion) strPtr() *string {
   267      return u.val.(*string)
   268  }
   269  func (u *sqlSymUnion) strs() []string {
   270      return u.val.([]string)
   271  }
   272  func (u *sqlSymUnion) roleSpec() tree.RoleSpec {
   273      return u.val.(tree.RoleSpec)
   274  }
   275  func (u *sqlSymUnion) roleSpecList() tree.RoleSpecList {
   276      return u.val.(tree.RoleSpecList)
   277  }
   278  func (u *sqlSymUnion) user() username.SQLUsername {
   279      return u.val.(username.SQLUsername)
   280  }
   281  func (u *sqlSymUnion) userPtr() *username.SQLUsername {
   282      return u.val.(*username.SQLUsername)
   283  }
   284  func (u *sqlSymUnion) users() []username.SQLUsername {
   285      return u.val.([]username.SQLUsername)
   286  }
   287  func (u *sqlSymUnion) newTableIndexName() *tree.TableIndexName {
   288      tn := u.val.(tree.TableIndexName)
   289      return &tn
   290  }
   291  func (u *sqlSymUnion) tableIndexName() tree.TableIndexName {
   292      return u.val.(tree.TableIndexName)
   293  }
   294  func (u *sqlSymUnion) newTableIndexNames() tree.TableIndexNames {
   295      return u.val.(tree.TableIndexNames)
   296  }
   297  func (u *sqlSymUnion) shardedIndexDef() *tree.ShardedIndexDef {
   298    return u.val.(*tree.ShardedIndexDef)
   299  }
   300  func (u *sqlSymUnion) nameList() tree.NameList {
   301      return u.val.(tree.NameList)
   302  }
   303  func (u *sqlSymUnion) enumValueList() tree.EnumValueList {
   304      return u.val.(tree.EnumValueList)
   305  }
   306  func (u *sqlSymUnion) compositeTypeList() []tree.CompositeTypeElem {
   307      return u.val.([]tree.CompositeTypeElem)
   308  }
   309  func (u *sqlSymUnion) unresolvedName() *tree.UnresolvedName {
   310      return u.val.(*tree.UnresolvedName)
   311  }
   312  func (u *sqlSymUnion) unresolvedObjectName() *tree.UnresolvedObjectName {
   313      return u.val.(*tree.UnresolvedObjectName)
   314  }
   315  func (u *sqlSymUnion) unresolvedObjectNames() []*tree.UnresolvedObjectName {
   316      return u.val.([]*tree.UnresolvedObjectName)
   317  }
   318  func (u *sqlSymUnion) tablePatterns() tree.TablePatterns {
   319      return u.val.(tree.TablePatterns)
   320  }
   321  func (u *sqlSymUnion) tableNames() tree.TableNames {
   322      return u.val.(tree.TableNames)
   323  }
   324  func (u *sqlSymUnion) indexFlags() *tree.IndexFlags {
   325      return u.val.(*tree.IndexFlags)
   326  }
   327  func (u *sqlSymUnion) arraySubscript() *tree.ArraySubscript {
   328      return u.val.(*tree.ArraySubscript)
   329  }
   330  func (u *sqlSymUnion) arraySubscripts() tree.ArraySubscripts {
   331      if as, ok := u.val.(tree.ArraySubscripts); ok {
   332          return as
   333      }
   334      return nil
   335  }
   336  func (u *sqlSymUnion) stmt() tree.Statement {
   337      if stmt, ok := u.val.(tree.Statement); ok {
   338          return stmt
   339      }
   340      return nil
   341  }
   342  func (u *sqlSymUnion) cte() *tree.CTE {
   343      if cte, ok := u.val.(*tree.CTE); ok {
   344          return cte
   345      }
   346      return nil
   347  }
   348  func (u *sqlSymUnion) ctes() []*tree.CTE {
   349      return u.val.([]*tree.CTE)
   350  }
   351  func (u *sqlSymUnion) with() *tree.With {
   352      if with, ok := u.val.(*tree.With); ok {
   353          return with
   354      }
   355      return nil
   356  }
   357  func (u *sqlSymUnion) slct() *tree.Select {
   358      return u.val.(*tree.Select)
   359  }
   360  func (u *sqlSymUnion) selectStmt() tree.SelectStatement {
   361      return u.val.(tree.SelectStatement)
   362  }
   363  func (u *sqlSymUnion) colTableDef() *tree.ColumnTableDef {
   364      return u.val.(*tree.ColumnTableDef)
   365  }
   366  func (u *sqlSymUnion) colDef() tree.ColumnDef {
   367      return u.val.(tree.ColumnDef)
   368  }
   369  func (u *sqlSymUnion) colDefList() tree.ColumnDefList {
   370      return u.val.(tree.ColumnDefList)
   371  }
   372  func (u *sqlSymUnion) constraintDef() tree.ConstraintTableDef {
   373      return u.val.(tree.ConstraintTableDef)
   374  }
   375  func (u *sqlSymUnion) tblDef() tree.TableDef {
   376      return u.val.(tree.TableDef)
   377  }
   378  func (u *sqlSymUnion) tblDefs() tree.TableDefs {
   379      return u.val.(tree.TableDefs)
   380  }
   381  func (u *sqlSymUnion) likeTableOption() tree.LikeTableOption {
   382      return u.val.(tree.LikeTableOption)
   383  }
   384  func (u *sqlSymUnion) likeTableOptionList() []tree.LikeTableOption {
   385      return u.val.([]tree.LikeTableOption)
   386  }
   387  func (u *sqlSymUnion) colQual() tree.NamedColumnQualification {
   388      return u.val.(tree.NamedColumnQualification)
   389  }
   390  func (u *sqlSymUnion) colQualElem() tree.ColumnQualification {
   391      return u.val.(tree.ColumnQualification)
   392  }
   393  func (u *sqlSymUnion) colQuals() []tree.NamedColumnQualification {
   394      return u.val.([]tree.NamedColumnQualification)
   395  }
   396  func (u *sqlSymUnion) storageParam() tree.StorageParam {
   397      return u.val.(tree.StorageParam)
   398  }
   399  func (u *sqlSymUnion) storageParams() []tree.StorageParam {
   400      if params, ok := u.val.([]tree.StorageParam); ok {
   401          return params
   402      }
   403      return nil
   404  }
   405  func (u *sqlSymUnion) storageParamKeys() []tree.Name {
   406      if params, ok := u.val.([]tree.Name); ok {
   407          return params
   408      }
   409      return nil
   410  }
   411  func (u *sqlSymUnion) tenantCapability() tree.TenantCapability {
   412      return u.val.(tree.TenantCapability)
   413  }
   414  func (u *sqlSymUnion) tenantCapabilities() []tree.TenantCapability {
   415      if capabilities, ok := u.val.([]tree.TenantCapability); ok {
   416          return capabilities
   417      }
   418      return nil
   419  }
   420  func (u *sqlSymUnion) persistence() tree.Persistence {
   421    return u.val.(tree.Persistence)
   422  }
   423  func (u *sqlSymUnion) colType() *types.T {
   424      if colType, ok := u.val.(*types.T); ok && colType != nil {
   425          return colType
   426      }
   427      return nil
   428  }
   429  func (u *sqlSymUnion) tableRefCols() []tree.ColumnID {
   430      if refCols, ok := u.val.([]tree.ColumnID); ok {
   431          return refCols
   432      }
   433      return nil
   434  }
   435  func (u *sqlSymUnion) colTypes() []*types.T {
   436      return u.val.([]*types.T)
   437  }
   438  func (u *sqlSymUnion) int32() int32 {
   439      return u.val.(int32)
   440  }
   441  func (u *sqlSymUnion) int64() int64 {
   442      return u.val.(int64)
   443  }
   444  func (u *sqlSymUnion) seqOpt() tree.SequenceOption {
   445      return u.val.(tree.SequenceOption)
   446  }
   447  func (u *sqlSymUnion) seqOpts() []tree.SequenceOption {
   448      return u.val.([]tree.SequenceOption)
   449  }
   450  func (u *sqlSymUnion) expr() tree.Expr {
   451      if expr, ok := u.val.(tree.Expr); ok {
   452          return expr
   453      }
   454      return nil
   455  }
   456  func (u *sqlSymUnion) exprs() tree.Exprs {
   457      return u.val.(tree.Exprs)
   458  }
   459  func (u *sqlSymUnion) selExpr() tree.SelectExpr {
   460      return u.val.(tree.SelectExpr)
   461  }
   462  func (u *sqlSymUnion) selExprs() tree.SelectExprs {
   463      return u.val.(tree.SelectExprs)
   464  }
   465  func (u *sqlSymUnion) retClause() tree.ReturningClause {
   466          return u.val.(tree.ReturningClause)
   467  }
   468  func (u *sqlSymUnion) aliasClause() tree.AliasClause {
   469      return u.val.(tree.AliasClause)
   470  }
   471  func (u *sqlSymUnion) asOfClause() tree.AsOfClause {
   472      return u.val.(tree.AsOfClause)
   473  }
   474  func (u *sqlSymUnion) tblExpr() tree.TableExpr {
   475      return u.val.(tree.TableExpr)
   476  }
   477  func (u *sqlSymUnion) tblExprs() tree.TableExprs {
   478      return u.val.(tree.TableExprs)
   479  }
   480  func (u *sqlSymUnion) from() tree.From {
   481      return u.val.(tree.From)
   482  }
   483  func (u *sqlSymUnion) batch() *tree.Batch {
   484      if batch, ok := u.val.(*tree.Batch); ok {
   485          return batch
   486      }
   487      return nil
   488  }
   489  func (u *sqlSymUnion) batchParam() tree.BatchParam {
   490      return u.val.(tree.BatchParam)
   491  }
   492  func (u *sqlSymUnion) batchParams() []tree.BatchParam {
   493      return u.val.([]tree.BatchParam)
   494  }
   495  func (u *sqlSymUnion) superRegion() tree.SuperRegion {
   496      return u.val.(tree.SuperRegion)
   497  }
   498  func (u *sqlSymUnion) int32s() []int32 {
   499      return u.val.([]int32)
   500  }
   501  func (u *sqlSymUnion) joinCond() tree.JoinCond {
   502      return u.val.(tree.JoinCond)
   503  }
   504  func (u *sqlSymUnion) when() *tree.When {
   505      return u.val.(*tree.When)
   506  }
   507  func (u *sqlSymUnion) whens() []*tree.When {
   508      return u.val.([]*tree.When)
   509  }
   510  func (u *sqlSymUnion) lockingClause() tree.LockingClause {
   511      return u.val.(tree.LockingClause)
   512  }
   513  func (u *sqlSymUnion) lockingItem() *tree.LockingItem {
   514      return u.val.(*tree.LockingItem)
   515  }
   516  func (u *sqlSymUnion) lockingStrength() tree.LockingStrength {
   517      return u.val.(tree.LockingStrength)
   518  }
   519  func (u *sqlSymUnion) lockingWaitPolicy() tree.LockingWaitPolicy {
   520      return u.val.(tree.LockingWaitPolicy)
   521  }
   522  func (u *sqlSymUnion) updateExpr() *tree.UpdateExpr {
   523      return u.val.(*tree.UpdateExpr)
   524  }
   525  func (u *sqlSymUnion) updateExprs() tree.UpdateExprs {
   526      return u.val.(tree.UpdateExprs)
   527  }
   528  func (u *sqlSymUnion) limit() *tree.Limit {
   529      return u.val.(*tree.Limit)
   530  }
   531  func (u *sqlSymUnion) backupTargetList() tree.BackupTargetList {
   532      return u.val.(tree.BackupTargetList)
   533  }
   534  func (u *sqlSymUnion) backupTargetListPtr() *tree.BackupTargetList {
   535      return u.val.(*tree.BackupTargetList)
   536  }
   537  func (u *sqlSymUnion) grantTargetList() tree.GrantTargetList {
   538      return u.val.(tree.GrantTargetList)
   539  }
   540  func (u *sqlSymUnion) grantTargetListPtr() *tree.GrantTargetList {
   541      return u.val.(*tree.GrantTargetList)
   542  }
   543  func (u *sqlSymUnion) changefeedTargets() tree.ChangefeedTargets {
   544      return u.val.(tree.ChangefeedTargets)
   545  }
   546  func (u *sqlSymUnion) changefeedTarget() tree.ChangefeedTarget {
   547      return u.val.(tree.ChangefeedTarget)
   548  }
   549  func (u *sqlSymUnion) privilegeType() privilege.Kind {
   550      return u.val.(privilege.Kind)
   551  }
   552  func (u *sqlSymUnion) privilegeList() privilege.List {
   553      return u.val.(privilege.List)
   554  }
   555  func (u *sqlSymUnion) onConflict() *tree.OnConflict {
   556      return u.val.(*tree.OnConflict)
   557  }
   558  func (u *sqlSymUnion) orderBy() tree.OrderBy {
   559      return u.val.(tree.OrderBy)
   560  }
   561  func (u *sqlSymUnion) order() *tree.Order {
   562      return u.val.(*tree.Order)
   563  }
   564  func (u *sqlSymUnion) orders() []*tree.Order {
   565      return u.val.([]*tree.Order)
   566  }
   567  func (u *sqlSymUnion) groupBy() tree.GroupBy {
   568      return u.val.(tree.GroupBy)
   569  }
   570  func (u *sqlSymUnion) windowFrame() *tree.WindowFrame {
   571      return u.val.(*tree.WindowFrame)
   572  }
   573  func (u *sqlSymUnion) windowFrameBounds() tree.WindowFrameBounds {
   574      return u.val.(tree.WindowFrameBounds)
   575  }
   576  func (u *sqlSymUnion) windowFrameBound() *tree.WindowFrameBound {
   577      return u.val.(*tree.WindowFrameBound)
   578  }
   579  func (u *sqlSymUnion) windowFrameExclusion() treewindow.WindowFrameExclusion {
   580      return u.val.(treewindow.WindowFrameExclusion)
   581  }
   582  func (u *sqlSymUnion) distinctOn() tree.DistinctOn {
   583      return u.val.(tree.DistinctOn)
   584  }
   585  func (u *sqlSymUnion) dir() tree.Direction {
   586      return u.val.(tree.Direction)
   587  }
   588  func (u *sqlSymUnion) nullsOrder() tree.NullsOrder {
   589      return u.val.(tree.NullsOrder)
   590  }
   591  func (u *sqlSymUnion) alterChangefeedCmd() tree.AlterChangefeedCmd {
   592      return u.val.(tree.AlterChangefeedCmd)
   593  }
   594  func (u *sqlSymUnion) alterChangefeedCmds() tree.AlterChangefeedCmds {
   595      return u.val.(tree.AlterChangefeedCmds)
   596  }
   597  func (u *sqlSymUnion) backupKMS() tree.BackupKMS {
   598      return u.val.(tree.BackupKMS)
   599  }
   600  func (u *sqlSymUnion) alterBackupCmd() tree.AlterBackupCmd {
   601      return u.val.(tree.AlterBackupCmd)
   602  }
   603  func (u *sqlSymUnion) alterBackupCmds() tree.AlterBackupCmds {
   604      return u.val.(tree.AlterBackupCmds)
   605  }
   606  func (u *sqlSymUnion) alterBackupScheduleCmd() tree.AlterBackupScheduleCmd {
   607      return u.val.(tree.AlterBackupScheduleCmd)
   608  }
   609  func (u *sqlSymUnion) alterBackupScheduleCmds() tree.AlterBackupScheduleCmds {
   610      return u.val.(tree.AlterBackupScheduleCmds)
   611  }
   612  func (u *sqlSymUnion) alterTableCmd() tree.AlterTableCmd {
   613      return u.val.(tree.AlterTableCmd)
   614  }
   615  func (u *sqlSymUnion) alterTableCmds() tree.AlterTableCmds {
   616      return u.val.(tree.AlterTableCmds)
   617  }
   618  func (u *sqlSymUnion) alterIndexCmd() tree.AlterIndexCmd {
   619      return u.val.(tree.AlterIndexCmd)
   620  }
   621  func (u *sqlSymUnion) alterIndexCmds() tree.AlterIndexCmds {
   622      return u.val.(tree.AlterIndexCmds)
   623  }
   624  func (u *sqlSymUnion) isoLevel() tree.IsolationLevel {
   625      return u.val.(tree.IsolationLevel)
   626  }
   627  func (u *sqlSymUnion) userPriority() tree.UserPriority {
   628      return u.val.(tree.UserPriority)
   629  }
   630  func (u *sqlSymUnion) readWriteMode() tree.ReadWriteMode {
   631      return u.val.(tree.ReadWriteMode)
   632  }
   633  func (u *sqlSymUnion) deferrableMode() tree.DeferrableMode {
   634      return u.val.(tree.DeferrableMode)
   635  }
   636  func (u *sqlSymUnion) idxElem() tree.IndexElem {
   637      return u.val.(tree.IndexElem)
   638  }
   639  func (u *sqlSymUnion) idxElems() tree.IndexElemList {
   640      return u.val.(tree.IndexElemList)
   641  }
   642  func (u *sqlSymUnion) indexInvisibility() tree.IndexInvisibility {
   643      return u.val.(tree.IndexInvisibility)
   644  }
   645  func (u *sqlSymUnion) dropBehavior() tree.DropBehavior {
   646      return u.val.(tree.DropBehavior)
   647  }
   648  func (u *sqlSymUnion) validationBehavior() tree.ValidationBehavior {
   649      return u.val.(tree.ValidationBehavior)
   650  }
   651  func (u *sqlSymUnion) partitionBy() *tree.PartitionBy {
   652      return u.val.(*tree.PartitionBy)
   653  }
   654  func (u *sqlSymUnion) partitionByTable() *tree.PartitionByTable {
   655      return u.val.(*tree.PartitionByTable)
   656  }
   657  func (u *sqlSymUnion) partitionByIndex() *tree.PartitionByIndex {
   658      return u.val.(*tree.PartitionByIndex)
   659  }
   660  func (u *sqlSymUnion) createTableOnCommitSetting() tree.CreateTableOnCommitSetting {
   661      return u.val.(tree.CreateTableOnCommitSetting)
   662  }
   663  func (u *sqlSymUnion) listPartition() tree.ListPartition {
   664      return u.val.(tree.ListPartition)
   665  }
   666  func (u *sqlSymUnion) listPartitions() []tree.ListPartition {
   667      return u.val.([]tree.ListPartition)
   668  }
   669  func (u *sqlSymUnion) rangePartition() tree.RangePartition {
   670      return u.val.(tree.RangePartition)
   671  }
   672  func (u *sqlSymUnion) rangePartitions() []tree.RangePartition {
   673      return u.val.([]tree.RangePartition)
   674  }
   675  func (u *sqlSymUnion) relocateSubject() tree.RelocateSubject {
   676      return u.val.(tree.RelocateSubject)
   677  }
   678  func (u *sqlSymUnion) setZoneConfig() *tree.SetZoneConfig {
   679      return u.val.(*tree.SetZoneConfig)
   680  }
   681  func (u *sqlSymUnion) tuples() []*tree.Tuple {
   682      return u.val.([]*tree.Tuple)
   683  }
   684  func (u *sqlSymUnion) tuple() *tree.Tuple {
   685      return u.val.(*tree.Tuple)
   686  }
   687  func (u *sqlSymUnion) windowDef() *tree.WindowDef {
   688      return u.val.(*tree.WindowDef)
   689  }
   690  func (u *sqlSymUnion) window() tree.Window {
   691      return u.val.(tree.Window)
   692  }
   693  func (u *sqlSymUnion) op() tree.Operator {
   694      return u.val.(tree.Operator)
   695  }
   696  func (u *sqlSymUnion) cmpOp() treecmp.ComparisonOperator {
   697      return u.val.(treecmp.ComparisonOperator)
   698  }
   699  func (u *sqlSymUnion) intervalTypeMetadata() types.IntervalTypeMetadata {
   700      return u.val.(types.IntervalTypeMetadata)
   701  }
   702  func (u *sqlSymUnion) kvOption() tree.KVOption {
   703      return u.val.(tree.KVOption)
   704  }
   705  func (u *sqlSymUnion) kvOptions() []tree.KVOption {
   706      if colType, ok := u.val.([]tree.KVOption); ok {
   707          return colType
   708      }
   709      return nil
   710  }
   711  func (u *sqlSymUnion) backupOptions() *tree.BackupOptions {
   712    return u.val.(*tree.BackupOptions)
   713  }
   714  func (u *sqlSymUnion) copyOptions() *tree.CopyOptions {
   715    return u.val.(*tree.CopyOptions)
   716  }
   717  func (u *sqlSymUnion) showJobOptions() *tree.ShowJobOptions {
   718    return u.val.(*tree.ShowJobOptions)
   719  }
   720  func (u *sqlSymUnion) showBackupDetails() tree.ShowBackupDetails {
   721    return u.val.(tree.ShowBackupDetails)
   722  }
   723  func (u *sqlSymUnion) showBackupOptions() *tree.ShowBackupOptions {
   724    return u.val.(*tree.ShowBackupOptions)
   725  }
   726  func (u *sqlSymUnion) restoreOptions() *tree.RestoreOptions {
   727    return u.val.(*tree.RestoreOptions)
   728  }
   729  func (u *sqlSymUnion) transactionModes() tree.TransactionModes {
   730      return u.val.(tree.TransactionModes)
   731  }
   732  func (u *sqlSymUnion) compositeKeyMatchMethod() tree.CompositeKeyMatchMethod {
   733    return u.val.(tree.CompositeKeyMatchMethod)
   734  }
   735  func (u *sqlSymUnion) referenceAction() tree.ReferenceAction {
   736      return u.val.(tree.ReferenceAction)
   737  }
   738  func (u *sqlSymUnion) referenceActions() tree.ReferenceActions {
   739      return u.val.(tree.ReferenceActions)
   740  }
   741  func (u *sqlSymUnion) createStatsOptions() *tree.CreateStatsOptions {
   742      return u.val.(*tree.CreateStatsOptions)
   743  }
   744  func (u *sqlSymUnion) scrubOptions() tree.ScrubOptions {
   745      return u.val.(tree.ScrubOptions)
   746  }
   747  func (u *sqlSymUnion) scrubOption() tree.ScrubOption {
   748      return u.val.(tree.ScrubOption)
   749  }
   750  func (u *sqlSymUnion) resolvableFuncRefFromName() tree.ResolvableFunctionReference {
   751      return tree.ResolvableFunctionReference{FunctionReference: u.unresolvedName()}
   752  }
   753  func (u *sqlSymUnion) resolvableFuncRef() tree.ResolvableFunctionReference {
   754      return u.val.(tree.ResolvableFunctionReference)
   755  }
   756  func (u *sqlSymUnion) rowsFromExpr() *tree.RowsFromExpr {
   757      return u.val.(*tree.RowsFromExpr)
   758  }
   759  func (u *sqlSymUnion) stringOrPlaceholderOptList() tree.StringOrPlaceholderOptList {
   760      return u.val.(tree.StringOrPlaceholderOptList)
   761  }
   762  func (u *sqlSymUnion) listOfStringOrPlaceholderOptList() []tree.StringOrPlaceholderOptList {
   763      return u.val.([]tree.StringOrPlaceholderOptList)
   764  }
   765  func (u *sqlSymUnion) fullBackupClause() *tree.FullBackupClause {
   766      return u.val.(*tree.FullBackupClause)
   767  }
   768  func (u *sqlSymUnion) scheduleLabelSpec() *tree.LabelSpec {
   769      return u.val.(*tree.LabelSpec)
   770  }
   771  func (u *sqlSymUnion) labelSpec() *tree.LabelSpec {
   772      return u.val.(*tree.LabelSpec)
   773  }
   774  
   775  func (u *sqlSymUnion) geoShapeType() geopb.ShapeType {
   776    return u.val.(geopb.ShapeType)
   777  }
   778  func newNameFromStr(s string) *tree.Name {
   779      return (*tree.Name)(&s)
   780  }
   781  func (u *sqlSymUnion) typeReference() tree.ResolvableTypeReference {
   782      return u.val.(tree.ResolvableTypeReference)
   783  }
   784  func (u *sqlSymUnion) typeReferences() []tree.ResolvableTypeReference {
   785      return u.val.([]tree.ResolvableTypeReference)
   786  }
   787  func (u *sqlSymUnion) alterTypeAddValuePlacement() *tree.AlterTypeAddValuePlacement {
   788      return u.val.(*tree.AlterTypeAddValuePlacement)
   789  }
   790  func (u *sqlSymUnion) scheduleState() tree.ScheduleState {
   791    return u.val.(tree.ScheduleState)
   792  }
   793  func (u *sqlSymUnion) executorType() tree.ScheduledJobExecutorType {
   794    return u.val.(tree.ScheduledJobExecutorType)
   795  }
   796  func (u *sqlSymUnion) refreshDataOption() tree.RefreshDataOption {
   797    return u.val.(tree.RefreshDataOption)
   798  }
   799  func (u *sqlSymUnion) locality() *tree.Locality {
   800    return u.val.(*tree.Locality)
   801  }
   802  func (u *sqlSymUnion) survivalGoal() tree.SurvivalGoal {
   803    return u.val.(tree.SurvivalGoal)
   804  }
   805  func (u *sqlSymUnion) dataPlacement() tree.DataPlacement {
   806    return u.val.(tree.DataPlacement)
   807  }
   808  func (u *sqlSymUnion) objectNamePrefix() tree.ObjectNamePrefix {
   809  	return u.val.(tree.ObjectNamePrefix)
   810  }
   811  func (u *sqlSymUnion) objectNamePrefixList() tree.ObjectNamePrefixList {
   812      return u.val.(tree.ObjectNamePrefixList)
   813  }
   814  func (u *sqlSymUnion) abbreviatedGrant() tree.AbbreviatedGrant {
   815    return u.val.(tree.AbbreviatedGrant)
   816  }
   817  func (u *sqlSymUnion) abbreviatedRevoke() tree.AbbreviatedRevoke {
   818    return u.val.(tree.AbbreviatedRevoke)
   819  }
   820  func (u *sqlSymUnion) targetObjectType() privilege.TargetObjectType {
   821    return u.val.(privilege.TargetObjectType)
   822  }
   823  func (u *sqlSymUnion) setVar() *tree.SetVar {
   824      return u.val.(*tree.SetVar)
   825  }
   826  func (u *sqlSymUnion) cursorSensitivity() tree.CursorSensitivity {
   827      return u.val.(tree.CursorSensitivity)
   828  }
   829  func (u *sqlSymUnion) cursorScrollOption() tree.CursorScrollOption {
   830      return u.val.(tree.CursorScrollOption)
   831  }
   832  func (u *sqlSymUnion) cursorStmt() tree.CursorStmt {
   833      return u.val.(tree.CursorStmt)
   834  }
   835  func (u *sqlSymUnion) asTenantClause() tree.TenantID {
   836      return u.val.(tree.TenantID)
   837  }
   838  func (u *sqlSymUnion) routineOptions() tree.RoutineOptions {
   839      return u.val.(tree.RoutineOptions)
   840  }
   841  func (u *sqlSymUnion) functionOption() tree.RoutineOption {
   842      return u.val.(tree.RoutineOption)
   843  }
   844  func (u *sqlSymUnion) routineParams() tree.RoutineParams {
   845      return u.val.(tree.RoutineParams)
   846  }
   847  func (u *sqlSymUnion) routineParam() tree.RoutineParam {
   848      return u.val.(tree.RoutineParam)
   849  }
   850  func (u *sqlSymUnion) routineParamClass() tree.RoutineParamClass {
   851      return u.val.(tree.RoutineParamClass)
   852  }
   853  func (u *sqlSymUnion) stmts() tree.Statements {
   854      return u.val.(tree.Statements)
   855  }
   856  func (u *sqlSymUnion) routineBody() *tree.RoutineBody {
   857      return u.val.(*tree.RoutineBody)
   858  }
   859  func (u *sqlSymUnion) functionObj() tree.RoutineObj {
   860      return u.val.(tree.RoutineObj)
   861  }
   862  func (u *sqlSymUnion) routineObjs() tree.RoutineObjs {
   863      return u.val.(tree.RoutineObjs)
   864  }
   865  func (u *sqlSymUnion) tenantReplicationOptions() *tree.TenantReplicationOptions {
   866    return u.val.(*tree.TenantReplicationOptions)
   867  }
   868  func (u *sqlSymUnion) showRangesOpts() *tree.ShowRangesOptions {
   869      return u.val.(*tree.ShowRangesOptions)
   870  }
   871  func (u *sqlSymUnion) tenantSpec() *tree.TenantSpec {
   872      return u.val.(*tree.TenantSpec)
   873  }
   874  func (u *sqlSymUnion) likeTenantSpec() *tree.LikeTenantSpec {
   875      return u.val.(*tree.LikeTenantSpec)
   876  }
   877  func (u *sqlSymUnion) cteMaterializeClause() tree.CTEMaterializeClause {
   878      return u.val.(tree.CTEMaterializeClause)
   879  }
   880  func (u *sqlSymUnion) showTenantOpts() tree.ShowTenantOptions {
   881      return u.val.(tree.ShowTenantOptions)
   882  }
   883  func (u *sqlSymUnion) showCreateFormatOption() tree.ShowCreateFormatOption {
   884      return u.val.(tree.ShowCreateFormatOption)
   885  }
   886  func (u *sqlSymUnion) beginTransaction() *tree.BeginTransaction {
   887      return u.val.(*tree.BeginTransaction)
   888  }
   889  %}
   890  
   891  // NB: the %token definitions must come before the %type definitions in this
   892  // file to work around a bug in goyacc. See #16369 for more details.
   893  
   894  // Non-keyword token types.
   895  %token <str> IDENT SCONST BCONST BITCONST
   896  %token <*tree.NumVal> ICONST FCONST
   897  %token <*tree.Placeholder> PLACEHOLDER
   898  %token <str> TYPECAST TYPEANNOTATE DOT_DOT
   899  %token <str> LESS_EQUALS GREATER_EQUALS NOT_EQUALS
   900  %token <str> NOT_REGMATCH REGIMATCH NOT_REGIMATCH
   901  %token <str> ERROR
   902  
   903  // If you want to make any keyword changes, add the new keyword here as well as
   904  // to the appropriate one of the reserved-or-not-so-reserved keyword lists,
   905  // below; search this file for "Keyword category lists".
   906  
   907  // Ordinary key words in alphabetical order.
   908  %token <str> ABORT ABSOLUTE ACCESS ACTION ADD ADMIN AFTER AGGREGATE
   909  %token <str> ALL ALTER ALWAYS ANALYSE ANALYZE AND AND_AND ANY ANNOTATE_TYPE ARRAY AS ASC AS_JSON AT_AT
   910  %token <str> ASENSITIVE ASYMMETRIC AT ATOMIC ATTRIBUTE AUTHORIZATION AUTOMATIC AVAILABILITY
   911  
   912  %token <str> BACKUP BACKUPS BACKWARD BATCH BEFORE BEGIN BETWEEN BIGINT BIGSERIAL BINARY BIT
   913  %token <str> BUCKET_COUNT
   914  %token <str> BOOLEAN BOTH BOX2D BUNDLE BY
   915  
   916  %token <str> CACHE CALL CALLED CANCEL CANCELQUERY CAPABILITIES CAPABILITY CASCADE CASE CAST CBRT CHANGEFEED CHAR
   917  %token <str> CHARACTER CHARACTERISTICS CHECK CHECK_FILES CLOSE
   918  %token <str> CLUSTER CLUSTERS COALESCE COLLATE COLLATION COLUMN COLUMNS COMMENT COMMENTS COMMIT
   919  %token <str> COMMITTED COMPACT COMPLETE COMPLETIONS CONCAT CONCURRENTLY CONFIGURATION CONFIGURATIONS CONFIGURE
   920  %token <str> CONFLICT CONNECTION CONNECTIONS CONSTRAINT CONSTRAINTS CONTAINS CONTROLCHANGEFEED CONTROLJOB
   921  %token <str> CONVERSION CONVERT COPY COST COVERING CREATE CREATEDB CREATELOGIN CREATEROLE
   922  %token <str> CROSS CSV CUBE CURRENT CURRENT_CATALOG CURRENT_DATE CURRENT_SCHEMA
   923  %token <str> CURRENT_ROLE CURRENT_TIME CURRENT_TIMESTAMP
   924  %token <str> CURRENT_USER CURSOR CYCLE
   925  
   926  %token <str> DATA DATABASE DATABASES DATE DAY DEBUG_IDS DEBUG_PAUSE_ON DEC DEBUG_DUMP_METADATA_SST DECIMAL DEFAULT DEFAULTS DEFINER
   927  %token <str> DEALLOCATE DECLARE DEFERRABLE DEFERRED DELETE DELIMITER DEPENDS DESC DESTINATION DETACHED DETAILS
   928  %token <str> DISCARD DISTINCT DO DOMAIN DOUBLE DROP
   929  
   930  %token <str> ELSE ENCODING ENCRYPTED ENCRYPTION_INFO_DIR ENCRYPTION_PASSPHRASE END ENUM ENUMS ESCAPE EXCEPT EXCLUDE EXCLUDING
   931  %token <str> EXISTS EXECUTE EXECUTION EXPERIMENTAL
   932  %token <str> EXPERIMENTAL_FINGERPRINTS EXPERIMENTAL_REPLICA
   933  %token <str> EXPERIMENTAL_AUDIT EXPERIMENTAL_RELOCATE
   934  %token <str> EXPIRATION EXPLAIN EXPORT EXTENSION EXTERNAL EXTRACT EXTRACT_DURATION EXTREMES
   935  
   936  %token <str> FAILURE FALSE FAMILY FETCH FETCHVAL FETCHTEXT FETCHVAL_PATH FETCHTEXT_PATH
   937  %token <str> FILES FILTER
   938  %token <str> FIRST FLOAT FLOAT4 FLOAT8 FLOORDIV FOLLOWING FOR FORCE FORCE_INDEX
   939  %token <str> FORCE_NOT_NULL FORCE_NULL FORCE_QUOTE FORCE_ZIGZAG
   940  %token <str> FOREIGN FORMAT FORWARD FREEZE FROM FULL FUNCTION FUNCTIONS
   941  
   942  %token <str> GENERATED GEOGRAPHY GEOMETRY GEOMETRYM GEOMETRYZ GEOMETRYZM
   943  %token <str> GEOMETRYCOLLECTION GEOMETRYCOLLECTIONM GEOMETRYCOLLECTIONZ GEOMETRYCOLLECTIONZM
   944  %token <str> GLOBAL GOAL GRANT GRANTEE GRANTS GREATEST GROUP GROUPING GROUPS
   945  
   946  %token <str> HAVING HASH HEADER HIGH HISTOGRAM HOLD HOUR
   947  
   948  %token <str> IDENTITY
   949  %token <str> IF IFERROR IFNULL IGNORE_FOREIGN_KEYS ILIKE IMMEDIATE IMMUTABLE IMPORT IN INCLUDE
   950  %token <str> INCLUDING INCLUDE_ALL_SECONDARY_TENANTS INCLUDE_ALL_VIRTUAL_CLUSTERS INCREMENT INCREMENTAL INCREMENTAL_LOCATION
   951  %token <str> INET INET_CONTAINED_BY_OR_EQUALS
   952  %token <str> INET_CONTAINS_OR_EQUALS INDEX INDEXES INHERITS INJECT INITIALLY
   953  %token <str> INDEX_BEFORE_PAREN INDEX_BEFORE_NAME_THEN_PAREN INDEX_AFTER_ORDER_BY_BEFORE_AT
   954  %token <str> INNER INOUT INPUT INSENSITIVE INSERT INT INTEGER
   955  %token <str> INTERSECT INTERVAL INTO INTO_DB INVERTED INVOKER IS ISERROR ISNULL ISOLATION
   956  
   957  %token <str> JOB JOBS JOIN JSON JSONB JSON_SOME_EXISTS JSON_ALL_EXISTS
   958  
   959  %token <str> KEY KEYS KMS KV
   960  
   961  %token <str> LABEL LANGUAGE LAST LATERAL LATEST LC_CTYPE LC_COLLATE
   962  %token <str> LEADING LEASE LEAST LEAKPROOF LEFT LESS LEVEL LIKE LIMIT
   963  %token <str> LINESTRING LINESTRINGM LINESTRINGZ LINESTRINGZM
   964  %token <str> LIST LOCAL LOCALITY LOCALTIME LOCALTIMESTAMP LOCKED LOGIN LOOKUP LOW LSHIFT
   965  
   966  %token <str> MATCH MATERIALIZED MERGE MINVALUE MAXVALUE METHOD MINUTE MODIFYCLUSTERSETTING MODIFYSQLCLUSTERSETTING MONTH MOVE
   967  %token <str> MULTILINESTRING MULTILINESTRINGM MULTILINESTRINGZ MULTILINESTRINGZM
   968  %token <str> MULTIPOINT MULTIPOINTM MULTIPOINTZ MULTIPOINTZM
   969  %token <str> MULTIPOLYGON MULTIPOLYGONM MULTIPOLYGONZ MULTIPOLYGONZM
   970  
   971  %token <str> NAN NAME NAMES NATURAL NEVER NEW_DB_NAME NEW_KMS NEXT NO NOCANCELQUERY NOCONTROLCHANGEFEED
   972  %token <str> NOCONTROLJOB NOCREATEDB NOCREATELOGIN NOCREATEROLE NOLOGIN NOMODIFYCLUSTERSETTING NOREPLICATION
   973  %token <str> NOSQLLOGIN NO_INDEX_JOIN NO_ZIGZAG_JOIN NO_FULL_SCAN NONE NONVOTERS NORMAL NOT
   974  %token <str> NOTHING NOTHING_AFTER_RETURNING
   975  %token <str> NOTNULL
   976  %token <str> NOVIEWACTIVITY NOVIEWACTIVITYREDACTED NOVIEWCLUSTERSETTING NOWAIT NULL NULLIF NULLS NUMERIC
   977  
   978  %token <str> OF OFF OFFSET OID OIDS OIDVECTOR OLD_KMS ON ONLY OPT OPTION OPTIONS OR
   979  %token <str> ORDER ORDINALITY OTHERS OUT OUTER OVER OVERLAPS OVERLAY OWNED OWNER OPERATOR
   980  
   981  %token <str> PARALLEL PARENT PARTIAL PARTITION PARTITIONS PASSWORD PAUSE PAUSED PHYSICAL PLACEMENT PLACING
   982  %token <str> PLAN PLANS POINT POINTM POINTZ POINTZM POLYGON POLYGONM POLYGONZ POLYGONZM
   983  %token <str> POSITION PRECEDING PRECISION PREPARE PRESERVE PRIMARY PRIOR PRIORITY PRIVILEGES
   984  %token <str> PROCEDURAL PROCEDURE PROCEDURES PUBLIC PUBLICATION
   985  
   986  %token <str> QUERIES QUERY QUOTE
   987  
   988  %token <str> RANGE RANGES READ REAL REASON REASSIGN RECURSIVE RECURRING REDACT REF REFERENCES REFRESH
   989  %token <str> REGCLASS REGION REGIONAL REGIONS REGNAMESPACE REGPROC REGPROCEDURE REGROLE REGTYPE REINDEX
   990  %token <str> RELATIVE RELOCATE REMOVE_PATH REMOVE_REGIONS RENAME REPEATABLE REPLACE REPLICATION
   991  %token <str> RELEASE RESET RESTART RESTORE RESTRICT RESTRICTED RESUME RETENTION RETURNING RETURN RETURNS RETRY REVISION_HISTORY
   992  %token <str> REVOKE RIGHT ROLE ROLES ROLLBACK ROLLUP ROUTINES ROW ROWS RSHIFT RULE RUNNING
   993  
   994  %token <str> SAVEPOINT SCANS SCATTER SCHEDULE SCHEDULES SCROLL SCHEMA SCHEMA_ONLY SCHEMAS SCRUB
   995  %token <str> SEARCH SECOND SECONDARY SECURITY SELECT SEQUENCE SEQUENCES
   996  %token <str> SERIALIZABLE SERVER SERVICE SESSION SESSIONS SESSION_USER SET SETOF SETS SETTING SETTINGS
   997  %token <str> SHARE SHARED SHOW SIMILAR SIMPLE SIZE SKIP SKIP_LOCALITIES_CHECK SKIP_MISSING_FOREIGN_KEYS
   998  %token <str> SKIP_MISSING_SEQUENCES SKIP_MISSING_SEQUENCE_OWNERS SKIP_MISSING_VIEWS SKIP_MISSING_UDFS SMALLINT SMALLSERIAL
   999  %token <str> SNAPSHOT SOME SPLIT SQL SQLLOGIN
  1000  %token <str> STABLE START STATE STATISTICS STATUS STDIN STDOUT STOP STREAM STRICT STRING STORAGE STORE STORED STORING SUBSTRING SUPER
  1001  %token <str> SUPPORT SURVIVE SURVIVAL SYMMETRIC SYNTAX SYSTEM SQRT SUBSCRIPTION STATEMENTS
  1002  
  1003  %token <str> TABLE TABLES TABLESPACE TEMP TEMPLATE TEMPORARY TENANT TENANT_NAME TENANTS TESTING_RELOCATE TEXT THEN
  1004  %token <str> TIES TIME TIMETZ TIMESTAMP TIMESTAMPTZ TO THROTTLING TRAILING TRACE
  1005  %token <str> TRANSACTION TRANSACTIONS TRANSFER TRANSFORM TREAT TRIGGER TRIM TRUE
  1006  %token <str> TRUNCATE TRUSTED TYPE TYPES
  1007  %token <str> TRACING
  1008  
  1009  %token <str> UNBOUNDED UNCOMMITTED UNION UNIQUE UNKNOWN UNLISTEN UNLOGGED UNSAFE_RESTORE_INCOMPATIBLE_VERSION UNSPLIT
  1010  %token <str> UPDATE UPDATES_CLUSTER_MONITORING_METRICS UPSERT UNSET UNTIL USE USER USERS USING UUID
  1011  
  1012  %token <str> VALID VALIDATE VALUE VALUES VARBIT VARCHAR VARIADIC VERIFY_BACKUP_TABLE_DATA VIEW VARYING VIEWACTIVITY VIEWACTIVITYREDACTED VIEWDEBUG
  1013  %token <str> VIEWCLUSTERMETADATA VIEWCLUSTERSETTING VIRTUAL VISIBLE INVISIBLE VISIBILITY VOLATILE VOTERS
  1014  %token <str> VIRTUAL_CLUSTER_NAME VIRTUAL_CLUSTER
  1015  
  1016  %token <str> WHEN WHERE WINDOW WITH WITHIN WITHOUT WORK WRITE
  1017  
  1018  %token <str> YEAR
  1019  
  1020  %token <str> ZONE
  1021  
  1022  // The grammar thinks these are keywords, but they are not in any category
  1023  // and so can never be entered directly. The filter in scan.go creates these
  1024  // tokens when required (based on looking one token ahead).
  1025  // Reference: pkg/sql/parser/lexer.go
  1026  //
  1027  // - NOT_LA exists so that productions such as NOT LIKE can be given the same
  1028  // precedence as LIKE; otherwise they'd effectively have the same precedence as
  1029  // NOT, at least with respect to their left-hand subexpression.
  1030  // - WITH_LA is needed to make the grammar LALR(1).
  1031  // - GENERATED_ALWAYS is needed to support the Postgres syntax for computed
  1032  // columns along with our family related extensions (CREATE FAMILY/CREATE FAMILY
  1033  // family_name).
  1034  // - RESET_ALL is used to differentiate `RESET var` from `RESET ALL`.
  1035  // - ROLE_ALL and USER_ALL are used in ALTER ROLE statements that affect all
  1036  // roles.
  1037  // - ON_LA is needed for ON UPDATE and ON DELETE expressions for foreign key
  1038  // references.
  1039  // - TENANT_ALL is used to differentiate `ALTER TENANT <id>` from
  1040  // `ALTER TENANT ALL`. Ditto `CLUSTER_ALL` and `CLUSTER ALL`.
  1041  %token NOT_LA NULLS_LA WITH_LA AS_LA GENERATED_ALWAYS GENERATED_BY_DEFAULT RESET_ALL ROLE_ALL
  1042  %token USER_ALL ON_LA TENANT_ALL CLUSTER_ALL SET_TRACING
  1043  
  1044  %union {
  1045    id    int32
  1046    pos   int32
  1047    str   string
  1048    union sqlSymUnion
  1049  }
  1050  
  1051  %type <tree.Statement> stmt_block
  1052  %type <tree.Statement> stmt stmt_without_legacy_transaction
  1053  
  1054  
  1055  %type <tree.Statement> alter_stmt
  1056  %type <tree.Statement> alter_changefeed_stmt
  1057  %type <tree.Statement> alter_backup_stmt
  1058  %type <tree.Statement> alter_ddl_stmt
  1059  %type <tree.Statement> alter_table_stmt
  1060  %type <tree.Statement> alter_index_stmt
  1061  %type <tree.Statement> alter_view_stmt
  1062  %type <tree.Statement> alter_sequence_stmt
  1063  %type <tree.Statement> alter_database_stmt
  1064  %type <tree.Statement> alter_range_stmt
  1065  %type <tree.Statement> alter_partition_stmt
  1066  %type <tree.Statement> alter_role_stmt
  1067  %type <*tree.SetVar> set_or_reset_clause
  1068  %type <tree.Statement> alter_type_stmt
  1069  %type <tree.Statement> alter_schema_stmt
  1070  %type <tree.Statement> alter_unsupported_stmt
  1071  %type <tree.Statement> alter_func_stmt
  1072  %type <tree.Statement> alter_proc_stmt
  1073  
  1074  // ALTER RANGE
  1075  %type <tree.Statement> alter_zone_range_stmt
  1076  %type <tree.Statement> alter_range_relocate_stmt
  1077  
  1078  // ALTER TABLE
  1079  %type <tree.Statement> alter_onetable_stmt
  1080  %type <tree.Statement> alter_split_stmt
  1081  %type <tree.Statement> alter_unsplit_stmt
  1082  %type <tree.Statement> alter_rename_table_stmt
  1083  %type <tree.Statement> alter_scatter_stmt
  1084  %type <tree.Statement> alter_relocate_stmt
  1085  %type <tree.Statement> alter_zone_table_stmt
  1086  %type <tree.Statement> alter_table_set_schema_stmt
  1087  %type <tree.Statement> alter_table_locality_stmt
  1088  %type <tree.Statement> alter_table_owner_stmt
  1089  
  1090  // ALTER VIRTUAL CLUSTER
  1091  %type <tree.Statement> alter_virtual_cluster_stmt
  1092  
  1093  // ALTER VIRTUAL CLUSTER CAPABILITY
  1094  %type <tree.Statement> virtual_cluster_capability virtual_cluster_capability_list
  1095  
  1096  // ALTER VIRTUAL CLUSTER SET CLUSTER SETTING
  1097  %type <tree.Statement> alter_virtual_cluster_csetting_stmt
  1098  
  1099  // ALTER VIRTUAL CLUSTER CAPABILITY
  1100  %type <tree.Statement> alter_virtual_cluster_capability_stmt
  1101  
  1102  // Other ALTER VIRTUAL CLUSTER statements.
  1103  %type <tree.Statement> alter_virtual_cluster_replication_stmt
  1104  %type <tree.Statement> alter_virtual_cluster_rename_stmt
  1105  %type <tree.Statement> alter_virtual_cluster_service_stmt
  1106  
  1107  // ALTER PARTITION
  1108  %type <tree.Statement> alter_zone_partition_stmt
  1109  
  1110  // ALTER DATABASE
  1111  %type <tree.Statement> alter_rename_database_stmt
  1112  %type <tree.Statement> alter_database_to_schema_stmt
  1113  %type <tree.Statement> alter_database_add_region_stmt
  1114  %type <tree.Statement> alter_database_drop_region_stmt
  1115  %type <tree.Statement> alter_database_survival_goal_stmt
  1116  %type <tree.Statement> alter_database_primary_region_stmt
  1117  %type <tree.Statement> alter_zone_database_stmt
  1118  %type <tree.Statement> alter_database_owner
  1119  %type <tree.Statement> alter_database_placement_stmt
  1120  %type <tree.Statement> alter_database_set_stmt
  1121  %type <tree.Statement> alter_database_add_super_region
  1122  %type <tree.Statement> alter_database_alter_super_region
  1123  %type <tree.Statement> alter_database_drop_super_region
  1124  %type <tree.Statement> alter_database_set_secondary_region_stmt
  1125  %type <tree.Statement> alter_database_drop_secondary_region
  1126  %type <tree.Statement> alter_database_set_zone_config_extension_stmt
  1127  
  1128  // ALTER INDEX
  1129  %type <tree.Statement> alter_oneindex_stmt
  1130  %type <tree.Statement> alter_scatter_index_stmt
  1131  %type <tree.Statement> alter_split_index_stmt
  1132  %type <tree.Statement> alter_unsplit_index_stmt
  1133  %type <tree.Statement> alter_rename_index_stmt
  1134  %type <tree.Statement> alter_relocate_index_stmt
  1135  %type <tree.Statement> alter_zone_index_stmt
  1136  %type <tree.Statement> alter_index_visible_stmt
  1137  
  1138  // ALTER VIEW
  1139  %type <tree.Statement> alter_rename_view_stmt
  1140  %type <tree.Statement> alter_view_set_schema_stmt
  1141  %type <tree.Statement> alter_view_owner_stmt
  1142  
  1143  // ALTER SEQUENCE
  1144  %type <tree.Statement> alter_rename_sequence_stmt
  1145  %type <tree.Statement> alter_sequence_options_stmt
  1146  %type <tree.Statement> alter_sequence_set_schema_stmt
  1147  %type <tree.Statement> alter_sequence_owner_stmt
  1148  
  1149  // ALTER DEFAULT PRIVILEGES
  1150  %type <tree.Statement> alter_default_privileges_stmt
  1151  
  1152  // ALTER FUNCTION
  1153  %type <tree.Statement> alter_func_options_stmt
  1154  %type <tree.Statement> alter_func_rename_stmt
  1155  %type <tree.Statement> alter_func_set_schema_stmt
  1156  %type <tree.Statement> alter_func_owner_stmt
  1157  %type <tree.Statement> alter_func_dep_extension_stmt
  1158  
  1159  // ALTER PROCEDURE
  1160  %type <tree.Statement> alter_proc_rename_stmt
  1161  %type <tree.Statement> alter_proc_set_schema_stmt
  1162  %type <tree.Statement> alter_proc_owner_stmt
  1163  
  1164  %type <tree.Statement> backup_stmt
  1165  %type <tree.Statement> begin_stmt
  1166  
  1167  %type <tree.Statement> call_stmt
  1168  
  1169  %type <tree.Statement> cancel_stmt
  1170  %type <tree.Statement> cancel_jobs_stmt
  1171  %type <tree.Statement> cancel_queries_stmt
  1172  %type <tree.Statement> cancel_sessions_stmt
  1173  %type <tree.Statement> cancel_all_jobs_stmt
  1174  
  1175  // SCRUB
  1176  %type <tree.Statement> scrub_stmt
  1177  %type <tree.Statement> scrub_database_stmt
  1178  %type <tree.Statement> scrub_table_stmt
  1179  %type <tree.ScrubOptions> opt_scrub_options_clause
  1180  %type <tree.ScrubOptions> scrub_option_list
  1181  %type <tree.ScrubOption> scrub_option
  1182  
  1183  %type <tree.Statement> comment_stmt
  1184  %type <tree.Statement> commit_stmt
  1185  %type <tree.Statement> copy_stmt
  1186  
  1187  %type <tree.Statement> create_stmt
  1188  %type <tree.Statement> create_schedule_stmt
  1189  %type <tree.Statement> create_changefeed_stmt create_schedule_for_changefeed_stmt
  1190  %type <tree.Statement> create_ddl_stmt
  1191  %type <tree.Statement> create_database_stmt
  1192  %type <tree.Statement> create_extension_stmt
  1193  %type <tree.Statement> create_external_connection_stmt
  1194  %type <tree.Statement> create_index_stmt
  1195  %type <tree.Statement> create_role_stmt
  1196  %type <tree.Statement> create_schedule_for_backup_stmt
  1197  %type <tree.Statement> alter_backup_schedule
  1198  %type <tree.Statement> create_schema_stmt
  1199  %type <tree.Statement> create_table_stmt
  1200  %type <tree.Statement> create_table_as_stmt
  1201  %type <tree.Statement> create_virtual_cluster_stmt
  1202  %type <tree.Statement> create_view_stmt
  1203  %type <tree.Statement> create_sequence_stmt
  1204  %type <tree.Statement> create_func_stmt
  1205  %type <tree.Statement> create_proc_stmt
  1206  
  1207  %type <*tree.LikeTenantSpec> opt_like_virtual_cluster
  1208  
  1209  %type <tree.Statement> create_stats_stmt
  1210  %type <*tree.CreateStatsOptions> opt_create_stats_options
  1211  %type <*tree.CreateStatsOptions> create_stats_option_list
  1212  %type <*tree.CreateStatsOptions> create_stats_option
  1213  
  1214  %type <tree.Statement> create_type_stmt
  1215  %type <tree.Statement> delete_stmt
  1216  %type <tree.Statement> discard_stmt
  1217  
  1218  %type <tree.Statement> drop_stmt
  1219  %type <tree.Statement> drop_ddl_stmt
  1220  %type <tree.Statement> drop_database_stmt
  1221  %type <tree.Statement> drop_external_connection_stmt
  1222  %type <tree.Statement> drop_index_stmt
  1223  %type <tree.Statement> drop_role_stmt
  1224  %type <tree.Statement> drop_schema_stmt
  1225  %type <tree.Statement> drop_table_stmt
  1226  %type <tree.Statement> drop_type_stmt
  1227  %type <tree.Statement> drop_view_stmt
  1228  %type <tree.Statement> drop_sequence_stmt
  1229  %type <tree.Statement> drop_func_stmt
  1230  %type <tree.Statement> drop_proc_stmt
  1231  %type <tree.Statement> drop_virtual_cluster_stmt
  1232  %type <bool>           opt_immediate
  1233  
  1234  %type <tree.Statement> analyze_stmt
  1235  %type <tree.Statement> explain_stmt
  1236  %type <tree.Statement> prepare_stmt
  1237  %type <tree.Statement> preparable_stmt
  1238  %type <tree.Statement> explainable_stmt
  1239  %type <tree.Statement> row_source_extension_stmt
  1240  %type <tree.Statement> copy_to_stmt
  1241  %type <tree.Statement> export_stmt
  1242  %type <tree.Statement> execute_stmt
  1243  %type <tree.Statement> deallocate_stmt
  1244  %type <tree.Statement> grant_stmt
  1245  %type <tree.Statement> insert_stmt
  1246  %type <tree.Statement> import_stmt
  1247  %type <tree.Statement> pause_stmt pause_jobs_stmt pause_schedules_stmt pause_all_jobs_stmt
  1248  %type <*tree.Select>   for_schedules_clause
  1249  %type <tree.Statement> reassign_owned_by_stmt
  1250  %type <tree.Statement> drop_owned_by_stmt
  1251  %type <tree.Statement> release_stmt
  1252  %type <tree.Statement> reset_stmt reset_session_stmt reset_csetting_stmt
  1253  %type <tree.Statement> resume_stmt resume_jobs_stmt resume_schedules_stmt resume_all_jobs_stmt
  1254  %type <tree.Statement> drop_schedule_stmt
  1255  %type <tree.Statement> restore_stmt
  1256  %type <tree.StringOrPlaceholderOptList> string_or_placeholder_opt_list
  1257  %type <[]tree.StringOrPlaceholderOptList> list_of_string_or_placeholder_opt_list
  1258  %type <tree.Statement> revoke_stmt
  1259  %type <tree.Statement> refresh_stmt
  1260  %type <*tree.Select> select_stmt
  1261  %type <tree.Statement> abort_stmt
  1262  %type <tree.Statement> rollback_stmt
  1263  %type <tree.Statement> savepoint_stmt
  1264  
  1265  %type <tree.Statement> preparable_set_stmt nonpreparable_set_stmt
  1266  %type <tree.Statement> set_local_stmt
  1267  %type <tree.Statement> set_session_stmt
  1268  %type <tree.Statement> set_csetting_stmt set_or_reset_csetting_stmt
  1269  %type <tree.Statement> set_transaction_stmt
  1270  %type <tree.Statement> set_exprs_internal
  1271  %type <tree.Statement> generic_set
  1272  %type <tree.Statement> set_rest_more
  1273  %type <tree.Statement> set_rest
  1274  %type <tree.Statement> set_names
  1275  
  1276  %type <tree.Statement> show_stmt
  1277  %type <tree.Statement> show_backup_stmt
  1278  %type <tree.Statement> show_columns_stmt
  1279  %type <tree.Statement> show_commit_timestamp_stmt
  1280  %type <tree.Statement> show_constraints_stmt
  1281  %type <tree.Statement> show_create_stmt
  1282  %type <tree.ShowCreateFormatOption> opt_show_create_format_options
  1283  %type <tree.Statement> show_create_schedules_stmt
  1284  %type <tree.Statement> show_create_external_connections_stmt
  1285  %type <tree.Statement> show_csettings_stmt show_local_or_virtual_cluster_csettings_stmt
  1286  %type <tree.Statement> show_databases_stmt
  1287  %type <tree.Statement> show_default_privileges_stmt
  1288  %type <tree.Statement> show_enums_stmt
  1289  %type <tree.Statement> show_fingerprints_stmt
  1290  %type <tree.Statement> show_functions_stmt
  1291  %type <tree.Statement> show_procedures_stmt
  1292  %type <tree.Statement> show_grants_stmt
  1293  %type <tree.Statement> show_histogram_stmt
  1294  %type <tree.Statement> show_indexes_stmt
  1295  %type <tree.Statement> show_partitions_stmt
  1296  %type <tree.Statement> show_jobs_stmt
  1297  %type <tree.Statement> show_statements_stmt
  1298  %type <tree.Statement> show_ranges_stmt
  1299  %type <tree.Statement> show_range_for_row_stmt
  1300  %type <tree.Statement> show_locality_stmt
  1301  %type <tree.Statement> show_survival_goal_stmt
  1302  %type <tree.Statement> show_regions_stmt
  1303  %type <tree.Statement> show_roles_stmt
  1304  %type <tree.Statement> show_schemas_stmt
  1305  %type <tree.Statement> show_sequences_stmt
  1306  %type <tree.Statement> show_session_stmt
  1307  %type <tree.Statement> show_sessions_stmt
  1308  %type <tree.Statement> show_savepoint_stmt
  1309  %type <tree.Statement> show_stats_stmt
  1310  %type <tree.Statement> show_syntax_stmt
  1311  %type <tree.Statement> show_last_query_stats_stmt
  1312  %type <tree.Statement> show_tables_stmt
  1313  %type <tree.Statement> show_virtual_cluster_stmt opt_show_virtual_cluster_options show_virtual_cluster_options
  1314  %type <tree.Statement> show_trace_stmt
  1315  %type <tree.Statement> show_transaction_stmt
  1316  %type <tree.Statement> show_transactions_stmt
  1317  %type <tree.Statement> show_transfer_stmt
  1318  %type <tree.Statement> show_types_stmt
  1319  %type <tree.Statement> show_users_stmt
  1320  %type <tree.Statement> show_zone_stmt
  1321  %type <tree.Statement> show_schedules_stmt
  1322  %type <tree.Statement> show_full_scans_stmt
  1323  %type <tree.Statement> show_completions_stmt
  1324  
  1325  %type <str> statements_or_queries
  1326  
  1327  %type <str> session_var
  1328  %type <*string> comment_text
  1329  
  1330  %type <tree.Statement> transaction_stmt legacy_transaction_stmt legacy_begin_stmt legacy_end_stmt
  1331  %type <tree.Statement> truncate_stmt
  1332  %type <tree.Statement> unlisten_stmt
  1333  %type <tree.Statement> update_stmt
  1334  %type <tree.Statement> upsert_stmt
  1335  %type <tree.Statement> use_stmt
  1336  
  1337  %type <tree.Statement> close_cursor_stmt
  1338  %type <tree.Statement> declare_cursor_stmt
  1339  %type <tree.Statement> fetch_cursor_stmt
  1340  %type <tree.Statement> move_cursor_stmt
  1341  %type <tree.CursorStmt> cursor_movement_specifier
  1342  %type <bool> opt_hold opt_binary
  1343  %type <tree.CursorSensitivity> opt_sensitivity
  1344  %type <tree.CursorScrollOption> opt_scroll
  1345  %type <int64> opt_forward_backward forward_backward
  1346  %type <int64> next_prior
  1347  
  1348  %type <tree.Statement> reindex_stmt
  1349  
  1350  %type <[]string> opt_incremental
  1351  %type <tree.KVOption> kv_option
  1352  %type <[]tree.KVOption> kv_option_list opt_with_options var_set_list opt_with_schedule_options
  1353  %type <*tree.BackupOptions> opt_with_backup_options backup_options backup_options_list
  1354  %type <*tree.RestoreOptions> opt_with_restore_options restore_options restore_options_list
  1355  %type <*tree.TenantReplicationOptions> opt_with_replication_options replication_options replication_options_list
  1356  %type <tree.ShowBackupDetails> show_backup_details
  1357  %type <*tree.ShowJobOptions> show_job_options show_job_options_list
  1358  %type <*tree.ShowBackupOptions> opt_with_show_backup_options show_backup_options show_backup_options_list show_backup_connection_options opt_with_show_backup_connection_options_list show_backup_connection_options_list
  1359  %type <*tree.CopyOptions> opt_with_copy_options copy_options copy_options_list copy_generic_options copy_generic_options_list
  1360  %type <str> import_format
  1361  %type <str> storage_parameter_key
  1362  %type <tree.NameList> storage_parameter_key_list
  1363  %type <tree.StorageParam> storage_parameter
  1364  %type <[]tree.StorageParam> storage_parameter_list opt_table_with opt_with_storage_parameter_list
  1365  
  1366  %type <*tree.Select> select_no_parens
  1367  %type <tree.SelectStatement> select_clause select_with_parens simple_select values_clause table_clause simple_select_clause
  1368  %type <tree.LockingClause> for_locking_clause opt_for_locking_clause for_locking_items
  1369  %type <*tree.LockingItem> for_locking_item
  1370  %type <tree.LockingStrength> for_locking_strength
  1371  %type <tree.LockingWaitPolicy> opt_nowait_or_skip
  1372  %type <tree.SelectStatement> set_operation
  1373  
  1374  %type <tree.Expr> alter_column_default
  1375  %type <tree.Expr> alter_column_on_update
  1376  %type <tree.Expr> alter_column_visible
  1377  %type <tree.Direction> opt_asc_desc
  1378  %type <tree.NullsOrder> opt_nulls_order
  1379  
  1380  %type <tree.AlterChangefeedCmd> alter_changefeed_cmd
  1381  %type <tree.AlterChangefeedCmds> alter_changefeed_cmds
  1382  %type <tree.AlterBackupScheduleCmd> alter_backup_schedule_cmd
  1383  %type <tree.AlterBackupScheduleCmds> alter_backup_schedule_cmds
  1384  
  1385  %type <tree.BackupKMS> backup_kms
  1386  %type <tree.AlterBackupCmd> alter_backup_cmd
  1387  %type <tree.AlterBackupCmd> alter_backup_cmds
  1388  
  1389  %type <tree.AlterTableCmd> alter_table_cmd
  1390  %type <tree.AlterTableCmds> alter_table_cmds
  1391  %type <tree.AlterIndexCmd> alter_index_cmd
  1392  %type <tree.AlterIndexCmds> alter_index_cmds
  1393  
  1394  %type <tree.DropBehavior> opt_drop_behavior
  1395  
  1396  %type <tree.ValidationBehavior> opt_validate_behavior
  1397  
  1398  %type <str> opt_template_clause opt_encoding_clause opt_lc_collate_clause opt_lc_ctype_clause
  1399  %type <tree.NameList> opt_regions_list
  1400  %type <str> region_name primary_region_clause opt_primary_region_clause secondary_region_clause opt_secondary_region_clause
  1401  %type <tree.SuperRegion> super_region_clause opt_super_region_clause
  1402  %type <tree.DataPlacement> opt_placement_clause placement_clause
  1403  %type <tree.NameList> region_name_list
  1404  %type <tree.SurvivalGoal> survival_goal_clause opt_survival_goal_clause
  1405  %type <*tree.Locality> locality opt_locality
  1406  %type <int32> opt_connection_limit
  1407  
  1408  %type <tree.IsolationLevel> transaction_iso_level
  1409  %type <tree.UserPriority> transaction_user_priority
  1410  %type <tree.ReadWriteMode> transaction_read_mode
  1411  %type <tree.DeferrableMode> transaction_deferrable_mode
  1412  
  1413  %type <str> name opt_name opt_name_parens
  1414  %type <str> privilege savepoint_name
  1415  %type <tree.KVOption> role_option password_clause valid_until_clause
  1416  %type <tree.Operator> subquery_op
  1417  %type <*tree.UnresolvedName> func_name func_name_no_crdb_extra
  1418  %type <tree.ResolvableFunctionReference> func_application_name
  1419  %type <str> opt_class opt_collate
  1420  
  1421  %type <str> cursor_name database_name index_name opt_index_name column_name insert_column_item statistics_name window_name opt_in_database
  1422  %type <str> family_name opt_family_name table_alias_name constraint_name target_name zone_name partition_name collation_name
  1423  %type <str> db_object_name_component
  1424  %type <*tree.UnresolvedObjectName> table_name db_name standalone_index_name sequence_name type_name
  1425  %type <*tree.UnresolvedObjectName> view_name db_object_name simple_db_object_name complex_db_object_name
  1426  %type <[]*tree.UnresolvedObjectName> type_name_list
  1427  %type <str> schema_name opt_in_schema
  1428  %type <tree.ObjectNamePrefix>  qualifiable_schema_name opt_schema_name wildcard_pattern
  1429  %type <tree.ObjectNamePrefixList> schema_name_list
  1430  %type <tree.ObjectNamePrefixList> schema_wildcard
  1431  %type <*tree.UnresolvedName> table_pattern complex_table_pattern
  1432  %type <*tree.UnresolvedName> column_path prefixed_column_path column_path_with_star
  1433  %type <tree.TableExpr> insert_target create_stats_target analyze_target
  1434  
  1435  %type <*tree.TableIndexName> table_index_name
  1436  %type <tree.TableIndexNames> table_index_name_list
  1437  
  1438  %type <tree.Operator> all_op qual_op operator_op
  1439  
  1440  %type <tree.IsolationLevel> iso_level
  1441  %type <tree.UserPriority> user_priority
  1442  
  1443  %type <tree.TableDefs> opt_table_elem_list table_elem_list create_as_opt_col_list create_as_table_defs
  1444  %type <[]tree.LikeTableOption> like_table_option_list
  1445  %type <tree.LikeTableOption> like_table_option
  1446  %type <tree.CreateTableOnCommitSetting> opt_create_table_on_commit
  1447  %type <*tree.PartitionBy> opt_partition_by partition_by partition_by_inner
  1448  %type <*tree.PartitionByTable> opt_partition_by_table partition_by_table
  1449  %type <*tree.PartitionByIndex> opt_partition_by_index partition_by_index
  1450  %type <str> partition opt_partition
  1451  %type <str> opt_create_table_inherits
  1452  %type <tree.ListPartition> list_partition
  1453  %type <[]tree.ListPartition> list_partitions
  1454  %type <tree.RangePartition> range_partition
  1455  %type <[]tree.RangePartition> range_partitions
  1456  %type <empty> opt_all_clause
  1457  %type <empty> opt_privileges_clause
  1458  %type <bool> distinct_clause opt_with_data
  1459  %type <tree.DistinctOn> distinct_on_clause
  1460  %type <tree.NameList> opt_column_list insert_column_list opt_stats_columns query_stats_cols
  1461  // Note that "no index" variants exist to disable custom ORDER BY <index> syntax
  1462  // in some places like function calls.
  1463  %type <tree.OrderBy> sort_clause sort_clause_no_index single_sort_clause opt_sort_clause opt_sort_clause_no_index
  1464  %type <[]*tree.Order> sortby_list sortby_no_index_list
  1465  %type <tree.IndexElemList> index_params create_as_params
  1466  %type <tree.IndexInvisibility> opt_index_visible alter_index_visible
  1467  %type <tree.NameList> name_list privilege_list
  1468  %type <[]int32> opt_array_bounds
  1469  %type <*tree.Batch> opt_batch_clause
  1470  %type <tree.From> from_clause
  1471  %type <tree.TableExprs> from_list rowsfrom_list opt_from_list
  1472  %type <tree.TablePatterns> table_pattern_list
  1473  %type <tree.TableNames> db_object_name_list table_name_list view_name_list sequence_name_list opt_locked_rels
  1474  %type <tree.Exprs> expr_list opt_expr_list tuple1_ambiguous_values tuple1_unambiguous_values
  1475  %type <*tree.Tuple> expr_tuple1_ambiguous expr_tuple_unambiguous
  1476  %type <tree.NameList> attrs
  1477  %type <[]string> session_var_parts
  1478  %type <tree.SelectExprs> target_list
  1479  %type <tree.UpdateExprs> set_clause_list
  1480  %type <*tree.UpdateExpr> set_clause multiple_set_clause
  1481  %type <tree.ArraySubscripts> array_subscripts
  1482  %type <tree.GroupBy> group_clause
  1483  %type <tree.Exprs> group_by_list
  1484  %type <tree.Expr> group_by_item
  1485  %type <*tree.Limit> select_limit opt_select_limit
  1486  %type <tree.TableNames> relation_expr_list
  1487  %type <tree.ReturningClause> returning_clause
  1488  %type <tree.TableExprs> opt_using_clause
  1489  %type <tree.RefreshDataOption> opt_clear_data
  1490  
  1491  %type <tree.BatchParam> batch_param
  1492  %type <[]tree.BatchParam> batch_param_list
  1493  
  1494  %type <[]tree.SequenceOption> sequence_option_list opt_sequence_option_list
  1495  %type <tree.SequenceOption> sequence_option_elem
  1496  
  1497  %type <bool> all_or_distinct
  1498  %type <bool> with_comment
  1499  %type <empty> join_outer
  1500  %type <tree.JoinCond> join_qual
  1501  %type <str> join_type
  1502  %type <str> opt_join_hint
  1503  
  1504  %type <tree.Exprs> extract_list
  1505  %type <tree.Exprs> overlay_list
  1506  %type <tree.Exprs> position_list
  1507  %type <tree.Exprs> substr_list
  1508  %type <tree.Exprs> trim_list
  1509  %type <tree.Exprs> execute_param_clause
  1510  %type <types.IntervalTypeMetadata> opt_interval_qualifier interval_qualifier interval_second
  1511  %type <tree.Expr> overlay_placing
  1512  %type <*tree.TenantSpec> virtual_cluster_spec virtual_cluster_spec_opt_all
  1513  
  1514  %type <bool> opt_unique opt_concurrently opt_cluster opt_without_index
  1515  %type <bool> opt_index_access_method
  1516  
  1517  %type <*tree.Limit> limit_clause offset_clause opt_limit_clause
  1518  %type <tree.Expr> select_fetch_first_value
  1519  %type <empty> row_or_rows
  1520  %type <empty> first_or_next
  1521  
  1522  %type <tree.Statement> insert_rest
  1523  %type <tree.ColumnDefList> opt_col_def_list col_def_list opt_col_def_list_no_types col_def_list_no_types
  1524  %type <tree.ColumnDef> col_def
  1525  %type <*tree.OnConflict> on_conflict
  1526  
  1527  %type <tree.Statement> begin_transaction
  1528  %type <tree.TransactionModes> transaction_mode_list transaction_mode
  1529  
  1530  %type <tree.Expr> opt_hash_sharded_bucket_count
  1531  %type <*tree.ShardedIndexDef> opt_hash_sharded
  1532  %type <tree.NameList> opt_storing
  1533  %type <*tree.ColumnTableDef> column_table_def
  1534  %type <tree.TableDef> table_elem
  1535  %type <tree.Expr> where_clause opt_where_clause
  1536  %type <*tree.ArraySubscript> array_subscript
  1537  %type <tree.Expr> opt_slice_bound
  1538  %type <*tree.IndexFlags> opt_index_flags
  1539  %type <*tree.IndexFlags> index_flags_param
  1540  %type <*tree.IndexFlags> index_flags_param_list
  1541  %type <tree.Expr> a_expr b_expr c_expr d_expr typed_literal
  1542  %type <tree.Expr> substr_from substr_for
  1543  %type <tree.Expr> in_expr
  1544  %type <tree.Expr> having_clause
  1545  %type <tree.Expr> array_expr
  1546  %type <tree.Expr> interval_value
  1547  %type <[]tree.ResolvableTypeReference> type_list prep_type_clause
  1548  %type <tree.Exprs> array_expr_list
  1549  %type <*tree.Tuple> row labeled_row
  1550  %type <tree.Expr> case_expr case_arg case_default
  1551  %type <*tree.When> when_clause
  1552  %type <[]*tree.When> when_clause_list
  1553  %type <treecmp.ComparisonOperator> sub_type
  1554  %type <tree.Expr> numeric_only
  1555  %type <tree.AliasClause> alias_clause opt_alias_clause func_alias_clause opt_func_alias_clause
  1556  %type <bool> opt_ordinality opt_compact
  1557  %type <*tree.Order> sortby sortby_index
  1558  %type <tree.IndexElem> index_elem index_elem_options create_as_param
  1559  %type <tree.TableExpr> table_ref numeric_table_ref func_table
  1560  %type <tree.Exprs> rowsfrom_list
  1561  %type <tree.Expr> rowsfrom_item
  1562  %type <tree.TableExpr> joined_table
  1563  %type <*tree.UnresolvedObjectName> relation_expr
  1564  %type <tree.TableExpr> table_expr_opt_alias_idx table_name_opt_idx
  1565  %type <bool> opt_only opt_descendant
  1566  %type <tree.SelectExpr> target_elem
  1567  %type <*tree.UpdateExpr> single_set_clause
  1568  %type <tree.AsOfClause> as_of_clause opt_as_of_clause
  1569  %type <tree.Expr> opt_changefeed_sink changefeed_sink
  1570  %type <str> opt_changefeed_family
  1571  
  1572  %type <str> explain_option_name
  1573  %type <[]string> explain_option_list opt_enum_val_list enum_val_list
  1574  %type <[]tree.CompositeTypeElem> composite_type_list opt_composite_type_list
  1575  
  1576  %type <tree.ResolvableTypeReference> typename simple_typename cast_target
  1577  %type <*types.T> const_typename
  1578  %type <*tree.AlterTypeAddValuePlacement> opt_add_val_placement
  1579  %type <bool> opt_timezone
  1580  %type <*types.T> numeric opt_numeric_modifiers
  1581  %type <*types.T> opt_float
  1582  %type <*types.T> character_with_length character_without_length
  1583  %type <*types.T> const_datetime interval_type
  1584  %type <*types.T> bit_with_length bit_without_length
  1585  %type <*types.T> character_base
  1586  %type <*types.T> geo_shape_type
  1587  %type <*types.T> const_geo
  1588  %type <str> extract_arg
  1589  %type <bool> opt_varying
  1590  
  1591  %type <*tree.NumVal> signed_iconst only_signed_iconst
  1592  %type <*tree.NumVal> signed_fconst only_signed_fconst
  1593  %type <int32> iconst32
  1594  %type <int64> signed_iconst64
  1595  %type <int64> iconst64
  1596  %type <tree.Expr> var_value
  1597  %type <tree.Exprs> var_list
  1598  %type <tree.NameList> var_name
  1599  %type <str> unrestricted_name type_function_name type_function_name_no_crdb_extra
  1600  %type <str> non_reserved_word
  1601  %type <str> non_reserved_word_or_sconst
  1602  %type <tree.RoleSpec> role_spec opt_owner_clause
  1603  %type <tree.RoleSpecList> role_spec_list
  1604  %type <tree.Expr> zone_value
  1605  %type <tree.Expr> string_or_placeholder
  1606  %type <tree.Expr> string_or_placeholder_list
  1607  %type <str> region_or_regions
  1608  
  1609  %type <str> unreserved_keyword type_func_name_keyword type_func_name_no_crdb_extra_keyword type_func_name_crdb_extra_keyword
  1610  %type <str> bare_label_keywords bare_col_label
  1611  %type <str> col_name_keyword reserved_keyword cockroachdb_extra_reserved_keyword extra_var_value
  1612  
  1613  %type <tree.ResolvableTypeReference> complex_type_name
  1614  %type <str> general_type_name
  1615  
  1616  %type <tree.ConstraintTableDef> table_constraint constraint_elem create_as_constraint_def create_as_constraint_elem
  1617  %type <tree.TableDef> index_def
  1618  %type <tree.TableDef> family_def
  1619  %type <[]tree.NamedColumnQualification> col_qual_list create_as_col_qual_list
  1620  %type <tree.NamedColumnQualification> col_qualification create_as_col_qualification
  1621  %type <tree.ColumnQualification> col_qualification_elem create_as_col_qualification_elem
  1622  %type <tree.CompositeKeyMatchMethod> key_match
  1623  %type <tree.ReferenceActions> reference_actions
  1624  %type <tree.ReferenceAction> reference_action reference_on_delete reference_on_update
  1625  
  1626  %type <tree.Expr> func_application func_expr_common_subexpr special_function
  1627  %type <tree.Expr> func_expr func_expr_windowless
  1628  %type <empty> opt_with
  1629  %type <*tree.With> with_clause opt_with_clause
  1630  %type <[]*tree.CTE> cte_list
  1631  %type <*tree.CTE> common_table_expr
  1632  %type <tree.CTEMaterializeClause> materialize_clause
  1633  
  1634  %type <tree.Expr> within_group_clause
  1635  %type <tree.Expr> filter_clause
  1636  %type <tree.Exprs> opt_partition_clause
  1637  %type <tree.Window> window_clause window_definition_list
  1638  %type <*tree.WindowDef> window_definition over_clause window_specification
  1639  %type <str> opt_existing_window_name
  1640  %type <*tree.WindowFrame> opt_frame_clause
  1641  %type <tree.WindowFrameBounds> frame_extent
  1642  %type <*tree.WindowFrameBound> frame_bound
  1643  %type <treewindow.WindowFrameExclusion> opt_frame_exclusion
  1644  
  1645  %type <[]tree.ColumnID> opt_tableref_col_list tableref_col_list
  1646  
  1647  %type <tree.ChangefeedTargets> changefeed_targets
  1648  %type <tree.ChangefeedTarget> changefeed_target
  1649  %type <tree.BackupTargetList> backup_targets
  1650  %type <*tree.BackupTargetList> opt_backup_targets
  1651  
  1652  %type <tree.GrantTargetList> grant_targets targets_roles target_types
  1653  %type <tree.TableExpr> changefeed_target_expr
  1654  %type <*tree.GrantTargetList> opt_on_targets_roles
  1655  %type <tree.RoleSpecList> for_grantee_clause
  1656  %type <privilege.List> privileges
  1657  %type <[]tree.KVOption> opt_role_options role_options
  1658  %type <tree.AuditMode> audit_mode
  1659  
  1660  %type <str> relocate_kw
  1661  %type <tree.RelocateSubject> relocate_subject relocate_subject_nonlease
  1662  
  1663  %type <*tree.SetZoneConfig> set_zone_config
  1664  
  1665  %type <tree.Expr> opt_alter_column_using
  1666  
  1667  %type <tree.Persistence> opt_temp
  1668  %type <tree.Persistence> opt_persistence_temp_table
  1669  %type <bool> role_or_group_or_user
  1670  
  1671  %type <*tree.LabelSpec> schedule_label_spec
  1672  %type <tree.Expr>  cron_expr sconst_or_placeholder
  1673  %type <*tree.FullBackupClause> opt_full_backup_clause
  1674  %type <tree.ScheduleState> schedule_state
  1675  %type <tree.ScheduledJobExecutorType> opt_schedule_executor_type
  1676  
  1677  %type <tree.AbbreviatedGrant> abbreviated_grant_stmt
  1678  %type <tree.AbbreviatedRevoke> abbreviated_revoke_stmt
  1679  %type <bool> opt_with_grant_option
  1680  %type <tree.NameList> opt_for_roles
  1681  %type <tree.ObjectNamePrefixList>  opt_in_schemas
  1682  %type <privilege.TargetObjectType> target_object_type
  1683  
  1684  // User defined function relevant components.
  1685  %type <bool> opt_or_replace opt_return_table opt_return_set opt_no
  1686  %type <str> param_name routine_as
  1687  %type <tree.RoutineParams> opt_routine_param_with_default_list routine_param_with_default_list func_params func_params_list
  1688  %type <tree.RoutineParam> routine_param_with_default routine_param
  1689  %type <tree.ResolvableTypeReference> routine_return_type routine_param_type
  1690  %type <tree.RoutineOptions> opt_create_routine_opt_list create_routine_opt_list alter_func_opt_list
  1691  %type <tree.RoutineOption> create_routine_opt_item common_routine_opt_item
  1692  %type <tree.RoutineParamClass> routine_param_class
  1693  %type <*tree.UnresolvedObjectName> routine_create_name
  1694  %type <tree.Statement> routine_return_stmt routine_body_stmt
  1695  %type <tree.Statements> routine_body_stmt_list
  1696  %type <*tree.RoutineBody> opt_routine_body
  1697  %type <tree.RoutineObj> function_with_paramtypes
  1698  %type <tree.RoutineObjs> function_with_paramtypes_list
  1699  %type <empty> opt_link_sym
  1700  
  1701  %type <*tree.LabelSpec> label_spec
  1702  
  1703  %type <*tree.ShowRangesOptions> opt_show_ranges_options show_ranges_options
  1704  
  1705  // Precedence: lowest to highest
  1706  %nonassoc  VALUES              // see value_clause
  1707  %nonassoc  SET                 // see table_expr_opt_alias_idx
  1708  %left      UNION EXCEPT
  1709  %left      INTERSECT
  1710  %left      OR
  1711  %left      AND
  1712  %right     NOT
  1713  %nonassoc  IS ISNULL NOTNULL   // IS sets precedence for IS NULL, etc
  1714  %nonassoc  '<' '>' '=' LESS_EQUALS GREATER_EQUALS NOT_EQUALS
  1715  %nonassoc  '~' BETWEEN IN LIKE ILIKE SIMILAR NOT_REGMATCH REGIMATCH NOT_REGIMATCH NOT_LA
  1716  %nonassoc  ESCAPE              // ESCAPE must be just above LIKE/ILIKE/SIMILAR
  1717  %nonassoc  CONTAINS CONTAINED_BY '?' JSON_SOME_EXISTS JSON_ALL_EXISTS
  1718  %nonassoc  OVERLAPS
  1719  %left      POSTFIXOP           // dummy for postfix OP rules
  1720  // To support target_elem without AS, we must give IDENT an explicit priority
  1721  // between POSTFIXOP and OP. We can safely assign the same priority to various
  1722  // unreserved keywords as needed to resolve ambiguities (this can't have any
  1723  // bad effects since obviously the keywords will still behave the same as if
  1724  // they weren't keywords). We need to do this for PARTITION, RANGE, ROWS,
  1725  // GROUPS to support opt_existing_window_name; and for RANGE, ROWS, GROUPS so
  1726  // that they can follow a_expr without creating postfix-operator problems; and
  1727  // for NULL so that it can follow b_expr in col_qual_list without creating
  1728  // postfix-operator problems.
  1729  //
  1730  // To support CUBE and ROLLUP in GROUP BY without reserving them, we give them
  1731  // an explicit priority lower than '(', so that a rule with CUBE '(' will shift
  1732  // rather than reducing a conflicting rule that takes CUBE as a function name.
  1733  // Using the same precedence as IDENT seems right for the reasons given above.
  1734  //
  1735  // The frame_bound productions UNBOUNDED PRECEDING and UNBOUNDED FOLLOWING are
  1736  // even messier: since UNBOUNDED is an unreserved keyword (per spec!), there is
  1737  // no principled way to distinguish these from the productions a_expr
  1738  // PRECEDING/FOLLOWING. We hack this up by giving UNBOUNDED slightly lower
  1739  // precedence than PRECEDING and FOLLOWING. At present this doesn't appear to
  1740  // cause UNBOUNDED to be treated differently from other unreserved keywords
  1741  // anywhere else in the grammar, but it's definitely risky. We can blame any
  1742  // funny behavior of UNBOUNDED on the SQL standard, though.
  1743  %nonassoc  UNBOUNDED         // ideally should have same precedence as IDENT
  1744  %nonassoc  IDENT NULL PARTITION RANGE ROWS GROUPS PRECEDING FOLLOWING CUBE ROLLUP
  1745  %left      CONCAT FETCHVAL FETCHTEXT FETCHVAL_PATH FETCHTEXT_PATH REMOVE_PATH AT_AT  // multi-character ops
  1746  %left      '|'
  1747  %left      '#'
  1748  %left      '&'
  1749  %left      LSHIFT RSHIFT INET_CONTAINS_OR_EQUALS INET_CONTAINED_BY_OR_EQUALS AND_AND SQRT CBRT
  1750  %left      OPERATOR // if changing the last token before OPERATOR, change all instances of %prec <last token>
  1751  %left      '+' '-'
  1752  %left      '*' '/' FLOORDIV '%'
  1753  %left      '^'
  1754  %left      INTERVAL_SIMPLE   // sets precedence for interval syntax
  1755  %left      TO                // sets precedence for interval syntax
  1756  // Unary Operators
  1757  %left      AT                // sets precedence for AT TIME ZONE
  1758  %left      COLLATE
  1759  %right     UMINUS
  1760  %left      '[' ']'
  1761  %left      '(' ')'
  1762  %left      TYPEANNOTATE
  1763  %left      TYPECAST
  1764  %left      '.'
  1765  // These might seem to be low-precedence, but actually they are not part
  1766  // of the arithmetic hierarchy at all in their use as JOIN operators.
  1767  // We make them high-precedence to support their use as function names.
  1768  // They wouldn't be given a precedence at all, were it not that we need
  1769  // left-associativity among the JOIN rules themselves.
  1770  %left      JOIN CROSS LEFT FULL RIGHT INNER NATURAL
  1771  %right     HELPTOKEN
  1772  
  1773  %%
  1774  
  1775  stmt_block:
  1776    stmt
  1777    {
  1778      sqllex.(*lexer).SetStmt($1.stmt())
  1779    }
  1780  
  1781  stmt:
  1782    HELPTOKEN { return helpWith(sqllex, "") }
  1783  | stmt_without_legacy_transaction
  1784  | legacy_transaction_stmt
  1785  | /* EMPTY */
  1786    {
  1787      $$.val = tree.Statement(nil)
  1788    }
  1789  
  1790  stmt_without_legacy_transaction:
  1791    preparable_stmt            // help texts in sub-rule
  1792  | analyze_stmt               // EXTEND WITH HELP: ANALYZE
  1793  | call_stmt
  1794  | copy_stmt
  1795  | comment_stmt
  1796  | execute_stmt               // EXTEND WITH HELP: EXECUTE
  1797  | deallocate_stmt            // EXTEND WITH HELP: DEALLOCATE
  1798  | discard_stmt               // EXTEND WITH HELP: DISCARD
  1799  | grant_stmt                 // EXTEND WITH HELP: GRANT
  1800  | prepare_stmt               // EXTEND WITH HELP: PREPARE
  1801  | revoke_stmt                // EXTEND WITH HELP: REVOKE
  1802  | savepoint_stmt             // EXTEND WITH HELP: SAVEPOINT
  1803  | reassign_owned_by_stmt     // EXTEND WITH HELP: REASSIGN OWNED BY
  1804  | drop_owned_by_stmt         // EXTEND WITH HELP: DROP OWNED BY
  1805  | release_stmt               // EXTEND WITH HELP: RELEASE
  1806  | refresh_stmt               // EXTEND WITH HELP: REFRESH
  1807  | nonpreparable_set_stmt     // help texts in sub-rule
  1808  | transaction_stmt           // help texts in sub-rule
  1809  | close_cursor_stmt          // EXTEND WITH HELP: CLOSE
  1810  | declare_cursor_stmt        // EXTEND WITH HELP: DECLARE
  1811  | fetch_cursor_stmt          // EXTEND WITH HELP: FETCH
  1812  | move_cursor_stmt           // EXTEND WITH HELP: MOVE
  1813  | reindex_stmt
  1814  | unlisten_stmt
  1815  | show_commit_timestamp_stmt // EXTEND WITH HELP: SHOW COMMIT TIMESTAMP
  1816  
  1817  // %Help: ALTER
  1818  // %Category: Group
  1819  // %Text: ALTER TABLE, ALTER INDEX, ALTER VIEW, ALTER SEQUENCE, ALTER DATABASE, ALTER USER, ALTER ROLE, ALTER DEFAULT PRIVILEGES
  1820  alter_stmt:
  1821    alter_ddl_stmt      // help texts in sub-rule
  1822  | alter_role_stmt     // EXTEND WITH HELP: ALTER ROLE
  1823  | alter_virtual_cluster_stmt   /* SKIP DOC */
  1824  | alter_unsupported_stmt
  1825  | ALTER error         // SHOW HELP: ALTER
  1826  
  1827  alter_ddl_stmt:
  1828    alter_table_stmt              // EXTEND WITH HELP: ALTER TABLE
  1829  | alter_index_stmt              // EXTEND WITH HELP: ALTER INDEX
  1830  | alter_view_stmt               // EXTEND WITH HELP: ALTER VIEW
  1831  | alter_sequence_stmt           // EXTEND WITH HELP: ALTER SEQUENCE
  1832  | alter_database_stmt           // EXTEND WITH HELP: ALTER DATABASE
  1833  | alter_range_stmt              // EXTEND WITH HELP: ALTER RANGE
  1834  | alter_partition_stmt          // EXTEND WITH HELP: ALTER PARTITION
  1835  | alter_schema_stmt             // EXTEND WITH HELP: ALTER SCHEMA
  1836  | alter_type_stmt               // EXTEND WITH HELP: ALTER TYPE
  1837  | alter_default_privileges_stmt // EXTEND WITH HELP: ALTER DEFAULT PRIVILEGES
  1838  | alter_changefeed_stmt         // EXTEND WITH HELP: ALTER CHANGEFEED
  1839  | alter_backup_stmt             // EXTEND WITH HELP: ALTER BACKUP
  1840  | alter_func_stmt               // EXTEND WITH HELP: ALTER FUNCTION
  1841  | alter_proc_stmt               // EXTEND WITH HELP: ALTER PROCEDURE
  1842  | alter_backup_schedule  // EXTEND WITH HELP: ALTER BACKUP SCHEDULE
  1843  
  1844  // %Help: ALTER TABLE - change the definition of a table
  1845  // %Category: DDL
  1846  // %Text:
  1847  // ALTER TABLE [IF EXISTS] <tablename> <command> [, ...]
  1848  //
  1849  // Commands:
  1850  //   ALTER TABLE ... ADD [COLUMN] [IF NOT EXISTS] <colname> <type> [<qualifiers...>]
  1851  //   ALTER TABLE ... ADD <constraint>
  1852  //   ALTER TABLE ... DROP [COLUMN] [IF EXISTS] <colname> [RESTRICT | CASCADE]
  1853  //   ALTER TABLE ... DROP CONSTRAINT [IF EXISTS] <constraintname> [RESTRICT | CASCADE]
  1854  //   ALTER TABLE ... ALTER [COLUMN] <colname> {SET DEFAULT <expr> | DROP DEFAULT}
  1855  //   ALTER TABLE ... ALTER [COLUMN] <colname> {SET ON UPDATE <expr> | DROP ON UPDATE}
  1856  //   ALTER TABLE ... ALTER [COLUMN] <colname> DROP NOT NULL
  1857  //   ALTER TABLE ... ALTER [COLUMN] <colname> DROP STORED
  1858  //   ALTER TABLE ... ALTER [COLUMN] <colname> [SET DATA] TYPE <type> [COLLATE <collation>]
  1859  //   ALTER TABLE ... ALTER PRIMARY KEY USING COLUMNS ( <colnames...> )
  1860  //   ALTER TABLE ... RENAME TO <newname>
  1861  //   ALTER TABLE ... RENAME [COLUMN] <colname> TO <newname>
  1862  //   ALTER TABLE ... VALIDATE CONSTRAINT <constraintname>
  1863  //   ALTER TABLE ... SET (storage_param = value, ...)
  1864  //   ALTER TABLE ... SPLIT AT <selectclause> [WITH EXPIRATION <expr>]
  1865  //   ALTER TABLE ... UNSPLIT AT <selectclause>
  1866  //   ALTER TABLE ... UNSPLIT ALL
  1867  //   ALTER TABLE ... SCATTER [ FROM ( <exprs...> ) TO ( <exprs...> ) ]
  1868  //   ALTER TABLE ... INJECT STATISTICS ...  (experimental)
  1869  //   ALTER TABLE ... RELOCATE [ LEASE | VOTERS | NONVOTERS ] <selectclause>  (experimental)
  1870  //   ALTER TABLE ... PARTITION BY RANGE ( <name...> ) ( <rangespec> )
  1871  //   ALTER TABLE ... PARTITION BY LIST ( <name...> ) ( <listspec> )
  1872  //   ALTER TABLE ... PARTITION BY NOTHING
  1873  //   ALTER TABLE ... CONFIGURE ZONE <zoneconfig>
  1874  //   ALTER TABLE ... SET SCHEMA <newschemaname>
  1875  //   ALTER TABLE ... SET LOCALITY [REGIONAL BY [TABLE IN <region> | ROW] | GLOBAL]
  1876  //
  1877  // Column qualifiers:
  1878  //   [CONSTRAINT <constraintname>] {NULL | NOT NULL | UNIQUE | PRIMARY KEY | CHECK (<expr>) | DEFAULT <expr>}
  1879  //   FAMILY <familyname>, CREATE [IF NOT EXISTS] FAMILY [<familyname>]
  1880  //   REFERENCES <tablename> [( <colnames...> )]
  1881  //   COLLATE <collationname>
  1882  //
  1883  // Zone configurations:
  1884  //   DISCARD
  1885  //   USING <var> = <expr> [, ...]
  1886  //   USING <var> = COPY FROM PARENT [, ...]
  1887  //   { TO | = } <expr>
  1888  //
  1889  // %SeeAlso: WEBDOCS/alter-table.html
  1890  alter_table_stmt:
  1891    alter_onetable_stmt
  1892  | alter_relocate_stmt
  1893  | alter_split_stmt
  1894  | alter_unsplit_stmt
  1895  | alter_scatter_stmt
  1896  | alter_zone_table_stmt
  1897  | alter_rename_table_stmt
  1898  | alter_table_set_schema_stmt
  1899  | alter_table_locality_stmt
  1900  | alter_table_owner_stmt
  1901  // ALTER TABLE has its error help token here because the ALTER TABLE
  1902  // prefix is spread over multiple non-terminals.
  1903  | ALTER TABLE error     // SHOW HELP: ALTER TABLE
  1904  
  1905  // %Help: ALTER PARTITION - apply zone configurations to a partition
  1906  // %Category: DDL
  1907  // %Text:
  1908  // ALTER PARTITION <name> <command>
  1909  //
  1910  // Commands:
  1911  //   -- Alter a single partition which exists on any of a table's indexes.
  1912  //   ALTER PARTITION <partition> OF TABLE <tablename> CONFIGURE ZONE <zoneconfig>
  1913  //
  1914  //   -- Alter a partition of a specific index.
  1915  //   ALTER PARTITION <partition> OF INDEX <tablename>@<indexname> CONFIGURE ZONE <zoneconfig>
  1916  //
  1917  //   -- Alter all partitions with the same name across a table's indexes.
  1918  //   ALTER PARTITION <partition> OF INDEX <tablename>@* CONFIGURE ZONE <zoneconfig>
  1919  //
  1920  // Zone configurations:
  1921  //   DISCARD
  1922  //   USING <var> = <expr> [, ...]
  1923  //   USING <var> = COPY FROM PARENT [, ...]
  1924  //   { TO | = } <expr>
  1925  //
  1926  // %SeeAlso: WEBDOCS/configure-zone.html
  1927  alter_partition_stmt:
  1928    alter_zone_partition_stmt
  1929  | ALTER PARTITION error // SHOW HELP: ALTER PARTITION
  1930  
  1931  // %Help: ALTER VIEW - change the definition of a view
  1932  // %Category: DDL
  1933  // %Text:
  1934  // ALTER [MATERIALIZED] VIEW [IF EXISTS] <name> RENAME TO <newname>
  1935  // ALTER [MATERIALIZED] VIEW [IF EXISTS] <name> SET SCHEMA <newschemaname>
  1936  // %SeeAlso: WEBDOCS/alter-view.html
  1937  alter_view_stmt:
  1938    alter_rename_view_stmt
  1939  | alter_view_set_schema_stmt
  1940  | alter_view_owner_stmt
  1941  // ALTER VIEW has its error help token here because the ALTER VIEW
  1942  // prefix is spread over multiple non-terminals.
  1943  | ALTER VIEW error // SHOW HELP: ALTER VIEW
  1944  
  1945  // %Help: ALTER SEQUENCE - change the definition of a sequence
  1946  // %Category: DDL
  1947  // %Text:
  1948  // ALTER SEQUENCE [IF EXISTS] <name>
  1949  //   [AS <typename>]
  1950  //   [INCREMENT <increment>]
  1951  //   [MINVALUE <minvalue> | NO MINVALUE]
  1952  //   [MAXVALUE <maxvalue> | NO MAXVALUE]
  1953  //   [START [WITH] <start>]
  1954  //   [RESTART [[WITH] <restart>]]
  1955  //   [[NO] CYCLE]
  1956  // ALTER SEQUENCE [IF EXISTS] <name> RENAME TO <newname>
  1957  // ALTER SEQUENCE [IF EXISTS] <name> SET SCHEMA <newschemaname>
  1958  alter_sequence_stmt:
  1959    alter_rename_sequence_stmt
  1960  | alter_sequence_options_stmt
  1961  | alter_sequence_set_schema_stmt
  1962  | alter_sequence_owner_stmt
  1963  | ALTER SEQUENCE error // SHOW HELP: ALTER SEQUENCE
  1964  
  1965  alter_sequence_options_stmt:
  1966    ALTER SEQUENCE sequence_name sequence_option_list
  1967    {
  1968      $$.val = &tree.AlterSequence{Name: $3.unresolvedObjectName(), Options: $4.seqOpts(), IfExists: false}
  1969    }
  1970  | ALTER SEQUENCE IF EXISTS sequence_name sequence_option_list
  1971    {
  1972      $$.val = &tree.AlterSequence{Name: $5.unresolvedObjectName(), Options: $6.seqOpts(), IfExists: true}
  1973    }
  1974  
  1975  
  1976  // %Help: ALTER DATABASE - change the definition of a database
  1977  // %Category: DDL
  1978  // %Text:
  1979  // ALTER DATABASE <name> RENAME TO <newname>
  1980  // ALTER DATABASE <name> CONFIGURE ZONE <zone config>
  1981  // ALTER DATABASE <name> OWNER TO <newowner>
  1982  // ALTER DATABASE <name> CONVERT TO SCHEMA WITH PARENT <name>
  1983  // ALTER DATABASE <name> ADD REGION [IF NOT EXISTS] <region>
  1984  // ALTER DATABASE <name> DROP REGION [IF EXISTS] <region>
  1985  // ALTER DATABASE <name> PRIMARY REGION <region>
  1986  // ALTER DATABASE <name> SURVIVE <failure type>
  1987  // ALTER DATABASE <name> PLACEMENT { RESTRICTED | DEFAULT }
  1988  // ALTER DATABASE <name> SET var { TO | = } { value | DEFAULT }
  1989  // ALTER DATABASE <name> RESET { var | ALL }
  1990  // ALTER DATABASE <name> ALTER LOCALITY { GLOBAL | REGIONAL [IN <region>] } CONFIGURE ZONE <zone config>
  1991  // %SeeAlso: WEBDOCS/alter-database.html
  1992  alter_database_stmt:
  1993    alter_rename_database_stmt
  1994  | alter_zone_database_stmt
  1995  | alter_database_owner
  1996  | alter_database_to_schema_stmt
  1997  | alter_database_add_region_stmt
  1998  | alter_database_drop_region_stmt
  1999  | alter_database_survival_goal_stmt
  2000  | alter_database_primary_region_stmt
  2001  | alter_database_placement_stmt
  2002  | alter_database_set_stmt
  2003  | alter_database_add_super_region
  2004  | alter_database_alter_super_region
  2005  | alter_database_drop_super_region
  2006  | alter_database_set_secondary_region_stmt
  2007  | alter_database_drop_secondary_region
  2008  | alter_database_set_zone_config_extension_stmt
  2009  
  2010  // %Help: ALTER FUNCTION - change the definition of a function
  2011  // %Category: DDL
  2012  // %Text:
  2013  // ALTER FUNCTION name [ ( [ [ argmode ] [ argname ] argtype [, ...] ] ) ]
  2014  //    action [ ... ] [ RESTRICT ]
  2015  // ALTER FUNCTION name [ ( [ [ argmode ] [ argname ] argtype [, ...] ] ) ]
  2016  //    RENAME TO new_name
  2017  // ALTER FUNCTION name [ ( [ [ argmode ] [ argname ] argtype [, ...] ] ) ]
  2018  //    OWNER TO { new_owner | CURRENT_USER | SESSION_USER }
  2019  // ALTER FUNCTION name [ ( [ [ argmode ] [ argname ] argtype [, ...] ] ) ]
  2020  //    SET SCHEMA new_schema
  2021  //
  2022  // where action is one of:
  2023  //
  2024  //    CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT
  2025  //    IMMUTABLE | STABLE | VOLATILE
  2026  //    [ NOT ] LEAKPROOF
  2027  // %SeeAlso: WEBDOCS/alter-function.html
  2028  alter_func_stmt:
  2029    alter_func_options_stmt
  2030  | alter_func_rename_stmt
  2031  | alter_func_owner_stmt
  2032  | alter_func_set_schema_stmt
  2033  | alter_func_dep_extension_stmt
  2034  | ALTER FUNCTION error // SHOW HELP: ALTER FUNCTION
  2035  
  2036  // %Help: ALTER PROCEDURE - change the definition of a procedure
  2037  // %Category: DDL
  2038  // %Text:
  2039  // ALTER PROCEDURE name [ ( [ [ argmode ] [ argname ] argtype [, ...] ] ) ]
  2040  //    RENAME TO new_name
  2041  // ALTER PROCEDURE name [ ( [ [ argmode ] [ argname ] argtype [, ...] ] ) ]
  2042  //    OWNER TO { new_owner | CURRENT_USER | SESSION_USER }
  2043  // ALTER PROCEDURE name [ ( [ [ argmode ] [ argname ] argtype [, ...] ] ) ]
  2044  //    SET SCHEMA new_schema
  2045  //
  2046  // %SeeAlso: WEBDOCS/alter-procedure.html
  2047  alter_proc_stmt:
  2048    alter_proc_rename_stmt
  2049  | alter_proc_owner_stmt
  2050  | alter_proc_set_schema_stmt
  2051  | ALTER PROCEDURE error // SHOW HELP: ALTER PROCEDURE
  2052  
  2053  // ALTER DATABASE has its error help token here because the ALTER DATABASE
  2054  // prefix is spread over multiple non-terminals.
  2055  | ALTER DATABASE error // SHOW HELP: ALTER DATABASE
  2056  
  2057  alter_database_owner:
  2058    ALTER DATABASE database_name OWNER TO role_spec
  2059    {
  2060      $$.val = &tree.AlterDatabaseOwner{Name: tree.Name($3), Owner: $6.roleSpec()}
  2061    }
  2062  
  2063  // This form is an alias for ALTER ROLE ALL IN DATABASE <db> SET ...
  2064  alter_database_set_stmt:
  2065    ALTER DATABASE database_name set_or_reset_clause
  2066    {
  2067      $$.val = &tree.AlterRoleSet{
  2068        AllRoles: true,
  2069        DatabaseName: tree.Name($3),
  2070        IsRole: true,
  2071        SetOrReset: $4.setVar(),
  2072      }
  2073    }
  2074  
  2075  alter_database_placement_stmt:
  2076    ALTER DATABASE database_name placement_clause
  2077    {
  2078      $$.val = &tree.AlterDatabasePlacement{
  2079        Name: tree.Name($3),
  2080        Placement: $4.dataPlacement(),
  2081      }
  2082    }
  2083  
  2084  alter_database_add_region_stmt:
  2085    ALTER DATABASE database_name ADD REGION region_name
  2086    {
  2087      $$.val = &tree.AlterDatabaseAddRegion{
  2088        Name: tree.Name($3),
  2089        Region: tree.Name($6),
  2090      }
  2091    }
  2092  | ALTER DATABASE database_name ADD REGION IF NOT EXISTS region_name
  2093    {
  2094      $$.val = &tree.AlterDatabaseAddRegion{
  2095        Name: tree.Name($3),
  2096        Region: tree.Name($9),
  2097        IfNotExists: true,
  2098      }
  2099    }
  2100  
  2101  alter_database_drop_region_stmt:
  2102    ALTER DATABASE database_name DROP REGION region_name
  2103    {
  2104      $$.val = &tree.AlterDatabaseDropRegion{
  2105        Name: tree.Name($3),
  2106        Region: tree.Name($6),
  2107      }
  2108    }
  2109  | ALTER DATABASE database_name DROP REGION IF EXISTS region_name
  2110    {
  2111      $$.val = &tree.AlterDatabaseDropRegion{
  2112        Name: tree.Name($3),
  2113        Region: tree.Name($8),
  2114        IfExists: true,
  2115      }
  2116    }
  2117  
  2118  alter_database_survival_goal_stmt:
  2119    ALTER DATABASE database_name survival_goal_clause
  2120    {
  2121      $$.val = &tree.AlterDatabaseSurvivalGoal{
  2122        Name: tree.Name($3),
  2123        SurvivalGoal: $4.survivalGoal(),
  2124      }
  2125    }
  2126  
  2127  alter_database_primary_region_stmt:
  2128    ALTER DATABASE database_name primary_region_clause
  2129    {
  2130      $$.val = &tree.AlterDatabasePrimaryRegion{
  2131        Name: tree.Name($3),
  2132        PrimaryRegion: tree.Name($4),
  2133      }
  2134    }
  2135  | ALTER DATABASE database_name SET primary_region_clause
  2136    {
  2137      $$.val = &tree.AlterDatabasePrimaryRegion{
  2138        Name: tree.Name($3),
  2139        PrimaryRegion: tree.Name($5),
  2140      }
  2141    }
  2142  
  2143  alter_database_add_super_region:
  2144    ALTER DATABASE database_name ADD SUPER REGION region_name VALUES region_name_list
  2145    {
  2146      $$.val = &tree.AlterDatabaseAddSuperRegion{
  2147        DatabaseName: tree.Name($3),
  2148        SuperRegionName: tree.Name($7),
  2149        Regions: $9.nameList(),
  2150      }
  2151    }
  2152  
  2153  alter_database_drop_super_region:
  2154    ALTER DATABASE database_name DROP SUPER REGION region_name
  2155    {
  2156      $$.val = &tree.AlterDatabaseDropSuperRegion{
  2157        DatabaseName: tree.Name($3),
  2158        SuperRegionName: tree.Name($7),
  2159      }
  2160    }
  2161  
  2162  alter_database_alter_super_region:
  2163    ALTER DATABASE database_name ALTER SUPER REGION region_name VALUES region_name_list
  2164    {
  2165      $$.val = &tree.AlterDatabaseAlterSuperRegion{
  2166        DatabaseName: tree.Name($3),
  2167        SuperRegionName: tree.Name($7),
  2168        Regions: $9.nameList(),
  2169      }
  2170    }
  2171  
  2172  alter_database_set_secondary_region_stmt:
  2173     ALTER DATABASE database_name SET secondary_region_clause
  2174     {
  2175       $$.val = &tree.AlterDatabaseSecondaryRegion{
  2176         DatabaseName: tree.Name($3),
  2177         SecondaryRegion: tree.Name($5),
  2178       }
  2179     }
  2180  
  2181  alter_database_drop_secondary_region:
  2182      ALTER DATABASE database_name DROP SECONDARY REGION
  2183      {
  2184        $$.val = &tree.AlterDatabaseDropSecondaryRegion{
  2185          DatabaseName: tree.Name($3),
  2186          IfExists: false,
  2187        }
  2188      }
  2189  
  2190    | ALTER DATABASE database_name DROP SECONDARY REGION IF EXISTS
  2191      {
  2192        $$.val = &tree.AlterDatabaseDropSecondaryRegion{
  2193          DatabaseName: tree.Name($3),
  2194          IfExists: true,
  2195        }
  2196      }
  2197  
  2198  alter_database_set_zone_config_extension_stmt:
  2199    ALTER DATABASE database_name ALTER LOCALITY GLOBAL set_zone_config
  2200    {
  2201      s := $7.setZoneConfig()
  2202      $$.val = &tree.AlterDatabaseSetZoneConfigExtension{
  2203        DatabaseName:  tree.Name($3),
  2204        LocalityLevel: tree.LocalityLevelGlobal,
  2205        ZoneConfigSettings: tree.ZoneConfigSettings {
  2206          SetDefault:    s.SetDefault,
  2207          YAMLConfig:    s.YAMLConfig,
  2208          Options:       s.Options,
  2209        },
  2210      }
  2211    }
  2212  | ALTER DATABASE database_name ALTER LOCALITY REGIONAL set_zone_config
  2213    {
  2214      s := $7.setZoneConfig()
  2215      $$.val = &tree.AlterDatabaseSetZoneConfigExtension{
  2216        DatabaseName:  tree.Name($3),
  2217        LocalityLevel: tree.LocalityLevelTable,
  2218        ZoneConfigSettings: tree.ZoneConfigSettings {
  2219          SetDefault:    s.SetDefault,
  2220          YAMLConfig:    s.YAMLConfig,
  2221          Options:       s.Options,
  2222        },
  2223      }
  2224    }
  2225  | ALTER DATABASE database_name ALTER LOCALITY REGIONAL IN region_name set_zone_config
  2226    {
  2227      s := $9.setZoneConfig()
  2228      $$.val = &tree.AlterDatabaseSetZoneConfigExtension{
  2229        DatabaseName:  tree.Name($3),
  2230        LocalityLevel: tree.LocalityLevelTable,
  2231        RegionName:    tree.Name($8),
  2232        ZoneConfigSettings: tree.ZoneConfigSettings {
  2233          SetDefault:    s.SetDefault,
  2234          YAMLConfig:    s.YAMLConfig,
  2235          Options:       s.Options,
  2236        },
  2237      }
  2238    }
  2239  
  2240  // %Help: ALTER RANGE - change the parameters of a range
  2241  // %Category: DDL
  2242  // %Text:
  2243  // ALTER RANGE <zonename> <command>
  2244  //
  2245  // Commands:
  2246  //   ALTER RANGE ... CONFIGURE ZONE <zoneconfig>
  2247  //   ALTER RANGE   RELOCATE { VOTERS | NONVOTERS } FROM <store_id> TO <store_id> FOR <selectclause>
  2248  //   ALTER RANGE r RELOCATE { VOTERS | NONVOTERS } FROM <store_id> TO <store_id>
  2249  //   ALTER RANGE   RELOCATE LEASE                                  TO <store_id> FOR <selectclause>
  2250  //   ALTER RANGE r RELOCATE LEASE                                  TO <store_id>
  2251  //
  2252  // Zone configurations:
  2253  //   DISCARD
  2254  //   USING <var> = <expr> [, ...]
  2255  //   USING <var> = COPY FROM PARENT [, ...]
  2256  //   { TO | = } <expr>
  2257  //
  2258  // %SeeAlso: ALTER TABLE
  2259  alter_range_stmt:
  2260    alter_zone_range_stmt
  2261  | alter_range_relocate_stmt
  2262  | ALTER RANGE error // SHOW HELP: ALTER RANGE
  2263  
  2264  // %Help: ALTER INDEX - change the definition of an index
  2265  // %Category: DDL
  2266  // %Text:
  2267  // ALTER INDEX [IF EXISTS] <idxname> <command>
  2268  //
  2269  // Commands:
  2270  //   ALTER INDEX ... RENAME TO <newname>
  2271  //   ALTER INDEX ... SPLIT AT <selectclause> [WITH EXPIRATION <expr>]
  2272  //   ALTER INDEX ... UNSPLIT AT <selectclause>
  2273  //   ALTER INDEX ... UNSPLIT ALL
  2274  //   ALTER INDEX ... SCATTER [ FROM ( <exprs...> ) TO ( <exprs...> ) ]
  2275  //   ALTER INDEX ... RELOCATE [ LEASE | VOTERS | NONVOTERS ] <selectclause>
  2276  //   ALTER INDEX ... [VISIBLE | NOT VISIBLE | INVISIBLE | VISIBILITY ...]
  2277  //
  2278  // Zone configurations:
  2279  //   DISCARD
  2280  //   USING <var> = <expr> [, ...]
  2281  //   USING <var> = COPY FROM PARENT [, ...]
  2282  //   { TO | = } <expr>
  2283  //
  2284  // %SeeAlso: WEBDOCS/alter-index.html
  2285  alter_index_stmt:
  2286    alter_oneindex_stmt
  2287  | alter_relocate_index_stmt
  2288  | alter_split_index_stmt
  2289  | alter_unsplit_index_stmt
  2290  | alter_scatter_index_stmt
  2291  | alter_rename_index_stmt
  2292  | alter_zone_index_stmt
  2293  | alter_index_visible_stmt
  2294  // ALTER INDEX has its error help token here because the ALTER INDEX
  2295  // prefix is spread over multiple non-terminals.
  2296  | ALTER INDEX error // SHOW HELP: ALTER INDEX
  2297  
  2298  alter_onetable_stmt:
  2299    ALTER TABLE relation_expr alter_table_cmds
  2300    {
  2301      $$.val = &tree.AlterTable{Table: $3.unresolvedObjectName(), IfExists: false, Cmds: $4.alterTableCmds()}
  2302    }
  2303  | ALTER TABLE IF EXISTS relation_expr alter_table_cmds
  2304    {
  2305      $$.val = &tree.AlterTable{Table: $5.unresolvedObjectName(), IfExists: true, Cmds: $6.alterTableCmds()}
  2306    }
  2307  
  2308  alter_oneindex_stmt:
  2309    ALTER INDEX table_index_name alter_index_cmds
  2310    {
  2311      $$.val = &tree.AlterIndex{Index: $3.tableIndexName(), IfExists: false, Cmds: $4.alterIndexCmds()}
  2312    }
  2313  | ALTER INDEX IF EXISTS table_index_name alter_index_cmds
  2314    {
  2315      $$.val = &tree.AlterIndex{Index: $5.tableIndexName(), IfExists: true, Cmds: $6.alterIndexCmds()}
  2316    }
  2317  
  2318  alter_split_stmt:
  2319    ALTER TABLE table_name SPLIT AT select_stmt
  2320    {
  2321      name := $3.unresolvedObjectName().ToTableName()
  2322      $$.val = &tree.Split{
  2323        TableOrIndex: tree.TableIndexName{Table: name},
  2324        Rows: $6.slct(),
  2325        ExpireExpr: tree.Expr(nil),
  2326      }
  2327    }
  2328  | ALTER TABLE table_name SPLIT AT select_stmt WITH EXPIRATION a_expr
  2329    {
  2330      name := $3.unresolvedObjectName().ToTableName()
  2331      $$.val = &tree.Split{
  2332        TableOrIndex: tree.TableIndexName{Table: name},
  2333        Rows: $6.slct(),
  2334        ExpireExpr: $9.expr(),
  2335      }
  2336    }
  2337  
  2338  alter_split_index_stmt:
  2339    ALTER INDEX table_index_name SPLIT AT select_stmt
  2340    {
  2341      $$.val = &tree.Split{TableOrIndex: $3.tableIndexName(), Rows: $6.slct(), ExpireExpr: tree.Expr(nil)}
  2342    }
  2343  | ALTER INDEX table_index_name SPLIT AT select_stmt WITH EXPIRATION a_expr
  2344    {
  2345      $$.val = &tree.Split{TableOrIndex: $3.tableIndexName(), Rows: $6.slct(), ExpireExpr: $9.expr()}
  2346    }
  2347  
  2348  alter_unsplit_stmt:
  2349    ALTER TABLE table_name UNSPLIT AT select_stmt
  2350    {
  2351      name := $3.unresolvedObjectName().ToTableName()
  2352      $$.val = &tree.Unsplit{
  2353        TableOrIndex: tree.TableIndexName{Table: name},
  2354        Rows: $6.slct(),
  2355      }
  2356    }
  2357  | ALTER TABLE table_name UNSPLIT ALL
  2358    {
  2359      name := $3.unresolvedObjectName().ToTableName()
  2360      $$.val = &tree.Unsplit {
  2361        TableOrIndex: tree.TableIndexName{Table: name},
  2362        All: true,
  2363      }
  2364    }
  2365  
  2366  alter_unsplit_index_stmt:
  2367    ALTER INDEX table_index_name UNSPLIT AT select_stmt
  2368    {
  2369      $$.val = &tree.Unsplit{TableOrIndex: $3.tableIndexName(), Rows: $6.slct()}
  2370    }
  2371  | ALTER INDEX table_index_name UNSPLIT ALL
  2372    {
  2373      $$.val = &tree.Unsplit{TableOrIndex: $3.tableIndexName(), All: true}
  2374    }
  2375  
  2376  relocate_kw:
  2377    TESTING_RELOCATE
  2378  | EXPERIMENTAL_RELOCATE
  2379  | RELOCATE
  2380  
  2381  relocate_subject:
  2382    relocate_subject_nonlease
  2383  | LEASE
  2384    {
  2385      $$.val = tree.RelocateLease
  2386    }
  2387  
  2388  relocate_subject_nonlease:
  2389    VOTERS
  2390    {
  2391      $$.val = tree.RelocateVoters
  2392    }
  2393  | /* EMPTY */
  2394    {
  2395      // No keyword is an alias for VOTERS.
  2396      $$.val = tree.RelocateVoters
  2397    }
  2398  | NONVOTERS
  2399    {
  2400      $$.val = tree.RelocateNonVoters
  2401    }
  2402  
  2403  alter_relocate_stmt:
  2404    ALTER TABLE table_name relocate_kw relocate_subject select_stmt
  2405    {
  2406      /* SKIP DOC */
  2407      name := $3.unresolvedObjectName().ToTableName()
  2408      $$.val = &tree.Relocate{
  2409        TableOrIndex: tree.TableIndexName{Table: name},
  2410        Rows: $6.slct(),
  2411        SubjectReplicas: $5.relocateSubject(),
  2412      }
  2413    }
  2414  
  2415  alter_relocate_index_stmt:
  2416    ALTER INDEX table_index_name relocate_kw relocate_subject select_stmt
  2417    {
  2418      /* SKIP DOC */
  2419      $$.val = &tree.Relocate{
  2420        TableOrIndex: $3.tableIndexName(),
  2421        Rows: $6.slct(),
  2422        SubjectReplicas: $5.relocateSubject(),
  2423      }
  2424    }
  2425  
  2426  alter_index_visible_stmt:
  2427    ALTER INDEX table_index_name alter_index_visible
  2428    {
  2429      $$.val = &tree.AlterIndexVisible{
  2430        Index: $3.tableIndexName(),
  2431        Invisibility: $4.indexInvisibility(),
  2432        IfExists: false,
  2433      }
  2434    }
  2435  | ALTER INDEX IF EXISTS table_index_name alter_index_visible
  2436    {
  2437      $$.val = &tree.AlterIndexVisible{
  2438        Index: $5.tableIndexName(),
  2439        Invisibility: $6.indexInvisibility(),
  2440        IfExists: true,
  2441      }
  2442    }
  2443  
  2444  alter_index_visible:
  2445    NOT VISIBLE
  2446    {
  2447      $$.val = tree.IndexInvisibility{Value: 1.0}
  2448    }
  2449  | INVISIBLE
  2450    {
  2451      $$.val = tree.IndexInvisibility{Value: 1.0}
  2452    }
  2453  | VISIBLE
  2454    {
  2455      $$.val = tree.IndexInvisibility{Value: 0.0}
  2456    }
  2457  | VISIBILITY FCONST
  2458    {
  2459      visibilityConst, _ := constant.Float64Val($2.numVal().AsConstantValue())
  2460        if visibilityConst < 0.0 || visibilityConst > 1.0 {
  2461          sqllex.Error("index visibility must be between 0 and 1")
  2462          return 1
  2463        }
  2464      invisibilityConst := 1.0 - visibilityConst
  2465      $$.val = tree.IndexInvisibility{Value: invisibilityConst, FloatProvided: true}
  2466    }
  2467  
  2468  // Note: even though the ALTER RANGE ... CONFIGURE ZONE syntax only
  2469  // accepts unrestricted names in the 3rd position, such that we could
  2470  // write:
  2471  //     ALTER RANGE zone_name set_zone_config
  2472  // we have to parse a full a_expr there instead, for otherwise we get
  2473  // a reduce/reduce conflict with the ALTER RANGE ... RELOCATE variants
  2474  // below.
  2475  //
  2476  // TODO(knz): Would it make sense to extend the semantics to enable
  2477  // zone configurations on arbitrary range IDs?
  2478  alter_zone_range_stmt:
  2479    ALTER RANGE a_expr set_zone_config
  2480    {
  2481        var zoneName string
  2482        switch e := $3.expr().(type) {
  2483        case *tree.UnresolvedName:
  2484            if e.NumParts != 1 {
  2485                return setErr(sqllex, errors.New("only simple names are supported in ALTER RANGE ... CONFIGURE ZONE"))
  2486            }
  2487            zoneName = e.Parts[0]
  2488        case tree.DefaultVal:
  2489            zoneName = "default"
  2490        default:
  2491            return setErr(sqllex, errors.New("only simple names are supported in ALTER RANGE ... CONFIGURE ZONE"))
  2492       }
  2493       s := $4.setZoneConfig()
  2494       s.ZoneSpecifier = tree.ZoneSpecifier{NamedZone: tree.UnrestrictedName(zoneName)}
  2495       $$.val = s
  2496    }
  2497  
  2498  alter_range_relocate_stmt:
  2499    ALTER RANGE relocate_kw LEASE TO a_expr FOR select_stmt
  2500    {
  2501      $$.val = &tree.RelocateRange{
  2502        Rows: $8.slct(),
  2503        FromStoreID: tree.DNull,
  2504        ToStoreID: $6.expr(),
  2505        SubjectReplicas: tree.RelocateLease,
  2506      }
  2507    }
  2508  | ALTER RANGE a_expr relocate_kw LEASE TO a_expr
  2509      {
  2510        $$.val = &tree.RelocateRange{
  2511          Rows: &tree.Select{
  2512            Select: &tree.ValuesClause{Rows: []tree.Exprs{tree.Exprs{$3.expr()}}},
  2513          },
  2514          FromStoreID: tree.DNull,
  2515          ToStoreID: $7.expr(),
  2516          SubjectReplicas: tree.RelocateLease,
  2517        }
  2518      }
  2519  | ALTER RANGE relocate_kw relocate_subject_nonlease FROM a_expr TO a_expr FOR select_stmt
  2520    {
  2521      $$.val = &tree.RelocateRange{
  2522        Rows: $10.slct(),
  2523        FromStoreID: $6.expr(),
  2524        ToStoreID: $8.expr(),
  2525        SubjectReplicas: $4.relocateSubject(),
  2526      }
  2527    }
  2528  | ALTER RANGE a_expr relocate_kw relocate_subject_nonlease FROM a_expr TO a_expr
  2529    {
  2530      $$.val = &tree.RelocateRange{
  2531        Rows: &tree.Select{
  2532          Select: &tree.ValuesClause{Rows: []tree.Exprs{tree.Exprs{$3.expr()}}},
  2533        },
  2534        FromStoreID: $7.expr(),
  2535        ToStoreID: $9.expr(),
  2536        SubjectReplicas: $5.relocateSubject(),
  2537      }
  2538    }
  2539  
  2540  set_zone_config:
  2541    CONFIGURE ZONE to_or_eq a_expr
  2542    {
  2543      /* SKIP DOC */
  2544      $$.val = &tree.SetZoneConfig{
  2545        ZoneConfigSettings: tree.ZoneConfigSettings {
  2546          YAMLConfig:    $4.expr(),
  2547        },
  2548      }
  2549    }
  2550  | CONFIGURE ZONE USING var_set_list
  2551    {
  2552      $$.val = &tree.SetZoneConfig{
  2553        ZoneConfigSettings: tree.ZoneConfigSettings {
  2554          Options: $4.kvOptions(),
  2555        },
  2556      }
  2557    }
  2558  | CONFIGURE ZONE USING DEFAULT
  2559    {
  2560      /* SKIP DOC */
  2561      $$.val = &tree.SetZoneConfig{
  2562        ZoneConfigSettings: tree.ZoneConfigSettings {
  2563          SetDefault: true,
  2564        },
  2565      }
  2566    }
  2567  | CONFIGURE ZONE DISCARD
  2568    {
  2569      $$.val = &tree.SetZoneConfig{
  2570        ZoneConfigSettings: tree.ZoneConfigSettings {
  2571          YAMLConfig: tree.DNull,
  2572        },
  2573      }
  2574    }
  2575  
  2576  alter_zone_database_stmt:
  2577    ALTER DATABASE database_name set_zone_config
  2578    {
  2579       s := $4.setZoneConfig()
  2580       s.ZoneSpecifier = tree.ZoneSpecifier{Database: tree.Name($3)}
  2581       $$.val = s
  2582    }
  2583  
  2584  alter_zone_table_stmt:
  2585    ALTER TABLE table_name set_zone_config
  2586    {
  2587      name := $3.unresolvedObjectName().ToTableName()
  2588      s := $4.setZoneConfig()
  2589      s.ZoneSpecifier = tree.ZoneSpecifier{
  2590         TableOrIndex: tree.TableIndexName{Table: name},
  2591      }
  2592      $$.val = s
  2593    }
  2594  
  2595  alter_zone_index_stmt:
  2596    ALTER INDEX table_index_name set_zone_config
  2597    {
  2598      s := $4.setZoneConfig()
  2599      s.ZoneSpecifier = tree.ZoneSpecifier{
  2600         TableOrIndex: $3.tableIndexName(),
  2601      }
  2602      $$.val = s
  2603    }
  2604  
  2605  alter_zone_partition_stmt:
  2606    ALTER PARTITION partition_name OF TABLE table_name set_zone_config
  2607    {
  2608      name := $6.unresolvedObjectName().ToTableName()
  2609      s := $7.setZoneConfig()
  2610      s.ZoneSpecifier = tree.ZoneSpecifier{
  2611         TableOrIndex: tree.TableIndexName{Table: name},
  2612         Partition: tree.Name($3),
  2613      }
  2614      $$.val = s
  2615    }
  2616  | ALTER PARTITION partition_name OF INDEX table_index_name set_zone_config
  2617    {
  2618      s := $7.setZoneConfig()
  2619      s.ZoneSpecifier = tree.ZoneSpecifier{
  2620         TableOrIndex: $6.tableIndexName(),
  2621         Partition: tree.Name($3),
  2622      }
  2623      $$.val = s
  2624    }
  2625  | ALTER PARTITION partition_name OF INDEX table_name '@' '*' set_zone_config
  2626    {
  2627      name := $6.unresolvedObjectName().ToTableName()
  2628      s := $9.setZoneConfig()
  2629      s.ZoneSpecifier = tree.ZoneSpecifier{
  2630         TableOrIndex: tree.TableIndexName{Table: name},
  2631         Partition: tree.Name($3),
  2632      }
  2633      s.AllIndexes = true
  2634      $$.val = s
  2635    }
  2636  | ALTER PARTITION partition_name OF TABLE table_name '@' error
  2637    {
  2638      err := errors.New("index name should not be specified in ALTER PARTITION ... OF TABLE")
  2639      err = errors.WithHint(err, "try ALTER PARTITION ... OF INDEX")
  2640      return setErr(sqllex, err)
  2641    }
  2642  | ALTER PARTITION partition_name OF TABLE table_name '@' '*' error
  2643    {
  2644      err := errors.New("index wildcard unsupported in ALTER PARTITION ... OF TABLE")
  2645      err = errors.WithHint(err, "try ALTER PARTITION <partition> OF INDEX <tablename>@*")
  2646      return setErr(sqllex, err)
  2647    }
  2648  
  2649  var_set_list:
  2650    var_name '=' COPY FROM PARENT
  2651    {
  2652      $$.val = []tree.KVOption{tree.KVOption{Key: tree.Name(strings.Join($1.strs(), "."))}}
  2653    }
  2654  | var_name '=' var_value
  2655    {
  2656      $$.val = []tree.KVOption{tree.KVOption{Key: tree.Name(strings.Join($1.strs(), ".")), Value: $3.expr()}}
  2657    }
  2658  | var_set_list ',' var_name '=' var_value
  2659    {
  2660      $$.val = append($1.kvOptions(), tree.KVOption{Key: tree.Name(strings.Join($3.strs(), ".")), Value: $5.expr()})
  2661    }
  2662  | var_set_list ',' var_name '=' COPY FROM PARENT
  2663    {
  2664      $$.val = append($1.kvOptions(), tree.KVOption{Key: tree.Name(strings.Join($3.strs(), "."))})
  2665    }
  2666  
  2667  alter_scatter_stmt:
  2668    ALTER TABLE table_name SCATTER
  2669    {
  2670      name := $3.unresolvedObjectName().ToTableName()
  2671      $$.val = &tree.Scatter{TableOrIndex: tree.TableIndexName{Table: name}}
  2672    }
  2673  | ALTER TABLE table_name SCATTER FROM '(' expr_list ')' TO '(' expr_list ')'
  2674    {
  2675      name := $3.unresolvedObjectName().ToTableName()
  2676      $$.val = &tree.Scatter{
  2677        TableOrIndex: tree.TableIndexName{Table: name},
  2678        From: $7.exprs(),
  2679        To: $11.exprs(),
  2680      }
  2681    }
  2682  
  2683  alter_scatter_index_stmt:
  2684    ALTER INDEX table_index_name SCATTER
  2685    {
  2686      $$.val = &tree.Scatter{TableOrIndex: $3.tableIndexName()}
  2687    }
  2688  | ALTER INDEX table_index_name SCATTER FROM '(' expr_list ')' TO '(' expr_list ')'
  2689    {
  2690      $$.val = &tree.Scatter{TableOrIndex: $3.tableIndexName(), From: $7.exprs(), To: $11.exprs()}
  2691    }
  2692  
  2693  alter_table_cmds:
  2694    alter_table_cmd
  2695    {
  2696      $$.val = tree.AlterTableCmds{$1.alterTableCmd()}
  2697    }
  2698  | alter_table_cmds ',' alter_table_cmd
  2699    {
  2700      $$.val = append($1.alterTableCmds(), $3.alterTableCmd())
  2701    }
  2702  
  2703  alter_table_cmd:
  2704    // ALTER TABLE <name> RENAME [COLUMN] <name> TO <newname>
  2705    RENAME opt_column column_name TO column_name
  2706    {
  2707      $$.val = &tree.AlterTableRenameColumn{Column: tree.Name($3), NewName: tree.Name($5) }
  2708    }
  2709    // ALTER TABLE <name> RENAME CONSTRAINT <name> TO <newname>
  2710  | RENAME CONSTRAINT column_name TO column_name
  2711    {
  2712      $$.val = &tree.AlterTableRenameConstraint{Constraint: tree.Name($3), NewName: tree.Name($5) }
  2713    }
  2714    // ALTER TABLE <name> ADD <coldef>
  2715  | ADD column_table_def
  2716    {
  2717      $$.val = &tree.AlterTableAddColumn{IfNotExists: false, ColumnDef: $2.colTableDef()}
  2718    }
  2719    // ALTER TABLE <name> ADD IF NOT EXISTS <coldef>
  2720  | ADD IF NOT EXISTS column_table_def
  2721    {
  2722      $$.val = &tree.AlterTableAddColumn{IfNotExists: true, ColumnDef: $5.colTableDef()}
  2723    }
  2724    // ALTER TABLE <name> ADD COLUMN <coldef>
  2725  | ADD COLUMN column_table_def
  2726    {
  2727      $$.val = &tree.AlterTableAddColumn{IfNotExists: false, ColumnDef: $3.colTableDef()}
  2728    }
  2729    // ALTER TABLE <name> ADD COLUMN IF NOT EXISTS <coldef>
  2730  | ADD COLUMN IF NOT EXISTS column_table_def
  2731    {
  2732      $$.val = &tree.AlterTableAddColumn{IfNotExists: true, ColumnDef: $6.colTableDef()}
  2733    }
  2734    // ALTER TABLE <name> ALTER [COLUMN] <colname> {SET DEFAULT <expr>|DROP DEFAULT}
  2735  | ALTER opt_column column_name alter_column_default
  2736    {
  2737      $$.val = &tree.AlterTableSetDefault{Column: tree.Name($3), Default: $4.expr()}
  2738    }
  2739    // ALTER TABLE <name> ALTER [COLUMN] <colname> {SET ON UPDATE <expr>|DROP ON UPDATE}
  2740  | ALTER opt_column column_name alter_column_on_update
  2741    {
  2742      $$.val = &tree.AlterTableSetOnUpdate{Column: tree.Name($3), Expr: $4.expr()}
  2743    }
  2744    // ALTER TABLE <name> ALTER [COLUMN] <colname> SET {VISIBLE|NOT VISIBLE}
  2745  | ALTER opt_column column_name alter_column_visible
  2746    {
  2747      $$.val = &tree.AlterTableSetVisible{Column: tree.Name($3), Visible: $4.bool()}
  2748    }
  2749    // ALTER TABLE <name> ALTER [COLUMN] <colname> DROP NOT NULL
  2750  | ALTER opt_column column_name DROP NOT NULL
  2751    {
  2752      $$.val = &tree.AlterTableDropNotNull{Column: tree.Name($3)}
  2753    }
  2754    // ALTER TABLE <name> ALTER [COLUMN] <colname> DROP STORED
  2755  | ALTER opt_column column_name DROP STORED
  2756    {
  2757      $$.val = &tree.AlterTableDropStored{Column: tree.Name($3)}
  2758    }
  2759    // ALTER TABLE <name> ALTER [COLUMN] <colname> SET NOT NULL
  2760  | ALTER opt_column column_name SET NOT NULL
  2761    {
  2762      $$.val = &tree.AlterTableSetNotNull{Column: tree.Name($3)}
  2763    }
  2764  | ALTER opt_column column_name ADD error
  2765    {
  2766      return unimplemented(sqllex, "alter table alter column add")
  2767    }
  2768    // ALTER TABLE <name> DROP [COLUMN] IF EXISTS <colname> [RESTRICT|CASCADE]
  2769  | DROP opt_column IF EXISTS column_name opt_drop_behavior
  2770    {
  2771      $$.val = &tree.AlterTableDropColumn{
  2772        IfExists: true,
  2773        Column: tree.Name($5),
  2774        DropBehavior: $6.dropBehavior(),
  2775      }
  2776    }
  2777    // ALTER TABLE <name> DROP [COLUMN] <colname> [RESTRICT|CASCADE]
  2778  | DROP opt_column column_name opt_drop_behavior
  2779    {
  2780      $$.val = &tree.AlterTableDropColumn{
  2781        IfExists: false,
  2782        Column: tree.Name($3),
  2783        DropBehavior: $4.dropBehavior(),
  2784      }
  2785    }
  2786    // ALTER TABLE <name> ALTER [COLUMN] <colname>
  2787    //     [SET DATA] TYPE <typename>
  2788    //     [ COLLATE collation ]
  2789    //     [ USING <expression> ]
  2790  | ALTER opt_column column_name opt_set_data TYPE typename opt_collate opt_alter_column_using
  2791    {
  2792      $$.val = &tree.AlterTableAlterColumnType{
  2793        Column: tree.Name($3),
  2794        ToType: $6.typeReference(),
  2795        Collation: $7,
  2796        Using: $8.expr(),
  2797      }
  2798    }
  2799    // ALTER TABLE <name> ADD CONSTRAINT ...
  2800  | ADD table_constraint opt_validate_behavior
  2801    {
  2802      $$.val = &tree.AlterTableAddConstraint{
  2803        ConstraintDef: $2.constraintDef(),
  2804        ValidationBehavior: $3.validationBehavior(),
  2805      }
  2806    }
  2807    // ALTER TABLE <name> ADD CONSTRAINT IF NOT EXISTS ...
  2808  | ADD CONSTRAINT IF NOT EXISTS constraint_name constraint_elem opt_validate_behavior
  2809    {
  2810      def := $7.constraintDef()
  2811      def.SetName(tree.Name($6))
  2812      def.SetIfNotExists()
  2813      $$.val = &tree.AlterTableAddConstraint{
  2814        ConstraintDef: def,
  2815        ValidationBehavior: $8.validationBehavior(),
  2816      }
  2817    }
  2818    // ALTER TABLE <name> ALTER CONSTRAINT ...
  2819  | ALTER CONSTRAINT constraint_name error { return unimplementedWithIssueDetail(sqllex, 31632, "alter constraint") }
  2820    // ALTER TABLE <name> INHERITS ....
  2821  | INHERITS error
  2822    {
  2823      /* SKIP DOC */
  2824      return unimplementedWithIssueDetail(sqllex, 22456, "alter table inherits")
  2825    }
  2826    // ALTER TABLE <name> NO INHERITS ....
  2827  | NO INHERITS error
  2828    {
  2829      /* SKIP DOC */
  2830      return unimplementedWithIssueDetail(sqllex, 22456, "alter table no inherits")
  2831    }
  2832    // ALTER TABLE <name> ALTER PRIMARY KEY USING COLUMNS ( <colnames...> )
  2833  | ALTER PRIMARY KEY USING COLUMNS '(' index_params ')' opt_hash_sharded opt_with_storage_parameter_list
  2834    {
  2835      $$.val = &tree.AlterTableAlterPrimaryKey{
  2836        Columns: $7.idxElems(),
  2837        Sharded: $9.shardedIndexDef(),
  2838        StorageParams: $10.storageParams(),
  2839      }
  2840    }
  2841    // ALTER TABLE <name> VALIDATE CONSTRAINT ...
  2842  | VALIDATE CONSTRAINT constraint_name
  2843    {
  2844      $$.val = &tree.AlterTableValidateConstraint{
  2845        Constraint: tree.Name($3),
  2846      }
  2847    }
  2848    // ALTER TABLE <name> DROP CONSTRAINT IF EXISTS <name> [RESTRICT|CASCADE]
  2849  | DROP CONSTRAINT IF EXISTS constraint_name opt_drop_behavior
  2850    {
  2851      $$.val = &tree.AlterTableDropConstraint{
  2852        IfExists: true,
  2853        Constraint: tree.Name($5),
  2854        DropBehavior: $6.dropBehavior(),
  2855      }
  2856    }
  2857    // ALTER TABLE <name> DROP CONSTRAINT <name> [RESTRICT|CASCADE]
  2858  | DROP CONSTRAINT constraint_name opt_drop_behavior
  2859    {
  2860      $$.val = &tree.AlterTableDropConstraint{
  2861        IfExists: false,
  2862        Constraint: tree.Name($3),
  2863        DropBehavior: $4.dropBehavior(),
  2864      }
  2865    }
  2866    // ALTER TABLE <name> EXPERIMENTAL_AUDIT SET <mode>
  2867  | EXPERIMENTAL_AUDIT SET audit_mode
  2868    {
  2869      $$.val = &tree.AlterTableSetAudit{Mode: $3.auditMode()}
  2870    }
  2871    // ALTER TABLE <name> PARTITION BY ...
  2872  | partition_by_table
  2873    {
  2874      $$.val = &tree.AlterTablePartitionByTable{
  2875        PartitionByTable: $1.partitionByTable(),
  2876      }
  2877    }
  2878    // ALTER TABLE <name> INJECT STATISTICS <json>
  2879  | INJECT STATISTICS a_expr
  2880    {
  2881      /* SKIP DOC */
  2882      $$.val = &tree.AlterTableInjectStats{
  2883        Stats: $3.expr(),
  2884      }
  2885    }
  2886  | SET '(' storage_parameter_list ')'
  2887    {
  2888      $$.val = &tree.AlterTableSetStorageParams{
  2889        StorageParams: $3.storageParams(),
  2890      }
  2891    }
  2892  | RESET '(' storage_parameter_key_list ')'
  2893    {
  2894      $$.val = &tree.AlterTableResetStorageParams{
  2895        Params: $3.storageParamKeys(),
  2896      }
  2897    }
  2898  
  2899  audit_mode:
  2900    READ WRITE { $$.val = tree.AuditModeReadWrite }
  2901  | OFF        { $$.val = tree.AuditModeDisable }
  2902  
  2903  alter_index_cmds:
  2904    alter_index_cmd
  2905    {
  2906      $$.val = tree.AlterIndexCmds{$1.alterIndexCmd()}
  2907    }
  2908  | alter_index_cmds ',' alter_index_cmd
  2909    {
  2910      $$.val = append($1.alterIndexCmds(), $3.alterIndexCmd())
  2911    }
  2912  
  2913  alter_index_cmd:
  2914    partition_by_index
  2915    {
  2916      $$.val = &tree.AlterIndexPartitionBy{
  2917        PartitionByIndex: $1.partitionByIndex(),
  2918      }
  2919    }
  2920  
  2921  alter_column_default:
  2922    SET DEFAULT a_expr
  2923    {
  2924      $$.val = $3.expr()
  2925    }
  2926  | DROP DEFAULT
  2927    {
  2928      $$.val = nil
  2929    }
  2930  
  2931  alter_column_on_update:
  2932    SET ON UPDATE b_expr
  2933    {
  2934      $$.val = $4.expr()
  2935    }
  2936  | DROP ON UPDATE
  2937    {
  2938      $$.val = nil
  2939    }
  2940  
  2941  alter_column_visible:
  2942    SET VISIBLE
  2943    {
  2944      $$.val = true
  2945    }
  2946  | SET NOT VISIBLE
  2947    {
  2948      $$.val = false
  2949    }
  2950  
  2951  opt_alter_column_using:
  2952    USING a_expr
  2953    {
  2954       $$.val = $2.expr()
  2955    }
  2956  | /* EMPTY */
  2957    {
  2958       $$.val = nil
  2959    }
  2960  
  2961  
  2962  opt_drop_behavior:
  2963    CASCADE
  2964    {
  2965      $$.val = tree.DropCascade
  2966    }
  2967  | RESTRICT
  2968    {
  2969      $$.val = tree.DropRestrict
  2970    }
  2971  | /* EMPTY */
  2972    {
  2973      $$.val = tree.DropDefault
  2974    }
  2975  
  2976  opt_validate_behavior:
  2977    NOT VALID
  2978    {
  2979      $$.val = tree.ValidationSkip
  2980    }
  2981  | /* EMPTY */
  2982    {
  2983      $$.val = tree.ValidationDefault
  2984    }
  2985  
  2986  // %Help: ALTER TYPE - change the definition of a type.
  2987  // %Category: DDL
  2988  // %Text: ALTER TYPE <typename> <command>
  2989  //
  2990  // Commands:
  2991  //   ALTER TYPE ... ADD VALUE [IF NOT EXISTS] <value> [ { BEFORE | AFTER } <value> ]
  2992  //   ALTER TYPE ... RENAME VALUE <oldname> TO <newname>
  2993  //   ALTER TYPE ... RENAME TO <newname>
  2994  //   ALTER TYPE ... SET SCHEMA <newschemaname>
  2995  //   ALTER TYPE ... OWNER TO {<newowner> | CURRENT_USER | SESSION_USER }
  2996  //   ALTER TYPE ... RENAME ATTRIBUTE <oldname> TO <newname> [ CASCADE | RESTRICT ]
  2997  //   ALTER TYPE ... <attributeaction> [, ... ]
  2998  //
  2999  // Attribute action:
  3000  //   ADD ATTRIBUTE <name> <type> [ COLLATE <collation> ] [ CASCADE | RESTRICT ]
  3001  //   DROP ATTRIBUTE [IF EXISTS] <name> [ CASCADE | RESTRICT ]
  3002  //   ALTER ATTRIBUTE <name> [ SET DATA ] TYPE <type> [ COLLATE <collation> ] [ CASCADE | RESTRICT ]
  3003  //
  3004  // %SeeAlso: WEBDOCS/alter-type.html
  3005  alter_type_stmt:
  3006    ALTER TYPE type_name ADD VALUE SCONST opt_add_val_placement
  3007    {
  3008      $$.val = &tree.AlterType{
  3009        Type: $3.unresolvedObjectName(),
  3010        Cmd: &tree.AlterTypeAddValue{
  3011          NewVal: tree.EnumValue($6),
  3012          IfNotExists: false,
  3013          Placement: $7.alterTypeAddValuePlacement(),
  3014        },
  3015      }
  3016    }
  3017  | ALTER TYPE type_name ADD VALUE IF NOT EXISTS SCONST opt_add_val_placement
  3018    {
  3019      $$.val = &tree.AlterType{
  3020        Type: $3.unresolvedObjectName(),
  3021        Cmd: &tree.AlterTypeAddValue{
  3022          NewVal: tree.EnumValue($9),
  3023          IfNotExists: true,
  3024          Placement: $10.alterTypeAddValuePlacement(),
  3025        },
  3026      }
  3027    }
  3028  | ALTER TYPE type_name DROP VALUE SCONST
  3029   {
  3030     $$.val = &tree.AlterType{
  3031       Type: $3.unresolvedObjectName(),
  3032       Cmd: &tree.AlterTypeDropValue{
  3033         Val: tree.EnumValue($6),
  3034       },
  3035     }
  3036   }
  3037  | ALTER TYPE type_name RENAME VALUE SCONST TO SCONST
  3038    {
  3039      $$.val = &tree.AlterType{
  3040        Type: $3.unresolvedObjectName(),
  3041        Cmd: &tree.AlterTypeRenameValue{
  3042          OldVal: tree.EnumValue($6),
  3043          NewVal: tree.EnumValue($8),
  3044        },
  3045      }
  3046    }
  3047  | ALTER TYPE type_name RENAME TO name
  3048    {
  3049      $$.val = &tree.AlterType{
  3050        Type: $3.unresolvedObjectName(),
  3051        Cmd: &tree.AlterTypeRename{
  3052          NewName: tree.Name($6),
  3053        },
  3054      }
  3055    }
  3056  | ALTER TYPE type_name SET SCHEMA schema_name
  3057    {
  3058      $$.val = &tree.AlterType{
  3059        Type: $3.unresolvedObjectName(),
  3060        Cmd: &tree.AlterTypeSetSchema{
  3061          Schema: tree.Name($6),
  3062        },
  3063      }
  3064    }
  3065  | ALTER TYPE type_name OWNER TO role_spec
  3066    {
  3067      $$.val = &tree.AlterType{
  3068        Type: $3.unresolvedObjectName(),
  3069        Cmd: &tree.AlterTypeOwner{
  3070          Owner: $6.roleSpec(),
  3071        },
  3072      }
  3073    }
  3074  | ALTER TYPE type_name RENAME ATTRIBUTE column_name TO column_name opt_drop_behavior
  3075    {
  3076      return unimplementedWithIssueDetail(sqllex, 48701, "ALTER TYPE ATTRIBUTE")
  3077    }
  3078  | ALTER TYPE type_name alter_attribute_action_list
  3079    {
  3080      return unimplementedWithIssueDetail(sqllex, 48701, "ALTER TYPE ATTRIBUTE")
  3081    }
  3082  | ALTER TYPE error // SHOW HELP: ALTER TYPE
  3083  
  3084  opt_add_val_placement:
  3085    BEFORE SCONST
  3086    {
  3087      $$.val = &tree.AlterTypeAddValuePlacement{
  3088         Before: true,
  3089         ExistingVal: tree.EnumValue($2),
  3090      }
  3091    }
  3092  | AFTER SCONST
  3093    {
  3094      $$.val = &tree.AlterTypeAddValuePlacement{
  3095         Before: false,
  3096         ExistingVal: tree.EnumValue($2),
  3097      }
  3098    }
  3099  | /* EMPTY */
  3100    {
  3101      $$.val = (*tree.AlterTypeAddValuePlacement)(nil)
  3102    }
  3103  
  3104  role_spec:
  3105    IDENT
  3106    {
  3107      $$.val = tree.RoleSpec{
  3108        RoleSpecType: tree.RoleName,
  3109        Name: $1,
  3110      }
  3111    }
  3112  | unreserved_keyword
  3113    {
  3114      $$.val = tree.RoleSpec{
  3115        RoleSpecType: tree.RoleName,
  3116        Name: $1,
  3117      }
  3118    }
  3119  | CURRENT_USER
  3120    {
  3121      $$.val = tree.RoleSpec{
  3122        RoleSpecType: tree.CurrentUser,
  3123      }
  3124    }
  3125  | SESSION_USER
  3126    {
  3127      $$.val = tree.RoleSpec{
  3128        RoleSpecType: tree.SessionUser,
  3129       }
  3130    }
  3131  
  3132  role_spec_list:
  3133    role_spec
  3134    {
  3135      $$.val = tree.RoleSpecList{$1.roleSpec()}
  3136    }
  3137  | role_spec_list ',' role_spec
  3138    {
  3139      $$.val = append($1.roleSpecList(), $3.roleSpec())
  3140    }
  3141  
  3142  alter_attribute_action_list:
  3143    alter_attribute_action
  3144  | alter_attribute_action_list ',' alter_attribute_action
  3145  
  3146  alter_attribute_action:
  3147    ADD ATTRIBUTE column_name type_name opt_collate opt_drop_behavior
  3148  | DROP ATTRIBUTE column_name opt_drop_behavior
  3149  | DROP ATTRIBUTE IF EXISTS column_name opt_drop_behavior
  3150  | ALTER ATTRIBUTE column_name TYPE type_name opt_collate opt_drop_behavior
  3151  | ALTER ATTRIBUTE column_name SET DATA TYPE type_name opt_collate opt_drop_behavior
  3152  
  3153  // %Help: REFRESH - recalculate a materialized view
  3154  // %Category: Misc
  3155  // %Text:
  3156  // REFRESH MATERIALIZED VIEW [CONCURRENTLY] view_name [WITH [NO] DATA]
  3157  refresh_stmt:
  3158    REFRESH MATERIALIZED VIEW opt_concurrently view_name opt_clear_data
  3159    {
  3160      $$.val = &tree.RefreshMaterializedView{
  3161        Name: $5.unresolvedObjectName(),
  3162        Concurrently: $4.bool(),
  3163        RefreshDataOption: $6.refreshDataOption(),
  3164      }
  3165    }
  3166  | REFRESH error // SHOW HELP: REFRESH
  3167  
  3168  opt_clear_data:
  3169    WITH DATA
  3170    {
  3171      $$.val = tree.RefreshDataWithData
  3172    }
  3173  | WITH NO DATA
  3174    {
  3175      $$.val = tree.RefreshDataClear
  3176    }
  3177  | /* EMPTY */
  3178    {
  3179      $$.val = tree.RefreshDataDefault
  3180    }
  3181  
  3182  // %Help: BACKUP - back up data to external storage
  3183  // %Category: CCL
  3184  // %Text:
  3185  //
  3186  // Create a full backup
  3187  // BACKUP <targets...> INTO <destination...>
  3188  //        [ AS OF SYSTEM TIME <expr> ]
  3189  //				[ WITH <option> [= <value>] [, ...] ]
  3190  //
  3191  // Append an incremental backup to the most recent backup added to a collection
  3192  // BACKUP <targets...> INTO LATEST IN <destination...>
  3193  //        [ AS OF SYSTEM TIME <expr> ]
  3194  //				[ WITH <option> [= <value>] [, ...] ]
  3195  //
  3196  //
  3197  // Append an incremental backup in the <subdir>. This command will create an
  3198  // incremental backup iff there is a full backup in <destination>
  3199  // BACKUP <targets...> INTO [<subdir...> IN] <destination>
  3200  //        [ AS OF SYSTEM TIME <expr> ]
  3201  //				[ WITH <option> [= <value>] [, ...] ]
  3202  //
  3203  // Targets:
  3204  //    Empty targets list: backup full cluster.
  3205  //    TABLE <pattern> [, ...]
  3206  //    DATABASE <databasename> [, ...]
  3207  //
  3208  // Destination:
  3209  //    "[scheme]://[host]/[path to backup]?[parameters]"
  3210  //
  3211  // Options:
  3212  //    revision_history: enable revision history
  3213  //    encryption_passphrase="secret": encrypt backups
  3214  //    kms="[kms_provider]://[kms_host]/[master_key_identifier]?[parameters]" : encrypt backups using KMS
  3215  //    detached: execute backup job asynchronously, without waiting for its completion
  3216  //    incremental_location: specify a different path to store the incremental backup
  3217  //    include_all_virtual_clusters: enable backups of all virtual clusters during a cluster backup
  3218  //
  3219  // %SeeAlso: RESTORE, WEBDOCS/backup.html
  3220  backup_stmt:
  3221    BACKUP opt_backup_targets INTO sconst_or_placeholder IN string_or_placeholder_opt_list opt_as_of_clause opt_with_backup_options
  3222    {
  3223      $$.val = &tree.Backup{
  3224        Targets: $2.backupTargetListPtr(),
  3225        To: $6.stringOrPlaceholderOptList(),
  3226        Nested: true,
  3227        AppendToLatest: false,
  3228        Subdir: $4.expr(),
  3229        AsOf: $7.asOfClause(),
  3230        Options: *$8.backupOptions(),
  3231      }
  3232    }
  3233  | BACKUP opt_backup_targets INTO string_or_placeholder_opt_list opt_as_of_clause opt_with_backup_options
  3234    {
  3235      $$.val = &tree.Backup{
  3236        Targets: $2.backupTargetListPtr(),
  3237        To: $4.stringOrPlaceholderOptList(),
  3238        Nested: true,
  3239        AsOf: $5.asOfClause(),
  3240        Options: *$6.backupOptions(),
  3241      }
  3242    }
  3243  | BACKUP opt_backup_targets INTO LATEST IN string_or_placeholder_opt_list opt_as_of_clause opt_with_backup_options
  3244    {
  3245      $$.val = &tree.Backup{
  3246        Targets: $2.backupTargetListPtr(),
  3247        To: $6.stringOrPlaceholderOptList(),
  3248        Nested: true,
  3249        AppendToLatest: true,
  3250        AsOf: $7.asOfClause(),
  3251        Options: *$8.backupOptions(),
  3252      }
  3253    }
  3254  | BACKUP opt_backup_targets TO string_or_placeholder_opt_list opt_as_of_clause opt_incremental opt_with_backup_options
  3255    {
  3256      $$.val = &tree.Backup{
  3257        Targets: $2.backupTargetListPtr(),
  3258        To: $4.stringOrPlaceholderOptList(),
  3259        IncrementalFrom: $6.exprs(),
  3260        AsOf: $5.asOfClause(),
  3261        Options: *$7.backupOptions(),
  3262      }
  3263    }
  3264  | BACKUP error // SHOW HELP: BACKUP
  3265  
  3266  opt_backup_targets:
  3267    /* EMPTY -- full cluster */
  3268    {
  3269      $$.val = (*tree.BackupTargetList)(nil)
  3270    }
  3271  | backup_targets
  3272    {
  3273      t := $1.backupTargetList()
  3274      $$.val = &t
  3275    }
  3276  
  3277  // Optional backup options.
  3278  opt_with_backup_options:
  3279    WITH backup_options_list
  3280    {
  3281      $$.val = $2.backupOptions()
  3282    }
  3283  | WITH OPTIONS '(' backup_options_list ')'
  3284    {
  3285      $$.val = $4.backupOptions()
  3286    }
  3287  | /* EMPTY */
  3288    {
  3289      $$.val = &tree.BackupOptions{}
  3290    }
  3291  
  3292  backup_options_list:
  3293    // Require at least one option
  3294    backup_options
  3295    {
  3296      $$.val = $1.backupOptions()
  3297    }
  3298  | backup_options_list ',' backup_options
  3299    {
  3300      if err := $1.backupOptions().CombineWith($3.backupOptions()); err != nil {
  3301        return setErr(sqllex, err)
  3302      }
  3303    }
  3304  
  3305  // List of valid backup options.
  3306  backup_options:
  3307    ENCRYPTION_PASSPHRASE '=' string_or_placeholder
  3308    {
  3309      $$.val = &tree.BackupOptions{EncryptionPassphrase: $3.expr()}
  3310    }
  3311  | REVISION_HISTORY
  3312    {
  3313      $$.val = &tree.BackupOptions{CaptureRevisionHistory: tree.MakeDBool(true)}
  3314    }
  3315  | REVISION_HISTORY '=' a_expr
  3316    {
  3317      $$.val = &tree.BackupOptions{CaptureRevisionHistory: $3.expr()}
  3318    }
  3319  | DETACHED
  3320    {
  3321      $$.val = &tree.BackupOptions{Detached: tree.MakeDBool(true)}
  3322    }
  3323  | DETACHED '=' TRUE
  3324    {
  3325      $$.val = &tree.BackupOptions{Detached: tree.MakeDBool(true)}
  3326    }
  3327  | DETACHED '=' FALSE
  3328    {
  3329      $$.val = &tree.BackupOptions{Detached: tree.MakeDBool(false)}
  3330    }
  3331  | KMS '=' string_or_placeholder_opt_list
  3332    {
  3333      $$.val = &tree.BackupOptions{EncryptionKMSURI: $3.stringOrPlaceholderOptList()}
  3334    }
  3335  | INCREMENTAL_LOCATION '=' string_or_placeholder_opt_list
  3336    {
  3337      $$.val = &tree.BackupOptions{IncrementalStorage: $3.stringOrPlaceholderOptList()}
  3338    }
  3339  | EXECUTION LOCALITY '=' string_or_placeholder
  3340    {
  3341      $$.val = &tree.BackupOptions{ExecutionLocality: $4.expr()}
  3342    }
  3343  | include_all_clusters
  3344    {
  3345      /* SKIP DOC */
  3346      $$.val = &tree.BackupOptions{IncludeAllSecondaryTenants: tree.MakeDBool(true)}
  3347    }
  3348  | include_all_clusters '=' a_expr
  3349    {
  3350      $$.val = &tree.BackupOptions{IncludeAllSecondaryTenants: $3.expr()}
  3351    }
  3352  | UPDATES_CLUSTER_MONITORING_METRICS
  3353    {
  3354      $$.val = &tree.BackupOptions{UpdatesClusterMonitoringMetrics: tree.MakeDBool(true)}
  3355    }
  3356  | UPDATES_CLUSTER_MONITORING_METRICS '=' a_expr
  3357    {
  3358      $$.val = &tree.BackupOptions{UpdatesClusterMonitoringMetrics: $3.expr()}
  3359    }
  3360  
  3361  include_all_clusters:
  3362    INCLUDE_ALL_SECONDARY_TENANTS { /* SKIP DOC */ }
  3363  | INCLUDE_ALL_VIRTUAL_CLUSTERS { }
  3364  
  3365  // %Help: CREATE SCHEDULE FOR BACKUP - backup data periodically
  3366  // %Category: CCL
  3367  // %Text:
  3368  // CREATE SCHEDULE [IF NOT EXISTS]
  3369  // [<description>]
  3370  // FOR BACKUP [<targets>] INTO <location...>
  3371  // [WITH <backup_option>[=<value>] [, ...]]
  3372  // RECURRING [crontab|NEVER] [FULL BACKUP <crontab|ALWAYS>]
  3373  // [WITH EXPERIMENTAL SCHEDULE OPTIONS <schedule_option>[= <value>] [, ...] ]
  3374  //
  3375  // All backups run in UTC timezone.
  3376  //
  3377  // Description:
  3378  //   Optional description (or name) for this schedule
  3379  //
  3380  // Targets:
  3381  //   empty targets: Backup entire cluster
  3382  //   DATABASE <pattern> [, ...]: comma separated list of databases to backup.
  3383  //   TABLE <pattern> [, ...]: comma separated list of tables to backup.
  3384  //
  3385  // Location:
  3386  //   "[scheme]://[host]/[path prefix to backup]?[parameters]"
  3387  //   Backup schedule will create subdirectories under this location to store
  3388  //   full and periodic backups.
  3389  //
  3390  // WITH <options>:
  3391  //   Options specific to BACKUP: See BACKUP options
  3392  //
  3393  // RECURRING <crontab>:
  3394  //   The RECURRING expression specifies when we backup.  By default these are incremental
  3395  //   backups that capture changes since the last backup, writing to the "current" backup.
  3396  //
  3397  //   Schedule specified as a string in crontab format.
  3398  //   All times in UTC.
  3399  //     "5 0 * * *": run schedule 5 minutes past midnight.
  3400  //     "@daily": run daily, at midnight
  3401  //   See https://en.wikipedia.org/wiki/Cron
  3402  //
  3403  // FULL BACKUP <crontab|ALWAYS>:
  3404  //   The optional FULL BACKUP '<cron expr>' clause specifies when we'll start a new full backup,
  3405  //   which becomes the "current" backup when complete.
  3406  //   If FULL BACKUP ALWAYS is specified, then the backups triggered by the RECURRING clause will
  3407  //   always be full backups. For free users, this is the only accepted value of FULL BACKUP.
  3408  //
  3409  //   If the FULL BACKUP clause is omitted, we will select a reasonable default:
  3410  //      * RECURRING <= 1 hour: we default to FULL BACKUP '@daily';
  3411  //      * RECURRING <= 1 day:  we default to FULL BACKUP '@weekly';
  3412  //      * Otherwise: we default to FULL BACKUP ALWAYS.
  3413  //
  3414  //  SCHEDULE OPTIONS:
  3415  //   The schedule can be modified by specifying the following options (which are considered
  3416  //   to be experimental at this time):
  3417  //   * first_run=TIMESTAMPTZ:
  3418  //     execute the schedule at the specified time. If not specified, the default is to execute
  3419  //     the scheduled based on it's next RECURRING time.
  3420  //   * on_execution_failure='[retry|reschedule|pause]':
  3421  //     If an error occurs during the execution, handle the error based as:
  3422  //     * retry: retry execution right away
  3423  //     * reschedule: retry execution by rescheduling it based on its RECURRING expression.
  3424  //       This is the default.
  3425  //     * pause: pause this schedule.  Requires manual intervention to unpause.
  3426  //   * on_previous_running='[start|skip|wait]':
  3427  //     If the previous backup started by this schedule still running, handle this as:
  3428  //     * start: start this execution anyway, even if the previous one still running.
  3429  //     * skip: skip this execution, reschedule it based on RECURRING (or change_capture_period)
  3430  //       expression.
  3431  //     * wait: wait for the previous execution to complete.  This is the default.
  3432  //   * ignore_existing_backups
  3433  //     If backups were already created in the destination in which a new schedule references,
  3434  //     this flag must be passed in to acknowledge that the new schedule may be backing up different
  3435  //     objects.
  3436  //
  3437  // %SeeAlso: BACKUP
  3438  create_schedule_for_backup_stmt:
  3439   CREATE SCHEDULE /*$3=*/schedule_label_spec FOR BACKUP /*$6=*/opt_backup_targets INTO
  3440    /*$8=*/string_or_placeholder_opt_list /*$9=*/opt_with_backup_options
  3441    /*$10=*/cron_expr /*$11=*/opt_full_backup_clause /*$12=*/opt_with_schedule_options
  3442    {
  3443    $$.val = &tree.ScheduledBackup{
  3444          ScheduleLabelSpec:    *($3.scheduleLabelSpec()),
  3445          Recurrence:           $10.expr(),
  3446          FullBackup:           $11.fullBackupClause(),
  3447          To:                   $8.stringOrPlaceholderOptList(),
  3448          Targets:              $6.backupTargetListPtr(),
  3449          BackupOptions:        *($9.backupOptions()),
  3450          ScheduleOptions:      $12.kvOptions(),
  3451        }
  3452    }
  3453   | CREATE SCHEDULE schedule_label_spec FOR BACKUP error // SHOW HELP: CREATE SCHEDULE FOR BACKUP
  3454  
  3455  // %Help: ALTER BACKUP SCHEDULE - alter an existing backup schedule
  3456  // %Category: CCL
  3457  // %Text:
  3458  // ALTER BACKUP SCHEDULE <id> <command> [, ...]
  3459  //
  3460  // Commands:
  3461  //   ALTER BACKUP SCHEDULE ... SET LABEL <label>
  3462  //   ALTER BACKUP SCHEDULE ... SET INTO <destination>
  3463  //   ALTER BACKUP SCHEDULE ... SET WITH <option>
  3464  //   ALTER BACKUP SCHEDULE ... SET RECURRING <crontab>
  3465  //   ALTER BACKUP SCHEDULE ... SET FULL BACKUP <crontab|ALWAYS>
  3466  //   ALTER BACKUP SCHEDULE ... SET SCHEDULE OPTION <option>
  3467  //
  3468  // See CREATE SCHEDULE FOR BACKUP for detailed option descriptions.
  3469  // %SeeAlso: CREATE SCHEDULE FOR BACKUP
  3470  alter_backup_schedule:
  3471    ALTER BACKUP SCHEDULE iconst64 alter_backup_schedule_cmds
  3472    {
  3473      $$.val = &tree.AlterBackupSchedule{
  3474  			ScheduleID: uint64($4.int64()),
  3475  			Cmds:       $5.alterBackupScheduleCmds(),
  3476      }
  3477    }
  3478    | ALTER BACKUP SCHEDULE error  // SHOW HELP: ALTER BACKUP SCHEDULE
  3479  
  3480  
  3481  alter_backup_schedule_cmds:
  3482    alter_backup_schedule_cmd
  3483    {
  3484      $$.val = tree.AlterBackupScheduleCmds{$1.alterBackupScheduleCmd()}
  3485    }
  3486  | alter_backup_schedule_cmds ',' alter_backup_schedule_cmd
  3487    {
  3488      $$.val = append($1.alterBackupScheduleCmds(), $3.alterBackupScheduleCmd())
  3489    }
  3490  
  3491  
  3492  alter_backup_schedule_cmd:
  3493    SET LABEL string_or_placeholder
  3494  	{
  3495  		$$.val = &tree.AlterBackupScheduleSetLabel{
  3496  		  Label: $3.expr(),
  3497  		}
  3498  	}
  3499  |	SET INTO string_or_placeholder_opt_list
  3500    {
  3501  		$$.val = &tree.AlterBackupScheduleSetInto{
  3502  		  Into: $3.stringOrPlaceholderOptList(),
  3503  		}
  3504    }
  3505  | SET WITH backup_options
  3506  	{
  3507  		$$.val = &tree.AlterBackupScheduleSetWith{
  3508  		  With: $3.backupOptions(),
  3509  		}
  3510  	}
  3511  | SET cron_expr
  3512    {
  3513  		$$.val = &tree.AlterBackupScheduleSetRecurring{
  3514  		  Recurrence: $2.expr(),
  3515  		}
  3516    }
  3517  | SET FULL BACKUP ALWAYS
  3518    {
  3519  		$$.val = &tree.AlterBackupScheduleSetFullBackup{
  3520  		  FullBackup: tree.FullBackupClause{AlwaysFull: true},
  3521  		}
  3522    }
  3523  | SET FULL BACKUP sconst_or_placeholder
  3524    {
  3525      $$.val = &tree.AlterBackupScheduleSetFullBackup{
  3526  		  FullBackup: tree.FullBackupClause{Recurrence: $4.expr()},
  3527  		}
  3528    }
  3529  | SET SCHEDULE OPTION kv_option
  3530    {
  3531  		$$.val = &tree.AlterBackupScheduleSetScheduleOption{
  3532  		  Option:  $4.kvOption(),
  3533  		}
  3534    }
  3535  
  3536  // sconst_or_placeholder matches a simple string, or a placeholder.
  3537  sconst_or_placeholder:
  3538    SCONST
  3539    {
  3540      $$.val = tree.NewStrVal($1)
  3541    }
  3542  | PLACEHOLDER
  3543    {
  3544      p := $1.placeholder()
  3545      sqllex.(*lexer).UpdateNumPlaceholders(p)
  3546      $$.val = p
  3547    }
  3548  
  3549  cron_expr:
  3550    RECURRING sconst_or_placeholder
  3551    // Can't use string_or_placeholder here due to conflict on NEVER branch above
  3552    // (is NEVER a keyword or a variable?).
  3553    {
  3554      $$.val = $2.expr()
  3555    }
  3556  
  3557  label_spec:
  3558    string_or_placeholder
  3559    {
  3560        $$.val = &tree.LabelSpec{Label: $1.expr(), IfNotExists: false}
  3561    }
  3562  | IF NOT EXISTS string_or_placeholder
  3563    {
  3564        $$.val = &tree.LabelSpec{Label: $4.expr(), IfNotExists: true}
  3565    }
  3566  
  3567  schedule_label_spec:
  3568    label_spec
  3569    {
  3570        $$.val = $1.labelSpec()
  3571    }
  3572  | /* EMPTY */
  3573    {
  3574        $$.val = &tree.LabelSpec{IfNotExists: false}
  3575    }
  3576  
  3577  
  3578  opt_full_backup_clause:
  3579    FULL BACKUP sconst_or_placeholder
  3580    // Can't use string_or_placeholder here due to conflict on ALWAYS branch below
  3581    // (is ALWAYS a keyword or a variable?).
  3582    {
  3583      $$.val = &tree.FullBackupClause{Recurrence: $3.expr()}
  3584    }
  3585  | FULL BACKUP ALWAYS
  3586    {
  3587      $$.val = &tree.FullBackupClause{AlwaysFull: true}
  3588    }
  3589  | /* EMPTY */
  3590    {
  3591      $$.val = (*tree.FullBackupClause)(nil)
  3592    }
  3593  
  3594  opt_with_schedule_options:
  3595    WITH SCHEDULE OPTIONS kv_option_list
  3596    {
  3597      $$.val = $4.kvOptions()
  3598    }
  3599  | WITH SCHEDULE OPTIONS '(' kv_option_list ')'
  3600    {
  3601      $$.val = $5.kvOptions()
  3602    }
  3603  | /* EMPTY */
  3604    {
  3605      $$.val = nil
  3606    }
  3607  
  3608  
  3609  // %Help: CREATE EXTERNAL CONNECTION - create a new external connection
  3610  // %Category: Misc
  3611  // %Text:
  3612  // CREATE EXTERNAL CONNECTION [IF NOT EXISTS] <name> AS <endpoint>
  3613  //
  3614  // Name:
  3615  //   Unique name for this external connection.
  3616  //
  3617  // Endpoint:
  3618  //   Endpoint of the resource that the external connection represents.
  3619  create_external_connection_stmt:
  3620  	CREATE EXTERNAL CONNECTION /*$4=*/label_spec AS /*$6=*/string_or_placeholder
  3621  	{
  3622  		$$.val = &tree.CreateExternalConnection{
  3623  				  ConnectionLabelSpec: *($4.labelSpec()),
  3624  		      As: $6.expr(),
  3625  		}
  3626  	}
  3627   | CREATE EXTERNAL CONNECTION error // SHOW HELP: CREATE EXTERNAL CONNECTION
  3628  
  3629  // %Help: DROP EXTERNAL CONNECTION - drop an existing external connection
  3630  // %Category: Misc
  3631  // %Text:
  3632  // DROP EXTERNAL CONNECTION <name>
  3633  //
  3634  // Name:
  3635  //   Unique name for this external connection.
  3636  drop_external_connection_stmt:
  3637  	DROP EXTERNAL CONNECTION string_or_placeholder
  3638  	{
  3639        $$.val = &tree.DropExternalConnection{
  3640              ConnectionLabel: $4.expr(),
  3641        }
  3642  	}
  3643  	| DROP EXTERNAL CONNECTION error // SHOW HELP: DROP EXTERNAL CONNECTION
  3644  
  3645  // %Help: RESTORE - restore data from external storage
  3646  // %Category: CCL
  3647  // %Text:
  3648  // RESTORE <targets...> FROM <location...>
  3649  //         [ AS OF SYSTEM TIME <expr> ]
  3650  //         [ WITH <option> [= <value>] [, ...] ]
  3651  // or
  3652  // RESTORE SYSTEM USERS FROM <location...>
  3653  //         [ AS OF SYSTEM TIME <expr> ]
  3654  //         [ WITH <option> [= <value>] [, ...] ]
  3655  //
  3656  // Targets:
  3657  //    TABLE <pattern> [, ...]
  3658  //    DATABASE <databasename> [, ...]
  3659  //
  3660  // Locations:
  3661  //    "[scheme]://[host]/[path to backup]?[parameters]"
  3662  //
  3663  // Options:
  3664  //    into_db: specify target database
  3665  //    skip_missing_foreign_keys: remove foreign key constraints before restoring
  3666  //    skip_missing_sequences: ignore sequence dependencies
  3667  //    skip_missing_views: skip restoring views because of dependencies that cannot be restored
  3668  //    skip_missing_sequence_owners: remove sequence-table ownership dependencies before restoring
  3669  //    skip_missing_udfs: skip restoring
  3670  //    encryption_passphrase=passphrase: decrypt BACKUP with specified passphrase
  3671  //    kms="[kms_provider]://[kms_host]/[master_key_identifier]?[parameters]" : decrypt backups using KMS
  3672  //    detached: execute restore job asynchronously, without waiting for its completion
  3673  //    skip_localities_check: ignore difference of zone configuration between restore cluster and backup cluster
  3674  //    debug_pause_on: describes the events that the job should pause itself on for debugging purposes.
  3675  //    new_db_name: renames the restored database. only applies to database restores
  3676  //    include_all_virtual_clusters: enable backups of all virtual clusters during a cluster backup
  3677  // %SeeAlso: BACKUP, WEBDOCS/restore.html
  3678  restore_stmt:
  3679    RESTORE FROM list_of_string_or_placeholder_opt_list opt_as_of_clause opt_with_restore_options
  3680    {
  3681      $$.val = &tree.Restore{
  3682      DescriptorCoverage: tree.AllDescriptors,
  3683      From: $3.listOfStringOrPlaceholderOptList(),
  3684      AsOf: $4.asOfClause(),
  3685      Options: *($5.restoreOptions()),
  3686      }
  3687    }
  3688  | RESTORE FROM string_or_placeholder IN list_of_string_or_placeholder_opt_list opt_as_of_clause opt_with_restore_options
  3689    {
  3690      $$.val = &tree.Restore{
  3691      DescriptorCoverage: tree.AllDescriptors,
  3692  		Subdir: $3.expr(),
  3693  		From: $5.listOfStringOrPlaceholderOptList(),
  3694  		AsOf: $6.asOfClause(),
  3695  		Options: *($7.restoreOptions()),
  3696      }
  3697    }
  3698  | RESTORE backup_targets FROM list_of_string_or_placeholder_opt_list opt_as_of_clause opt_with_restore_options
  3699    {
  3700      $$.val = &tree.Restore{
  3701      Targets: $2.backupTargetList(),
  3702      From: $4.listOfStringOrPlaceholderOptList(),
  3703      AsOf: $5.asOfClause(),
  3704      Options: *($6.restoreOptions()),
  3705      }
  3706    }
  3707  | RESTORE backup_targets FROM string_or_placeholder IN list_of_string_or_placeholder_opt_list opt_as_of_clause opt_with_restore_options
  3708    {
  3709      $$.val = &tree.Restore{
  3710        Targets: $2.backupTargetList(),
  3711        Subdir: $4.expr(),
  3712        From: $6.listOfStringOrPlaceholderOptList(),
  3713        AsOf: $7.asOfClause(),
  3714        Options: *($8.restoreOptions()),
  3715      }
  3716    }
  3717  | RESTORE SYSTEM USERS FROM list_of_string_or_placeholder_opt_list opt_as_of_clause opt_with_restore_options
  3718    {
  3719      $$.val = &tree.Restore{
  3720        DescriptorCoverage: tree.SystemUsers,
  3721        From: $5.listOfStringOrPlaceholderOptList(),
  3722        AsOf: $6.asOfClause(),
  3723        Options: *($7.restoreOptions()),
  3724      }
  3725    }
  3726  | RESTORE SYSTEM USERS FROM string_or_placeholder IN list_of_string_or_placeholder_opt_list opt_as_of_clause opt_with_restore_options
  3727    {
  3728      $$.val = &tree.Restore{
  3729        DescriptorCoverage: tree.SystemUsers,
  3730        Subdir: $5.expr(),
  3731        From: $7.listOfStringOrPlaceholderOptList(),
  3732        AsOf: $8.asOfClause(),
  3733        Options: *($9.restoreOptions()),
  3734      }
  3735    }
  3736  | RESTORE error // SHOW HELP: RESTORE
  3737  
  3738  string_or_placeholder_opt_list:
  3739    string_or_placeholder
  3740    {
  3741      $$.val = tree.StringOrPlaceholderOptList{$1.expr()}
  3742    }
  3743  | '(' string_or_placeholder_list ')'
  3744    {
  3745      $$.val = tree.StringOrPlaceholderOptList($2.exprs())
  3746    }
  3747  
  3748  list_of_string_or_placeholder_opt_list:
  3749    string_or_placeholder_opt_list
  3750    {
  3751      $$.val = []tree.StringOrPlaceholderOptList{$1.stringOrPlaceholderOptList()}
  3752    }
  3753  | list_of_string_or_placeholder_opt_list ',' string_or_placeholder_opt_list
  3754    {
  3755      $$.val = append($1.listOfStringOrPlaceholderOptList(), $3.stringOrPlaceholderOptList())
  3756    }
  3757  
  3758  // Optional restore options.
  3759  opt_with_restore_options:
  3760    WITH restore_options_list
  3761    {
  3762      $$.val = $2.restoreOptions()
  3763    }
  3764  | WITH OPTIONS '(' restore_options_list ')'
  3765    {
  3766      $$.val = $4.restoreOptions()
  3767    }
  3768  | /* EMPTY */
  3769    {
  3770      $$.val = &tree.RestoreOptions{}
  3771    }
  3772  
  3773  restore_options_list:
  3774    // Require at least one option
  3775    restore_options
  3776    {
  3777      $$.val = $1.restoreOptions()
  3778    }
  3779  | restore_options_list ',' restore_options
  3780    {
  3781      if err := $1.restoreOptions().CombineWith($3.restoreOptions()); err != nil {
  3782        return setErr(sqllex, err)
  3783      }
  3784    }
  3785  
  3786  // List of valid restore options.
  3787  restore_options:
  3788    ENCRYPTION_PASSPHRASE '=' string_or_placeholder
  3789    {
  3790      $$.val = &tree.RestoreOptions{EncryptionPassphrase: $3.expr()}
  3791    }
  3792  | KMS '=' string_or_placeholder_opt_list
  3793  	{
  3794      $$.val = &tree.RestoreOptions{DecryptionKMSURI: $3.stringOrPlaceholderOptList()}
  3795  	}
  3796  | INTO_DB '=' string_or_placeholder
  3797    {
  3798      $$.val = &tree.RestoreOptions{IntoDB: $3.expr()}
  3799    }
  3800  | SKIP_MISSING_FOREIGN_KEYS
  3801    {
  3802      $$.val = &tree.RestoreOptions{SkipMissingFKs: true}
  3803    }
  3804  | SKIP_MISSING_SEQUENCES
  3805    {
  3806      $$.val = &tree.RestoreOptions{SkipMissingSequences: true}
  3807    }
  3808  | SKIP_MISSING_SEQUENCE_OWNERS
  3809    {
  3810      $$.val = &tree.RestoreOptions{SkipMissingSequenceOwners: true}
  3811    }
  3812  | SKIP_MISSING_VIEWS
  3813    {
  3814      $$.val = &tree.RestoreOptions{SkipMissingViews: true}
  3815    }
  3816  | SKIP_MISSING_UDFS
  3817    {
  3818      $$.val = &tree.RestoreOptions{SkipMissingUDFs: true}
  3819    }
  3820  | DETACHED
  3821    {
  3822      $$.val = &tree.RestoreOptions{Detached: true}
  3823    }
  3824  | SKIP_LOCALITIES_CHECK
  3825    {
  3826      $$.val = &tree.RestoreOptions{SkipLocalitiesCheck: true}
  3827    }
  3828  | DEBUG_PAUSE_ON '=' string_or_placeholder
  3829    {
  3830      $$.val = &tree.RestoreOptions{DebugPauseOn: $3.expr()}
  3831    }
  3832  | NEW_DB_NAME '=' string_or_placeholder
  3833    {
  3834      $$.val = &tree.RestoreOptions{NewDBName: $3.expr()}
  3835    }
  3836  | include_all_clusters
  3837    {
  3838      $$.val = &tree.RestoreOptions{IncludeAllSecondaryTenants: tree.MakeDBool(true)}
  3839    }
  3840  | include_all_clusters '=' a_expr
  3841    {
  3842      $$.val = &tree.RestoreOptions{IncludeAllSecondaryTenants: $3.expr()}
  3843    }
  3844  | INCREMENTAL_LOCATION '=' string_or_placeholder_opt_list
  3845  	{
  3846  		$$.val = &tree.RestoreOptions{IncrementalStorage: $3.stringOrPlaceholderOptList()}
  3847  	}
  3848  | virtual_cluster_name '=' string_or_placeholder
  3849    {
  3850      $$.val = &tree.RestoreOptions{AsTenant: $3.expr()}
  3851    }
  3852  | virtual_cluster_opt '=' string_or_placeholder
  3853    {
  3854      $$.val = &tree.RestoreOptions{ForceTenantID: $3.expr()}
  3855    }
  3856  | SCHEMA_ONLY
  3857  	{
  3858  		$$.val = &tree.RestoreOptions{SchemaOnly: true}
  3859  	}
  3860  | VERIFY_BACKUP_TABLE_DATA
  3861  	{
  3862  		$$.val = &tree.RestoreOptions{VerifyData: true}
  3863  	}
  3864  | UNSAFE_RESTORE_INCOMPATIBLE_VERSION
  3865    {
  3866      $$.val = &tree.RestoreOptions{UnsafeRestoreIncompatibleVersion: true}
  3867    }
  3868  | EXECUTION LOCALITY '=' string_or_placeholder
  3869    {
  3870      $$.val = &tree.RestoreOptions{ExecutionLocality: $4.expr()}
  3871    }
  3872  | EXPERIMENTAL DEFERRED COPY
  3873    {
  3874      $$.val = &tree.RestoreOptions{ExperimentalOnline: true}
  3875    }
  3876  | REMOVE_REGIONS
  3877    {
  3878      $$.val = &tree.RestoreOptions{RemoveRegions: true, SkipLocalitiesCheck: true}
  3879    }
  3880  
  3881  virtual_cluster_opt:
  3882    TENANT  { /* SKIP DOC */ }
  3883  | VIRTUAL_CLUSTER { }
  3884  
  3885  virtual_cluster_name:
  3886    TENANT_NAME { /* SKIP DOC */ }
  3887  | VIRTUAL_CLUSTER_NAME { }
  3888  
  3889  import_format:
  3890    name
  3891    {
  3892      $$ = strings.ToUpper($1)
  3893    }
  3894  
  3895  alter_unsupported_stmt:
  3896    ALTER DOMAIN error
  3897    {
  3898      return unimplemented(sqllex, "alter domain")
  3899    }
  3900  | ALTER AGGREGATE error
  3901    {
  3902      return unimplementedWithIssueDetail(sqllex, 74775, "alter aggregate")
  3903    }
  3904  
  3905  // %Help: IMPORT - load data from file in a distributed manner
  3906  // %Category: CCL
  3907  // %Text:
  3908  // -- Import both schema and table data:
  3909  // IMPORT [ TABLE <tablename> FROM ]
  3910  //        <format> <datafile>
  3911  //        [ WITH <option> [= <value>] [, ...] ]
  3912  //
  3913  // Formats:
  3914  //    MYSQLDUMP
  3915  //    PGDUMP
  3916  //
  3917  // Options:
  3918  //    distributed = '...'
  3919  //    sstsize = '...'
  3920  //    temp = '...'
  3921  //
  3922  // Use CREATE TABLE followed by IMPORT INTO to create and import into a table
  3923  // from external files that only have table data.
  3924  //
  3925  // %SeeAlso: CREATE TABLE, WEBDOCS/import-into.html
  3926  import_stmt:
  3927   IMPORT import_format '(' string_or_placeholder ')' opt_with_options
  3928    {
  3929      /* SKIP DOC */
  3930      $$.val = &tree.Import{Bundle: true, FileFormat: $2, Files: tree.Exprs{$4.expr()}, Options: $6.kvOptions()}
  3931    }
  3932  | IMPORT import_format string_or_placeholder opt_with_options
  3933    {
  3934      $$.val = &tree.Import{Bundle: true, FileFormat: $2, Files: tree.Exprs{$3.expr()}, Options: $4.kvOptions()}
  3935    }
  3936  | IMPORT TABLE table_name FROM import_format '(' string_or_placeholder ')' opt_with_options
  3937    {
  3938      /* SKIP DOC */
  3939      name := $3.unresolvedObjectName().ToTableName()
  3940      $$.val = &tree.Import{Bundle: true, Table: &name, FileFormat: $5, Files: tree.Exprs{$7.expr()}, Options: $9.kvOptions()}
  3941    }
  3942  | IMPORT TABLE table_name FROM import_format string_or_placeholder opt_with_options
  3943    {
  3944      name := $3.unresolvedObjectName().ToTableName()
  3945      $$.val = &tree.Import{Bundle: true, Table: &name, FileFormat: $5, Files: tree.Exprs{$6.expr()}, Options: $7.kvOptions()}
  3946    }
  3947  | IMPORT INTO table_name '(' insert_column_list ')' import_format DATA '(' string_or_placeholder_list ')' opt_with_options
  3948    {
  3949      name := $3.unresolvedObjectName().ToTableName()
  3950      $$.val = &tree.Import{Table: &name, Into: true, IntoCols: $5.nameList(), FileFormat: $7, Files: $10.exprs(), Options: $12.kvOptions()}
  3951    }
  3952  | IMPORT INTO table_name import_format DATA '(' string_or_placeholder_list ')' opt_with_options
  3953    {
  3954      name := $3.unresolvedObjectName().ToTableName()
  3955      $$.val = &tree.Import{Table: &name, Into: true, IntoCols: nil, FileFormat: $4, Files: $7.exprs(), Options: $9.kvOptions()}
  3956    }
  3957  | IMPORT error // SHOW HELP: IMPORT
  3958  
  3959  // %Help: EXPORT - export data to file in a distributed manner
  3960  // %Category: CCL
  3961  // %Text:
  3962  // EXPORT INTO <format> <datafile> [WITH <option> [= value] [,...]] FROM <query>
  3963  //
  3964  // Formats:
  3965  //    CSV
  3966  //    Parquet
  3967  //
  3968  // Options:
  3969  //    delimiter = '...'   [CSV-specific]
  3970  //
  3971  // %SeeAlso: SELECT
  3972  export_stmt:
  3973    EXPORT INTO import_format string_or_placeholder opt_with_options FROM select_stmt
  3974    {
  3975      $$.val = &tree.Export{Query: $7.slct(), FileFormat: $3, File: $4.expr(), Options: $5.kvOptions()}
  3976    }
  3977  | EXPORT error // SHOW HELP: EXPORT
  3978  
  3979  string_or_placeholder:
  3980    non_reserved_word_or_sconst
  3981    {
  3982      $$.val = tree.NewStrVal($1)
  3983    }
  3984  | PLACEHOLDER
  3985    {
  3986      p := $1.placeholder()
  3987      sqllex.(*lexer).UpdateNumPlaceholders(p)
  3988      $$.val = p
  3989    }
  3990  
  3991  string_or_placeholder_list:
  3992    string_or_placeholder
  3993    {
  3994      $$.val = tree.Exprs{$1.expr()}
  3995    }
  3996  | string_or_placeholder_list ',' string_or_placeholder
  3997    {
  3998      $$.val = append($1.exprs(), $3.expr())
  3999    }
  4000  
  4001  opt_incremental:
  4002    INCREMENTAL FROM string_or_placeholder_list
  4003    {
  4004      $$.val = $3.exprs()
  4005    }
  4006  | /* EMPTY */
  4007    {
  4008      $$.val = tree.Exprs(nil)
  4009    }
  4010  
  4011  kv_option:
  4012    name '=' string_or_placeholder
  4013    {
  4014      $$.val = tree.KVOption{Key: tree.Name($1), Value: $3.expr()}
  4015    }
  4016  |  name
  4017    {
  4018      $$.val = tree.KVOption{Key: tree.Name($1)}
  4019    }
  4020  |  SCONST '=' string_or_placeholder
  4021    {
  4022      $$.val = tree.KVOption{Key: tree.Name($1), Value: $3.expr()}
  4023    }
  4024  |  SCONST
  4025    {
  4026      $$.val = tree.KVOption{Key: tree.Name($1)}
  4027    }
  4028  
  4029  kv_option_list:
  4030    kv_option
  4031    {
  4032      $$.val = []tree.KVOption{$1.kvOption()}
  4033    }
  4034  |  kv_option_list ',' kv_option
  4035    {
  4036      $$.val = append($1.kvOptions(), $3.kvOption())
  4037    }
  4038  
  4039  opt_with_options:
  4040    WITH kv_option_list
  4041    {
  4042      $$.val = $2.kvOptions()
  4043    }
  4044  | WITH OPTIONS '(' kv_option_list ')'
  4045    {
  4046      $$.val = $4.kvOptions()
  4047    }
  4048  | /* EMPTY */
  4049    {
  4050      $$.val = nil
  4051    }
  4052  
  4053  // %Help: CALL - invoke a procedure
  4054  // %Category: Misc
  4055  // %Text: CALL <name> ( [ <expr> [, ...] ] )
  4056  // %SeeAlso: CREATE PROCEDURE
  4057  call_stmt:
  4058    CALL func_application
  4059    {
  4060      p := $2.expr().(*tree.FuncExpr)
  4061      p.InCall = true
  4062      $$.val = &tree.Call{Proc: p}
  4063    }
  4064  
  4065  // The COPY grammar in postgres has 3 different versions, all of which are supported by postgres:
  4066  // 1) The "really old" syntax from v7.2 and prior
  4067  // 2) Pre 9.0 using hard-wired, space-separated options
  4068  // 3) The current and preferred options using comma-separated generic identifiers instead of keywords.
  4069  // We currently support only the #2 format.
  4070  // See the comment for CopyStmt in https://github.com/postgres/postgres/blob/master/src/backend/parser/gram.y.
  4071  copy_stmt:
  4072    COPY table_name opt_column_list FROM STDIN opt_with_copy_options opt_where_clause
  4073    {
  4074      /* FORCE DOC */
  4075      name := $2.unresolvedObjectName().ToTableName()
  4076      if $7.expr() != nil {
  4077        return unimplementedWithIssue(sqllex, 54580)
  4078      }
  4079      $$.val = &tree.CopyFrom{
  4080         Table: name,
  4081         Columns: $3.nameList(),
  4082         Stdin: true,
  4083         Options: *$6.copyOptions(),
  4084      }
  4085    }
  4086  | COPY table_name opt_column_list FROM error
  4087    {
  4088      return unimplemented(sqllex, "copy from unsupported format")
  4089    }
  4090  | COPY table_name opt_column_list TO STDOUT opt_with_copy_options
  4091    {
  4092      /* FORCE DOC */
  4093      name := $2.unresolvedObjectName().ToTableName()
  4094      $$.val = &tree.CopyTo{
  4095         Table: name,
  4096         Columns: $3.nameList(),
  4097         Options: *$6.copyOptions(),
  4098      }
  4099    }
  4100  | COPY table_name opt_column_list TO error
  4101    {
  4102      return unimplementedWithIssue(sqllex, 97181)
  4103    }
  4104  | COPY '(' copy_to_stmt ')' TO STDOUT opt_with_copy_options
  4105     {
  4106       /* FORCE DOC */
  4107       $$.val = &tree.CopyTo{
  4108          Statement: $3.stmt(),
  4109          Options: *$7.copyOptions(),
  4110       }
  4111     }
  4112  | COPY '(' copy_to_stmt ')' TO error
  4113     {
  4114       return unimplementedWithIssue(sqllex, 96590)
  4115     }
  4116  
  4117  opt_with_copy_options:
  4118    opt_with copy_options_list
  4119    {
  4120      $$.val = $2.copyOptions()
  4121    }
  4122  | opt_with '(' copy_generic_options_list ')'
  4123    {
  4124      $$.val = $3.copyOptions()
  4125    }
  4126  | /* EMPTY */
  4127    {
  4128      $$.val = &tree.CopyOptions{}
  4129    }
  4130  
  4131  copy_options_list:
  4132    copy_options
  4133    {
  4134      $$.val = $1.copyOptions()
  4135    }
  4136  | copy_options_list copy_options
  4137    {
  4138      if err := $1.copyOptions().CombineWith($2.copyOptions()); err != nil {
  4139        return setErr(sqllex, err)
  4140      }
  4141    }
  4142  
  4143  copy_generic_options_list:
  4144    copy_generic_options
  4145    {
  4146      $$.val = $1.copyOptions()
  4147    }
  4148  | copy_generic_options_list ',' copy_generic_options
  4149    {
  4150      if err := $1.copyOptions().CombineWith($3.copyOptions()); err != nil {
  4151        return setErr(sqllex, err)
  4152      }
  4153    }
  4154  
  4155  copy_options:
  4156    DESTINATION '=' string_or_placeholder
  4157    {
  4158      $$.val = &tree.CopyOptions{Destination: $3.expr()}
  4159    }
  4160  | BINARY
  4161    {
  4162      $$.val = &tree.CopyOptions{CopyFormat: tree.CopyFormatBinary, HasFormat: true}
  4163    }
  4164  | CSV
  4165    {
  4166      $$.val = &tree.CopyOptions{CopyFormat: tree.CopyFormatCSV, HasFormat: true}
  4167    }
  4168  | DELIMITER string_or_placeholder
  4169    {
  4170      $$.val = &tree.CopyOptions{Delimiter: $2.expr()}
  4171    }
  4172  | NULL string_or_placeholder
  4173    {
  4174      $$.val = &tree.CopyOptions{Null: $2.expr()}
  4175    }
  4176  | OIDS error
  4177    {
  4178      return unimplementedWithIssueDetail(sqllex, 41608, "oids")
  4179    }
  4180  | FREEZE error
  4181    {
  4182      return unimplementedWithIssueDetail(sqllex, 41608, "freeze")
  4183    }
  4184  | HEADER
  4185    {
  4186      $$.val = &tree.CopyOptions{Header: true, HasHeader: true}
  4187    }
  4188  | QUOTE SCONST
  4189    {
  4190      $$.val = &tree.CopyOptions{Quote: tree.NewStrVal($2)}
  4191    }
  4192  | ESCAPE SCONST
  4193    {
  4194      $$.val = &tree.CopyOptions{Escape: tree.NewStrVal($2)}
  4195    }
  4196  | FORCE QUOTE error
  4197    {
  4198      return unimplementedWithIssueDetail(sqllex, 41608, "force_quote")
  4199    }
  4200  | FORCE NOT NULL error
  4201    {
  4202      return unimplementedWithIssueDetail(sqllex, 41608, "force_not_null")
  4203    }
  4204  | FORCE NULL error
  4205    {
  4206      return unimplementedWithIssueDetail(sqllex, 41608, "force_null")
  4207    }
  4208  | ENCODING SCONST error
  4209    {
  4210      return unimplementedWithIssueDetail(sqllex, 41608, "encoding")
  4211    }
  4212  
  4213  copy_generic_options:
  4214    DESTINATION string_or_placeholder
  4215    {
  4216      $$.val = &tree.CopyOptions{Destination: $2.expr()}
  4217    }
  4218  | FORMAT BINARY
  4219    {
  4220      $$.val = &tree.CopyOptions{CopyFormat: tree.CopyFormatBinary, HasFormat: true}
  4221    }
  4222  | FORMAT CSV
  4223    {
  4224      $$.val = &tree.CopyOptions{CopyFormat: tree.CopyFormatCSV, HasFormat: true}
  4225    }
  4226  | FORMAT TEXT
  4227    {
  4228      $$.val = &tree.CopyOptions{CopyFormat: tree.CopyFormatText, HasFormat: true}
  4229    }
  4230  | FORMAT SCONST
  4231    {
  4232      format := $2
  4233      switch format {
  4234      case "csv":
  4235        $$.val = &tree.CopyOptions{CopyFormat: tree.CopyFormatCSV, HasFormat: true}
  4236      case "binary":
  4237        $$.val = &tree.CopyOptions{CopyFormat: tree.CopyFormatBinary, HasFormat: true}
  4238      case "text":
  4239        $$.val = &tree.CopyOptions{CopyFormat: tree.CopyFormatText, HasFormat: true}
  4240      default:
  4241        sqllex.Error("COPY format \"" + format + "\" not recognized")
  4242        return 1
  4243      }
  4244    }
  4245  | DELIMITER string_or_placeholder
  4246    {
  4247      $$.val = &tree.CopyOptions{Delimiter: $2.expr()}
  4248    }
  4249  | NULL string_or_placeholder
  4250    {
  4251      $$.val = &tree.CopyOptions{Null: $2.expr()}
  4252    }
  4253  | OIDS error
  4254    {
  4255      return unimplementedWithIssueDetail(sqllex, 41608, "oids")
  4256    }
  4257  | FREEZE error
  4258    {
  4259      return unimplementedWithIssueDetail(sqllex, 41608, "freeze")
  4260    }
  4261  | HEADER
  4262    {
  4263      $$.val = &tree.CopyOptions{Header: true, HasHeader: true}
  4264    }
  4265  | HEADER TRUE
  4266    {
  4267      $$.val = &tree.CopyOptions{Header: true, HasHeader: true}
  4268    }
  4269  | HEADER FALSE
  4270    {
  4271      $$.val = &tree.CopyOptions{Header: false, HasHeader: true}
  4272    }
  4273  | QUOTE SCONST
  4274    {
  4275      $$.val = &tree.CopyOptions{Quote: tree.NewStrVal($2)}
  4276    }
  4277  | ESCAPE SCONST
  4278    {
  4279      $$.val = &tree.CopyOptions{Escape: tree.NewStrVal($2)}
  4280    }
  4281  | FORCE_QUOTE error
  4282    {
  4283      return unimplementedWithIssueDetail(sqllex, 41608, "force_quote")
  4284    }
  4285  | FORCE_NOT_NULL error
  4286    {
  4287      return unimplementedWithIssueDetail(sqllex, 41608, "force_not_null")
  4288    }
  4289  | FORCE_NULL error
  4290    {
  4291      return unimplementedWithIssueDetail(sqllex, 41608, "force_null")
  4292    }
  4293  | ENCODING SCONST error
  4294    {
  4295      return unimplementedWithIssueDetail(sqllex, 41608, "encoding")
  4296    }
  4297  
  4298  // %Help: CANCEL
  4299  // %Category: Group
  4300  // %Text: CANCEL JOBS, CANCEL QUERIES, CANCEL SESSIONS
  4301  cancel_stmt:
  4302    cancel_jobs_stmt      // EXTEND WITH HELP: CANCEL JOBS
  4303  | cancel_queries_stmt   // EXTEND WITH HELP: CANCEL QUERIES
  4304  | cancel_sessions_stmt  // EXTEND WITH HELP: CANCEL SESSIONS
  4305  | cancel_all_jobs_stmt  // EXTEND WITH HELP: CANCEL ALL JOBS
  4306  | CANCEL error          // SHOW HELP: CANCEL
  4307  
  4308  // %Help: CANCEL JOBS - cancel background jobs
  4309  // %Category: Misc
  4310  // %Text:
  4311  // CANCEL JOBS <selectclause>
  4312  // CANCEL JOB <jobid>
  4313  // %SeeAlso: SHOW JOBS, PAUSE JOBS, RESUME JOBS
  4314  cancel_jobs_stmt:
  4315    CANCEL JOB a_expr
  4316    {
  4317      $$.val = &tree.ControlJobs{
  4318        Jobs: &tree.Select{
  4319          Select: &tree.ValuesClause{Rows: []tree.Exprs{tree.Exprs{$3.expr()}}},
  4320        },
  4321        Command: tree.CancelJob,
  4322      }
  4323    }
  4324  | CANCEL JOB error // SHOW HELP: CANCEL JOBS
  4325  | CANCEL JOBS select_stmt
  4326    {
  4327      $$.val = &tree.ControlJobs{Jobs: $3.slct(), Command: tree.CancelJob}
  4328    }
  4329  | CANCEL JOBS for_schedules_clause
  4330    {
  4331      $$.val = &tree.ControlJobsForSchedules{Schedules: $3.slct(), Command: tree.CancelJob}
  4332    }
  4333  | CANCEL JOBS error // SHOW HELP: CANCEL JOBS
  4334  
  4335  // %Help: CANCEL QUERIES - cancel running queries
  4336  // %Category: Misc
  4337  // %Text:
  4338  // CANCEL QUERIES [IF EXISTS] <selectclause>
  4339  // CANCEL QUERY [IF EXISTS] <expr>
  4340  // %SeeAlso: SHOW STATEMENTS
  4341  cancel_queries_stmt:
  4342    CANCEL QUERY a_expr
  4343    {
  4344      $$.val = &tree.CancelQueries{
  4345        Queries: &tree.Select{
  4346          Select: &tree.ValuesClause{Rows: []tree.Exprs{tree.Exprs{$3.expr()}}},
  4347        },
  4348        IfExists: false,
  4349      }
  4350    }
  4351  | CANCEL QUERY IF EXISTS a_expr
  4352    {
  4353      $$.val = &tree.CancelQueries{
  4354        Queries: &tree.Select{
  4355          Select: &tree.ValuesClause{Rows: []tree.Exprs{tree.Exprs{$5.expr()}}},
  4356        },
  4357        IfExists: true,
  4358      }
  4359    }
  4360  | CANCEL QUERY error // SHOW HELP: CANCEL QUERIES
  4361  | CANCEL QUERIES select_stmt
  4362    {
  4363      $$.val = &tree.CancelQueries{Queries: $3.slct(), IfExists: false}
  4364    }
  4365  | CANCEL QUERIES IF EXISTS select_stmt
  4366    {
  4367      $$.val = &tree.CancelQueries{Queries: $5.slct(), IfExists: true}
  4368    }
  4369  | CANCEL QUERIES error // SHOW HELP: CANCEL QUERIES
  4370  
  4371  // %Help: CANCEL SESSIONS - cancel open sessions
  4372  // %Category: Misc
  4373  // %Text:
  4374  // CANCEL SESSIONS [IF EXISTS] <selectclause>
  4375  // CANCEL SESSION [IF EXISTS] <sessionid>
  4376  // %SeeAlso: SHOW SESSIONS
  4377  cancel_sessions_stmt:
  4378    CANCEL SESSION a_expr
  4379    {
  4380     $$.val = &tree.CancelSessions{
  4381        Sessions: &tree.Select{
  4382          Select: &tree.ValuesClause{Rows: []tree.Exprs{tree.Exprs{$3.expr()}}},
  4383        },
  4384        IfExists: false,
  4385      }
  4386    }
  4387  | CANCEL SESSION IF EXISTS a_expr
  4388    {
  4389     $$.val = &tree.CancelSessions{
  4390        Sessions: &tree.Select{
  4391          Select: &tree.ValuesClause{Rows: []tree.Exprs{tree.Exprs{$5.expr()}}},
  4392        },
  4393        IfExists: true,
  4394      }
  4395    }
  4396  | CANCEL SESSION error // SHOW HELP: CANCEL SESSIONS
  4397  | CANCEL SESSIONS select_stmt
  4398    {
  4399      $$.val = &tree.CancelSessions{Sessions: $3.slct(), IfExists: false}
  4400    }
  4401  | CANCEL SESSIONS IF EXISTS select_stmt
  4402    {
  4403      $$.val = &tree.CancelSessions{Sessions: $5.slct(), IfExists: true}
  4404    }
  4405  | CANCEL SESSIONS error // SHOW HELP: CANCEL SESSIONS
  4406  
  4407  // %Help: CANCEL ALL JOBS - cancel all background jobs
  4408  // %Category: Misc
  4409  // %Text:
  4410  // CANCEL ALL {BACKUP|CHANGEFEED|IMPORT|RESTORE} JOBS
  4411  cancel_all_jobs_stmt:
  4412    CANCEL ALL name JOBS
  4413    {
  4414      $$.val = &tree.ControlJobsOfType{Type: $3, Command: tree.CancelJob}
  4415    }
  4416  | CANCEL ALL error // SHOW HELP: CANCEL ALL JOBS
  4417  
  4418  comment_stmt:
  4419    COMMENT ON DATABASE database_name IS comment_text
  4420    {
  4421      $$.val = &tree.CommentOnDatabase{Name: tree.Name($4), Comment: $6.strPtr()}
  4422    }
  4423  | COMMENT ON SCHEMA qualifiable_schema_name IS comment_text
  4424    {
  4425      $$.val = &tree.CommentOnSchema{Name: $4.objectNamePrefix(), Comment: $6.strPtr()}
  4426    }
  4427  | COMMENT ON TABLE table_name IS comment_text
  4428    {
  4429      $$.val = &tree.CommentOnTable{Table: $4.unresolvedObjectName(), Comment: $6.strPtr()}
  4430    }
  4431  | COMMENT ON COLUMN column_path IS comment_text
  4432    {
  4433      varName, err := $4.unresolvedName().NormalizeVarName()
  4434      if err != nil {
  4435        return setErr(sqllex, err)
  4436      }
  4437      columnItem, ok := varName.(*tree.ColumnItem)
  4438      if !ok {
  4439        sqllex.Error(fmt.Sprintf("invalid column name: %q", tree.ErrString($4.unresolvedName())))
  4440              return 1
  4441      }
  4442      if columnItem != nil && columnItem.TableName != nil {
  4443        aIdx := sqllex.(*lexer).NewAnnotation()
  4444        columnItem.TableName.AnnotatedNode = tree.AnnotatedNode{AnnIdx: aIdx}
  4445      }
  4446      $$.val = &tree.CommentOnColumn{ColumnItem: columnItem, Comment: $6.strPtr()}
  4447    }
  4448  | COMMENT ON INDEX table_index_name IS comment_text
  4449    {
  4450      $$.val = &tree.CommentOnIndex{Index: $4.tableIndexName(), Comment: $6.strPtr()}
  4451    }
  4452  
  4453  | COMMENT ON CONSTRAINT constraint_name ON table_name IS comment_text
  4454    {
  4455      $$.val = &tree.CommentOnConstraint{Constraint:tree.Name($4), Table: $6.unresolvedObjectName(), Comment: $8.strPtr()}
  4456    }
  4457  | COMMENT ON EXTENSION error { return unimplementedWithIssueDetail(sqllex, 74777, "comment on extension") }
  4458  | COMMENT ON FUNCTION error { return unimplementedWithIssueDetail(sqllex, 17511, "comment on function") }
  4459  
  4460  comment_text:
  4461    SCONST
  4462    {
  4463      t := $1
  4464      $$.val = &t
  4465    }
  4466  | NULL
  4467    {
  4468      var str *string
  4469      $$.val = str
  4470    }
  4471  
  4472  // %Help: CREATE
  4473  // %Category: Group
  4474  // %Text:
  4475  // CREATE DATABASE, CREATE TABLE, CREATE INDEX, CREATE TABLE AS,
  4476  // CREATE USER, CREATE VIEW, CREATE SEQUENCE, CREATE STATISTICS,
  4477  // CREATE ROLE, CREATE TYPE, CREATE EXTENSION, CREATE SCHEDULE
  4478  create_stmt:
  4479    create_role_stmt       // EXTEND WITH HELP: CREATE ROLE
  4480  | create_ddl_stmt        // help texts in sub-rule
  4481  | create_stats_stmt      // EXTEND WITH HELP: CREATE STATISTICS
  4482  | create_changefeed_stmt // EXTEND WITH HELP: CREATE CHANGEFEED
  4483  | create_extension_stmt  // EXTEND WITH HELP: CREATE EXTENSION
  4484  | create_external_connection_stmt // EXTEND WITH HELP: CREATE EXTERNAL CONNECTION
  4485  | create_virtual_cluster_stmt     // EXTEND WITH HELP: CREATE VIRTUAL CLUSTER
  4486  | create_schedule_stmt   // help texts in sub-rule
  4487  | create_unsupported     {}
  4488  | CREATE error           // SHOW HELP: CREATE
  4489  
  4490  // %Help: CREATE VIRTUAL CLUSTER - create a new virtual cluster
  4491  // %Category: Experimental
  4492  // %Text:
  4493  // CREATE VIRTUAL CLUSTER [ IF NOT EXISTS ] name [ LIKE <virtual_cluster_spec> ] [ <replication> ]
  4494  //
  4495  // Replication option:
  4496  //    FROM REPLICATION OF <virtual_cluster_spec> ON <location> [ WITH OPTIONS ... ]
  4497  create_virtual_cluster_stmt:
  4498    CREATE virtual_cluster d_expr opt_like_virtual_cluster
  4499    {
  4500      /* SKIP DOC */
  4501      $$.val = &tree.CreateTenant{
  4502        TenantSpec: &tree.TenantSpec{IsName: true, Expr: $3.expr()},
  4503        Like: $4.likeTenantSpec(),
  4504      }
  4505    }
  4506  | CREATE virtual_cluster IF NOT EXISTS d_expr opt_like_virtual_cluster
  4507    {
  4508      /* SKIP DOC */
  4509      $$.val = &tree.CreateTenant{
  4510        IfNotExists: true,
  4511        TenantSpec: &tree.TenantSpec{IsName: true, Expr: $6.expr()},
  4512        Like: $7.likeTenantSpec(),
  4513      }
  4514    }
  4515  | CREATE virtual_cluster d_expr opt_like_virtual_cluster FROM REPLICATION OF d_expr ON d_expr opt_with_replication_options
  4516    {
  4517      /* SKIP DOC */
  4518      $$.val = &tree.CreateTenantFromReplication{
  4519        TenantSpec: &tree.TenantSpec{IsName: true, Expr: $3.expr()},
  4520        ReplicationSourceTenantName: &tree.TenantSpec{IsName: true, Expr: $8.expr()},
  4521        ReplicationSourceAddress: $10.expr(),
  4522        Options: *$11.tenantReplicationOptions(),
  4523        Like: $4.likeTenantSpec(),
  4524      }
  4525    }
  4526  | CREATE virtual_cluster IF NOT EXISTS d_expr opt_like_virtual_cluster FROM REPLICATION OF d_expr ON d_expr opt_with_replication_options
  4527    {
  4528      /* SKIP DOC */
  4529      $$.val = &tree.CreateTenantFromReplication{
  4530        IfNotExists: true,
  4531        TenantSpec: &tree.TenantSpec{IsName: true, Expr: $6.expr()},
  4532        ReplicationSourceTenantName: &tree.TenantSpec{IsName: true, Expr: $11.expr()},
  4533        ReplicationSourceAddress: $13.expr(),
  4534        Options: *$14.tenantReplicationOptions(),
  4535        Like: $7.likeTenantSpec(),
  4536      }
  4537    }
  4538  | CREATE virtual_cluster error // SHOW HELP: CREATE VIRTUAL CLUSTER
  4539  
  4540  virtual_cluster:
  4541    TENANT { /* SKIP DOC */ }
  4542  | VIRTUAL CLUSTER
  4543  
  4544  // opt_like_virtual_cluster defines a LIKE clause for CREATE VIRTUAL CLUSTER.
  4545  // Eventually this can grow to support INCLUDING/EXCLUDING options
  4546  // like in CREATE TABLE.
  4547  opt_like_virtual_cluster:
  4548    /* EMPTY */
  4549    {
  4550       $$.val = &tree.LikeTenantSpec{}
  4551    }
  4552  | LIKE virtual_cluster_spec
  4553    {
  4554        $$.val = &tree.LikeTenantSpec{OtherTenant: $2.tenantSpec()}
  4555    }
  4556  
  4557  // Optional tenant replication options.
  4558  opt_with_replication_options:
  4559    WITH replication_options_list
  4560    {
  4561      $$.val = $2.tenantReplicationOptions()
  4562    }
  4563  | WITH OPTIONS '(' replication_options_list ')'
  4564    {
  4565      $$.val = $4.tenantReplicationOptions()
  4566    }
  4567  | /* EMPTY */
  4568    {
  4569      $$.val = &tree.TenantReplicationOptions{}
  4570    }
  4571  
  4572  replication_options_list:
  4573    // Require at least one option
  4574    replication_options
  4575    {
  4576      $$.val = $1.tenantReplicationOptions()
  4577    }
  4578  | replication_options_list ',' replication_options
  4579    {
  4580      if err := $1.tenantReplicationOptions().CombineWith($3.tenantReplicationOptions()); err != nil {
  4581        return setErr(sqllex, err)
  4582      }
  4583    }
  4584  
  4585  // List of valid tenant replication options.
  4586  replication_options:
  4587    RETENTION '=' d_expr
  4588    {
  4589      $$.val = &tree.TenantReplicationOptions{Retention: $3.expr()}
  4590    }
  4591  |
  4592    RESUME TIMESTAMP '=' d_expr
  4593    {
  4594      $$.val = &tree.TenantReplicationOptions{ResumeTimestamp: $4.expr()}
  4595    }
  4596  
  4597  // %Help: CREATE SCHEDULE
  4598  // %Category: Group
  4599  // %Text:
  4600  // CREATE SCHEDULE FOR BACKUP,
  4601  // CREATE SCHEDULE FOR CHANGEFEED
  4602  create_schedule_stmt:
  4603    create_schedule_for_changefeed_stmt // EXTEND WITH HELP: CREATE SCHEDULE FOR CHANGEFEED
  4604  | create_schedule_for_backup_stmt     // EXTEND WITH HELP: CREATE SCHEDULE FOR BACKUP
  4605  | CREATE SCHEDULE error               // SHOW HELP: CREATE SCHEDULE
  4606  
  4607  // %Help: CREATE EXTENSION - pseudo-statement for PostgreSQL compatibility
  4608  // %Category: Cfg
  4609  // %Text: CREATE EXTENSION [IF NOT EXISTS] name
  4610  create_extension_stmt:
  4611    CREATE EXTENSION IF NOT EXISTS name
  4612    {
  4613      $$.val = &tree.CreateExtension{IfNotExists: true, Name: tree.Name($6)}
  4614    }
  4615  | CREATE EXTENSION name {
  4616      $$.val = &tree.CreateExtension{Name: tree.Name($3)}
  4617    }
  4618  | CREATE EXTENSION IF NOT EXISTS name WITH error
  4619    {
  4620      return unimplementedWithIssueDetail(sqllex, 74777, "create extension if not exists with")
  4621    }
  4622  | CREATE EXTENSION name WITH error {
  4623      return unimplementedWithIssueDetail(sqllex, 74777, "create extension with")
  4624    }
  4625  | CREATE EXTENSION error // SHOW HELP: CREATE EXTENSION
  4626  
  4627  // %Help: CREATE FUNCTION - define a new function
  4628  // %Category: DDL
  4629  // %Text:
  4630  // CREATE [ OR REPLACE ] FUNCTION
  4631  //    name ( [ [ argmode ] [ argname ] argtype [, ...] ] )
  4632  //    [ RETURNS rettype ]
  4633  //  { LANGUAGE lang_name
  4634  //    | { IMMUTABLE | STABLE | VOLATILE }
  4635  //    | [ NOT ] LEAKPROOF
  4636  //    | { CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT }
  4637  //    | AS 'definition'
  4638  //  } ...
  4639  // %SeeAlso: WEBDOCS/create-function.html
  4640  create_func_stmt:
  4641    CREATE opt_or_replace FUNCTION routine_create_name '(' opt_routine_param_with_default_list ')'
  4642    RETURNS opt_return_table opt_return_set routine_return_type
  4643    opt_create_routine_opt_list opt_routine_body
  4644    {
  4645      name := $4.unresolvedObjectName().ToRoutineName()
  4646      $$.val = &tree.CreateRoutine{
  4647        IsProcedure: false,
  4648        Replace: $2.bool(),
  4649        Name: name,
  4650        Params: $6.routineParams(),
  4651        ReturnType: tree.RoutineReturnType{
  4652          Type: $11.typeReference(),
  4653          SetOf: $10.bool(),
  4654        },
  4655        Options: $12.routineOptions(),
  4656        RoutineBody: $13.routineBody(),
  4657      }
  4658    }
  4659  | CREATE opt_or_replace FUNCTION error // SHOW HELP: CREATE FUNCTION
  4660  
  4661  // %Help: CREATE PROCEDURE - define a new procedure
  4662  // %Category: DDL
  4663  // %Text:
  4664  // CREATE [ OR REPLACE ] PROCEDURE
  4665  //    name ( [ [ argmode ] [ argname ] argtype [, ...] ] )
  4666  //  { LANGUAGE lang_name
  4667  //    | AS 'definition'
  4668  //  } ...
  4669  // %SeeAlso: WEBDOCS/create-procedure.html
  4670  create_proc_stmt:
  4671    CREATE opt_or_replace PROCEDURE routine_create_name '(' opt_routine_param_with_default_list ')'
  4672    opt_create_routine_opt_list opt_routine_body
  4673    {
  4674      name := $4.unresolvedObjectName().ToRoutineName()
  4675      $$.val = &tree.CreateRoutine{
  4676        IsProcedure: true,
  4677        Replace: $2.bool(),
  4678        Name: name,
  4679        Params: $6.routineParams(),
  4680        Options: $8.routineOptions(),
  4681        RoutineBody: $9.routineBody(),
  4682        ReturnType: tree.RoutineReturnType{
  4683          Type: types.Void,
  4684        },
  4685      }
  4686    }
  4687  | CREATE opt_or_replace PROCEDURE error // SHOW HELP: CREATE PROCEDURE
  4688  
  4689  opt_or_replace:
  4690    OR REPLACE { $$.val = true }
  4691  | /* EMPTY */ { $$.val = false }
  4692  
  4693  opt_return_table:
  4694    TABLE { return unimplementedWithIssueDetail(sqllex, 100226, "UDF returning TABLE") }
  4695  | /* EMPTY */ { $$.val = false }
  4696  
  4697  opt_return_set:
  4698    SETOF { $$.val = true}
  4699  | /* EMPTY */ { $$.val = false }
  4700  
  4701  routine_create_name:
  4702    db_object_name
  4703  
  4704  opt_routine_param_with_default_list:
  4705    routine_param_with_default_list { $$.val = $1.routineParams() }
  4706  | /* Empty */ { $$.val = tree.RoutineParams{} }
  4707  
  4708  routine_param_with_default_list:
  4709    routine_param_with_default { $$.val = tree.RoutineParams{$1.routineParam()} }
  4710  | routine_param_with_default_list ',' routine_param_with_default
  4711    {
  4712      $$.val = append($1.routineParams(), $3.routineParam())
  4713    }
  4714  
  4715  routine_param_with_default:
  4716    routine_param
  4717  | routine_param DEFAULT a_expr
  4718    {
  4719      arg := $1.routineParam()
  4720      arg.DefaultVal = $3.expr()
  4721      $$.val = arg
  4722    }
  4723  | routine_param '=' a_expr
  4724    {
  4725      arg := $1.routineParam()
  4726      arg.DefaultVal = $3.expr()
  4727      $$.val = arg
  4728    }
  4729  
  4730  routine_param:
  4731    routine_param_class param_name routine_param_type
  4732    {
  4733      $$.val = tree.RoutineParam{
  4734        Name: tree.Name($2),
  4735        Type: $3.typeReference(),
  4736        Class: $1.routineParamClass(),
  4737      }
  4738    }
  4739  | param_name routine_param_class routine_param_type
  4740    {
  4741      $$.val = tree.RoutineParam{
  4742        Name: tree.Name($1),
  4743        Type: $3.typeReference(),
  4744        Class: $2.routineParamClass(),
  4745      }
  4746    }
  4747  | param_name routine_param_type
  4748    {
  4749      $$.val = tree.RoutineParam{
  4750        Name: tree.Name($1),
  4751        Type: $2.typeReference(),
  4752        Class: tree.RoutineParamIn,
  4753      }
  4754    }
  4755  | routine_param_class routine_param_type
  4756    {
  4757      $$.val = tree.RoutineParam{
  4758        Type: $2.typeReference(),
  4759        Class: $1.routineParamClass(),
  4760      }
  4761    }
  4762  | routine_param_type
  4763    {
  4764      $$.val = tree.RoutineParam{
  4765        Type: $1.typeReference(),
  4766        Class: tree.RoutineParamIn,
  4767      }
  4768    }
  4769  
  4770  routine_param_class:
  4771    IN { $$.val = tree.RoutineParamIn }
  4772  | OUT { return unimplementedWithIssueDetail(sqllex, 100405, "create function with 'OUT' argument class") }
  4773  | INOUT { return unimplementedWithIssueDetail(sqllex, 100405, "create function with 'INOUT' argument class") }
  4774  | IN OUT { return unimplementedWithIssueDetail(sqllex, 100405, "create function with 'IN OUT' argument class") }
  4775  | VARIADIC { return unimplementedWithIssueDetail(sqllex, 88947, "variadic user-defined functions") }
  4776  
  4777  routine_param_type:
  4778    typename
  4779  
  4780  routine_return_type:
  4781    routine_param_type
  4782  
  4783  opt_create_routine_opt_list:
  4784    create_routine_opt_list { $$.val = $1.routineOptions() }
  4785  | /* EMPTY */ { $$.val = tree.RoutineOptions{} }
  4786  
  4787  create_routine_opt_list:
  4788    create_routine_opt_item { $$.val = tree.RoutineOptions{$1.functionOption()} }
  4789  | create_routine_opt_list create_routine_opt_item
  4790    {
  4791      $$.val = append($1.routineOptions(), $2.functionOption())
  4792    }
  4793  
  4794  create_routine_opt_item:
  4795    AS routine_as opt_link_sym
  4796    {
  4797      $$.val = tree.RoutineBodyStr($2)
  4798    }
  4799  | LANGUAGE non_reserved_word_or_sconst
  4800    {
  4801      lang, err := tree.AsRoutineLanguage($2)
  4802      if err != nil {
  4803        return setErr(sqllex, err)
  4804      }
  4805      $$.val = lang
  4806    }
  4807  | TRANSFORM { return unimplemented(sqllex, "create transform function") }
  4808  | WINDOW { return unimplemented(sqllex, "create window function") }
  4809  | common_routine_opt_item
  4810    {
  4811      $$.val = $1.functionOption()
  4812    }
  4813  
  4814  common_routine_opt_item:
  4815    CALLED ON NULL INPUT
  4816    {
  4817      $$.val = tree.RoutineCalledOnNullInput
  4818    }
  4819  | RETURNS NULL ON NULL INPUT
  4820    {
  4821      $$.val = tree.RoutineReturnsNullOnNullInput
  4822    }
  4823  | STRICT
  4824    {
  4825      $$.val = tree.RoutineStrict
  4826    }
  4827  | IMMUTABLE
  4828    {
  4829      $$.val = tree.RoutineImmutable
  4830    }
  4831  | STABLE
  4832    {
  4833      $$.val = tree.RoutineStable
  4834    }
  4835  | VOLATILE
  4836    {
  4837      $$.val = tree.RoutineVolatile
  4838    }
  4839  | EXTERNAL SECURITY DEFINER
  4840    {
  4841      return unimplemented(sqllex, "create function...security")
  4842    }
  4843  | EXTERNAL SECURITY INVOKER
  4844    {
  4845      return unimplemented(sqllex, "create function...security")
  4846    }
  4847  | SECURITY DEFINER
  4848    {
  4849      return unimplemented(sqllex, "create function...security")
  4850    }
  4851  | SECURITY INVOKER
  4852    {
  4853      return unimplemented(sqllex, "create function...security")
  4854    }
  4855  | LEAKPROOF
  4856    {
  4857      $$.val = tree.RoutineLeakproof(true)
  4858    }
  4859  | NOT LEAKPROOF
  4860    {
  4861      $$.val = tree.RoutineLeakproof(false)
  4862    }
  4863  | COST numeric_only
  4864    {
  4865      return unimplemented(sqllex, "create function/procedure ... cost")
  4866    }
  4867  | ROWS numeric_only
  4868    {
  4869      return unimplemented(sqllex, "create function/procedure ... rows")
  4870    }
  4871  | SUPPORT name
  4872    {
  4873      return unimplemented(sqllex, "create function/procedure ... support")
  4874    }
  4875  
  4876  // In theory we should parse the a whole set/reset statement here. But it's fine
  4877  // to just return fast on SET/RESET keyword for now since it's not supported
  4878  // yet.
  4879  | SET { return unimplemented(sqllex, "create function/procedure ... set") }
  4880  | PARALLEL { return unimplemented(sqllex, "create function/procedure ... parallel") }
  4881  
  4882  routine_as:
  4883    SCONST
  4884  
  4885  routine_return_stmt:
  4886    RETURN a_expr
  4887  {
  4888    $$.val = &tree.RoutineReturn{
  4889      ReturnVal: $2.expr(),
  4890    }
  4891  }
  4892  
  4893  routine_body_stmt:
  4894    stmt_without_legacy_transaction
  4895  | routine_return_stmt
  4896  
  4897  routine_body_stmt_list:
  4898    routine_body_stmt_list routine_body_stmt ';'
  4899    {
  4900      $$.val = append($1.stmts(), $2.stmt())
  4901    }
  4902  | /* Empty */
  4903    {
  4904      $$.val = tree.Statements{}
  4905    }
  4906  
  4907  opt_routine_body:
  4908    routine_return_stmt
  4909    {
  4910      $$.val = &tree.RoutineBody{
  4911        Stmts: tree.Statements{$1.stmt()},
  4912      }
  4913    }
  4914  | BEGIN ATOMIC routine_body_stmt_list END
  4915    {
  4916      $$.val = &tree.RoutineBody{
  4917          Stmts: $3.stmts(),
  4918      }
  4919    }
  4920  | /* Empty */
  4921    {
  4922      $$.val = (*tree.RoutineBody)(nil)
  4923    }
  4924  
  4925  opt_link_sym:
  4926    ',' SCONST
  4927    {
  4928    }
  4929  | /* Empty */
  4930    {
  4931    }
  4932  
  4933  // %Help: DROP FUNCTION - remove a function
  4934  // %Category: DDL
  4935  // %Text:
  4936  // DROP FUNCTION [ IF EXISTS ] name [ ( [ [ argmode ] [ argname ] argtype [, ...] ] ) ] [, ...]
  4937  //    [ CASCADE | RESTRICT ]
  4938  // %SeeAlso: WEBDOCS/drop-function.html
  4939  drop_func_stmt:
  4940    DROP FUNCTION function_with_paramtypes_list opt_drop_behavior
  4941    {
  4942      $$.val = &tree.DropRoutine{
  4943        Routines: $3.routineObjs(),
  4944        DropBehavior: $4.dropBehavior(),
  4945      }
  4946    }
  4947  | DROP FUNCTION IF EXISTS function_with_paramtypes_list opt_drop_behavior
  4948    {
  4949      $$.val = &tree.DropRoutine{
  4950        IfExists: true,
  4951        Routines: $5.routineObjs(),
  4952        DropBehavior: $6.dropBehavior(),
  4953      }
  4954    }
  4955  | DROP FUNCTION error // SHOW HELP: DROP FUNCTION
  4956  
  4957  // %Help: DROP PROCEDURE - remove a procedure
  4958  // %Category: DDL
  4959  // %Text:
  4960  // DROP PROCEDURE [ IF EXISTS ] name [ ( [ [ argmode ] [ argname ] argtype [, ...] ] ) ] [, ...]
  4961  //    [ CASCADE | RESTRICT ]
  4962  // %SeeAlso: WEBDOCS/drop-procedure.html
  4963  drop_proc_stmt:
  4964    DROP PROCEDURE function_with_paramtypes_list opt_drop_behavior
  4965    {
  4966      $$.val = &tree.DropRoutine{
  4967        Procedure: true,
  4968        Routines: $3.routineObjs(),
  4969        DropBehavior: $4.dropBehavior(),
  4970      }
  4971    }
  4972  | DROP PROCEDURE IF EXISTS function_with_paramtypes_list opt_drop_behavior
  4973    {
  4974      $$.val = &tree.DropRoutine{
  4975        IfExists: true,
  4976        Procedure: true,
  4977        Routines: $5.routineObjs(),
  4978        DropBehavior: $6.dropBehavior(),
  4979      }
  4980    }
  4981  | DROP PROCEDURE error // SHOW HELP: DROP PROCEDURE
  4982  
  4983  function_with_paramtypes_list:
  4984    function_with_paramtypes
  4985    {
  4986      $$.val = tree.RoutineObjs{$1.functionObj()}
  4987    }
  4988    | function_with_paramtypes_list ',' function_with_paramtypes
  4989    {
  4990      $$.val = append($1.routineObjs(), $3.functionObj())
  4991    }
  4992  
  4993  function_with_paramtypes:
  4994    db_object_name func_params
  4995    {
  4996      $$.val = tree.RoutineObj{
  4997        FuncName: $1.unresolvedObjectName().ToRoutineName(),
  4998        Params: $2.routineParams(),
  4999      }
  5000    }
  5001    | db_object_name
  5002    {
  5003      $$.val = tree.RoutineObj{
  5004        FuncName: $1.unresolvedObjectName().ToRoutineName(),
  5005      }
  5006    }
  5007  
  5008  func_params:
  5009    '(' func_params_list ')'
  5010    {
  5011      $$.val = $2.routineParams()
  5012    }
  5013    | '(' ')'
  5014    {
  5015      $$.val = tree.RoutineParams{}
  5016    }
  5017  
  5018  func_params_list:
  5019    routine_param
  5020    {
  5021      $$.val = tree.RoutineParams{$1.routineParam()}
  5022    }
  5023    | func_params_list ',' routine_param
  5024    {
  5025      $$.val = append($1.routineParams(), $3.routineParam())
  5026    }
  5027  
  5028  alter_func_options_stmt:
  5029    ALTER FUNCTION function_with_paramtypes alter_func_opt_list opt_restrict
  5030    {
  5031      $$.val = &tree.AlterFunctionOptions{
  5032        Function: $3.functionObj(),
  5033        Options: $4.routineOptions(),
  5034      }
  5035    }
  5036  
  5037  alter_func_opt_list:
  5038    common_routine_opt_item
  5039    {
  5040      $$.val = tree.RoutineOptions{$1.functionOption()}
  5041    }
  5042  | alter_func_opt_list common_routine_opt_item
  5043    {
  5044      $$.val = append($1.routineOptions(), $2.functionOption())
  5045    }
  5046  
  5047  opt_restrict:
  5048    RESTRICT {}
  5049  | /* EMPTY */ {}
  5050  
  5051  alter_func_rename_stmt:
  5052    ALTER FUNCTION function_with_paramtypes RENAME TO name
  5053    {
  5054      $$.val = &tree.AlterRoutineRename{
  5055        Function: $3.functionObj(),
  5056        NewName: tree.Name($6),
  5057      }
  5058    }
  5059  
  5060  alter_func_set_schema_stmt:
  5061    ALTER FUNCTION function_with_paramtypes SET SCHEMA schema_name
  5062    {
  5063      $$.val = &tree.AlterRoutineSetSchema{
  5064        Function: $3.functionObj(),
  5065        NewSchemaName: tree.Name($6),
  5066      }
  5067    }
  5068  
  5069  alter_func_owner_stmt:
  5070    ALTER FUNCTION function_with_paramtypes OWNER TO role_spec
  5071    {
  5072      $$.val = &tree.AlterRoutineSetOwner{
  5073        Function: $3.functionObj(),
  5074        NewOwner: $6.roleSpec(),
  5075      }
  5076    }
  5077  
  5078  alter_func_dep_extension_stmt:
  5079    ALTER FUNCTION function_with_paramtypes opt_no DEPENDS ON EXTENSION name
  5080    {
  5081      $$.val = &tree.AlterFunctionDepExtension{
  5082        Function: $3.functionObj(),
  5083        Remove: $4.bool(),
  5084        Extension: tree.Name($8),
  5085      }
  5086    }
  5087  
  5088  alter_proc_rename_stmt:
  5089    ALTER PROCEDURE function_with_paramtypes RENAME TO name
  5090    {
  5091      $$.val = &tree.AlterRoutineRename{
  5092        Function: $3.functionObj(),
  5093        NewName: tree.Name($6),
  5094        Procedure: true,
  5095      }
  5096    }
  5097  
  5098  alter_proc_set_schema_stmt:
  5099    ALTER PROCEDURE function_with_paramtypes SET SCHEMA schema_name
  5100    {
  5101      $$.val = &tree.AlterRoutineSetSchema{
  5102        Function: $3.functionObj(),
  5103        NewSchemaName: tree.Name($6),
  5104        Procedure: true,
  5105      }
  5106    }
  5107  
  5108  alter_proc_owner_stmt:
  5109    ALTER PROCEDURE function_with_paramtypes OWNER TO role_spec
  5110    {
  5111      $$.val = &tree.AlterRoutineSetOwner{
  5112        Function: $3.functionObj(),
  5113        NewOwner: $6.roleSpec(),
  5114        Procedure: true,
  5115      }
  5116    }
  5117  
  5118  opt_no:
  5119    NO
  5120    {
  5121      $$.val = true
  5122    }
  5123  | /* EMPTY */
  5124    {
  5125      $$.val = false
  5126    }
  5127  
  5128  create_unsupported:
  5129    CREATE ACCESS METHOD error { return unimplemented(sqllex, "create access method") }
  5130  | CREATE AGGREGATE error { return unimplementedWithIssueDetail(sqllex, 74775, "create aggregate") }
  5131  | CREATE CAST error { return unimplemented(sqllex, "create cast") }
  5132  | CREATE CONSTRAINT TRIGGER error { return unimplementedWithIssueDetail(sqllex, 28296, "create constraint") }
  5133  | CREATE CONVERSION error { return unimplemented(sqllex, "create conversion") }
  5134  | CREATE DEFAULT CONVERSION error { return unimplemented(sqllex, "create def conv") }
  5135  | CREATE FOREIGN TABLE error { return unimplemented(sqllex, "create foreign table") }
  5136  | CREATE FOREIGN DATA error { return unimplemented(sqllex, "create fdw") }
  5137  | CREATE opt_or_replace opt_trusted opt_procedural LANGUAGE name error { return unimplementedWithIssueDetail(sqllex, 17511, "create language " + $6) }
  5138  | CREATE OPERATOR error { return unimplementedWithIssue(sqllex, 65017) }
  5139  | CREATE PUBLICATION error { return unimplemented(sqllex, "create publication") }
  5140  | CREATE opt_or_replace RULE error { return unimplemented(sqllex, "create rule") }
  5141  | CREATE SERVER error { return unimplemented(sqllex, "create server") }
  5142  | CREATE SUBSCRIPTION error { return unimplemented(sqllex, "create subscription") }
  5143  | CREATE TABLESPACE error { return unimplementedWithIssueDetail(sqllex, 54113, "create tablespace") }
  5144  | CREATE TEXT error { return unimplementedWithIssueDetail(sqllex, 7821, "create text") }
  5145  | CREATE TRIGGER error { return unimplementedWithIssueDetail(sqllex, 28296, "create trigger") }
  5146  
  5147  opt_trusted:
  5148    TRUSTED {}
  5149  | /* EMPTY */ {}
  5150  
  5151  opt_procedural:
  5152    PROCEDURAL {}
  5153  | /* EMPTY */ {}
  5154  
  5155  drop_unsupported:
  5156    DROP ACCESS METHOD error { return unimplemented(sqllex, "drop access method") }
  5157  | DROP AGGREGATE error { return unimplementedWithIssueDetail(sqllex, 74775, "drop aggregate") }
  5158  | DROP CAST error { return unimplemented(sqllex, "drop cast") }
  5159  | DROP COLLATION error { return unimplemented(sqllex, "drop collation") }
  5160  | DROP CONVERSION error { return unimplemented(sqllex, "drop conversion") }
  5161  | DROP DOMAIN error { return unimplementedWithIssueDetail(sqllex, 27796, "drop") }
  5162  | DROP EXTENSION IF EXISTS name error { return unimplementedWithIssueDetail(sqllex, 74777, "drop extension if exists") }
  5163  | DROP EXTENSION name error { return unimplementedWithIssueDetail(sqllex, 74777, "drop extension") }
  5164  | DROP FOREIGN TABLE error { return unimplemented(sqllex, "drop foreign table") }
  5165  | DROP FOREIGN DATA error { return unimplemented(sqllex, "drop fdw") }
  5166  | DROP opt_procedural LANGUAGE name error { return unimplementedWithIssueDetail(sqllex, 17511, "drop language " + $4) }
  5167  | DROP OPERATOR error { return unimplemented(sqllex, "drop operator") }
  5168  | DROP PUBLICATION error { return unimplemented(sqllex, "drop publication") }
  5169  | DROP RULE error { return unimplemented(sqllex, "drop rule") }
  5170  | DROP SERVER error { return unimplemented(sqllex, "drop server") }
  5171  | DROP SUBSCRIPTION error { return unimplemented(sqllex, "drop subscription") }
  5172  | DROP TEXT error { return unimplementedWithIssueDetail(sqllex, 7821, "drop text") }
  5173  | DROP TRIGGER error { return unimplementedWithIssueDetail(sqllex, 28296, "drop") }
  5174  
  5175  create_ddl_stmt:
  5176    create_database_stmt // EXTEND WITH HELP: CREATE DATABASE
  5177  | create_index_stmt    // EXTEND WITH HELP: CREATE INDEX
  5178  | create_schema_stmt   // EXTEND WITH HELP: CREATE SCHEMA
  5179  | create_table_stmt    // EXTEND WITH HELP: CREATE TABLE
  5180  | create_table_as_stmt // EXTEND WITH HELP: CREATE TABLE
  5181  // Error case for both CREATE TABLE and CREATE TABLE ... AS in one
  5182  | CREATE opt_persistence_temp_table TABLE error   // SHOW HELP: CREATE TABLE
  5183  | create_type_stmt     // EXTEND WITH HELP: CREATE TYPE
  5184  | create_view_stmt     // EXTEND WITH HELP: CREATE VIEW
  5185  | create_sequence_stmt // EXTEND WITH HELP: CREATE SEQUENCE
  5186  | create_func_stmt     // EXTEND WITH HELP: CREATE FUNCTION
  5187  | create_proc_stmt     // EXTEND WITH HELP: CREATE PROCEDURE
  5188  
  5189  // %Help: CREATE STATISTICS - create a new table statistic
  5190  // %Category: Misc
  5191  // %Text:
  5192  // CREATE STATISTICS <statisticname>
  5193  //   [ON <colname> [, ...]]
  5194  //   FROM <tablename> [AS OF SYSTEM TIME <expr>]
  5195  create_stats_stmt:
  5196    CREATE STATISTICS statistics_name opt_stats_columns FROM create_stats_target opt_create_stats_options
  5197    {
  5198      $$.val = &tree.CreateStats{
  5199        Name: tree.Name($3),
  5200        ColumnNames: $4.nameList(),
  5201        Table: $6.tblExpr(),
  5202        Options: *$7.createStatsOptions(),
  5203      }
  5204    }
  5205  | CREATE STATISTICS error // SHOW HELP: CREATE STATISTICS
  5206  
  5207  opt_stats_columns:
  5208    ON name_list
  5209    {
  5210      $$.val = $2.nameList()
  5211    }
  5212  | /* EMPTY */
  5213    {
  5214      $$.val = tree.NameList(nil)
  5215    }
  5216  
  5217  create_stats_target:
  5218    table_name
  5219    {
  5220      $$.val = $1.unresolvedObjectName()
  5221    }
  5222  | '[' iconst64 ']'
  5223    {
  5224      /* SKIP DOC */
  5225      $$.val = &tree.TableRef{
  5226        TableID: $2.int64(),
  5227      }
  5228    }
  5229  
  5230  opt_create_stats_options:
  5231    create_stats_option_list
  5232    {
  5233      $$.val = $1.createStatsOptions()
  5234    }
  5235  | WITH OPTIONS create_stats_option_list
  5236    {
  5237      $$.val = $3.createStatsOptions()
  5238    }
  5239  | /* EMPTY */
  5240    {
  5241      $$.val = &tree.CreateStatsOptions{}
  5242    }
  5243  
  5244  create_stats_option_list:
  5245    create_stats_option
  5246    {
  5247      $$.val = $1.createStatsOptions()
  5248    }
  5249  | create_stats_option_list create_stats_option
  5250    {
  5251      a := $1.createStatsOptions()
  5252      b := $2.createStatsOptions()
  5253      if err := a.CombineWith(b); err != nil {
  5254        return setErr(sqllex, err)
  5255      }
  5256      $$.val = a
  5257    }
  5258  
  5259  create_stats_option:
  5260    THROTTLING FCONST
  5261    {
  5262      /* SKIP DOC */
  5263      value, _ := constant.Float64Val($2.numVal().AsConstantValue())
  5264      if value < 0.0 || value >= 1.0 {
  5265        sqllex.Error("THROTTLING fraction must be between 0 and 1")
  5266        return 1
  5267      }
  5268      $$.val = &tree.CreateStatsOptions{
  5269        Throttling: value,
  5270      }
  5271    }
  5272  | as_of_clause
  5273    {
  5274      $$.val = &tree.CreateStatsOptions{
  5275        AsOf: $1.asOfClause(),
  5276      }
  5277    }
  5278  | USING EXTREMES
  5279    {
  5280      $$.val = &tree.CreateStatsOptions{
  5281        UsingExtremes: true,
  5282      }
  5283    }
  5284  | where_clause
  5285    {
  5286      $$.val = &tree.CreateStatsOptions{
  5287        Where: tree.NewWhere(tree.AstWhere, $1.expr()),
  5288      }
  5289    }
  5290  
  5291  // %Help: CREATE CHANGEFEED  - create change data capture
  5292  // %Category: CCL
  5293  // %Text:
  5294  // CREATE CHANGEFEED
  5295  // FOR <targets> [INTO sink] [WITH <options>]
  5296  //
  5297  // sink: data capture stream destination (Enterprise only)
  5298  create_changefeed_stmt:
  5299    CREATE CHANGEFEED FOR changefeed_targets opt_changefeed_sink opt_with_options
  5300    {
  5301      $$.val = &tree.CreateChangefeed{
  5302        Targets: $4.changefeedTargets(),
  5303        SinkURI: $5.expr(),
  5304        Options: $6.kvOptions(),
  5305      }
  5306    }
  5307  | CREATE CHANGEFEED /*$3=*/ opt_changefeed_sink /*$4=*/ opt_with_options
  5308    AS SELECT /*$7=*/target_list FROM /*$9=*/changefeed_target_expr /*$10=*/opt_where_clause
  5309    {
  5310      target, err := tree.ChangefeedTargetFromTableExpr($9.tblExpr())
  5311      if err != nil {
  5312        return setErr(sqllex, err)
  5313      }
  5314  
  5315      $$.val = &tree.CreateChangefeed{
  5316        SinkURI: $3.expr(),
  5317        Options: $4.kvOptions(),
  5318        Targets: tree.ChangefeedTargets{target},
  5319        Select:  &tree.SelectClause{
  5320           Exprs: $7.selExprs(),
  5321           From:  tree.From{Tables: tree.TableExprs{$9.tblExpr()}},
  5322           Where: tree.NewWhere(tree.AstWhere, $10.expr()),
  5323        },
  5324      }
  5325    }
  5326  | EXPERIMENTAL CHANGEFEED FOR changefeed_targets opt_with_options
  5327    {
  5328      /* SKIP DOC */
  5329      $$.val = &tree.CreateChangefeed{
  5330        Targets: $4.changefeedTargets(),
  5331        Options: $5.kvOptions(),
  5332      }
  5333    }
  5334  
  5335  // %Help: CREATE SCHEDULE FOR CHANGEFEED - create changefeed periodically
  5336  // %Category: CCL
  5337  // %Text:
  5338  // CREATE SCHEDULE [IF NOT EXISTS]
  5339  // [<description>]
  5340  // FOR CHANGEFEED
  5341  // <targets> INTO <sink> [WITH <options>]
  5342  // RECURRING [crontab|NEVER]
  5343  // [WITH EXPERIMENTAL SCHEDULE OPTIONS <schedule_option>[= <value>] [, ...] ]
  5344  //
  5345  // All changefeeds run in UTC timezone.
  5346  //
  5347  // Description:
  5348  //   Optional description (or name) for this schedule
  5349  //
  5350  // RECURRING <crontab>:
  5351  //   The RECURRING expression specifies when export runs
  5352  //   Schedule specified as a string in crontab format.
  5353  //   All times in UTC.
  5354  //     "5 0 * * *": run schedule 5 minutes past midnight.
  5355  //     "@daily": run daily, at midnight
  5356  //   See https://en.wikipedia.org/wiki/Cron
  5357  //
  5358  // sink: data capture stream destination (Enterprise only)
  5359  // %SeeAlso: CREATE CHANGEFEED
  5360  create_schedule_for_changefeed_stmt:
  5361    CREATE SCHEDULE /*$3=*/schedule_label_spec FOR CHANGEFEED
  5362    /* $6=*/changefeed_targets /*$7=*/changefeed_sink
  5363    /*$8=*/opt_with_options /*$9=*/cron_expr /*$10=*/opt_with_schedule_options
  5364    {
  5365       $$.val = &tree.ScheduledChangefeed{
  5366          CreateChangefeed:   &tree.CreateChangefeed{
  5367            Targets:    $6.changefeedTargets(),
  5368            SinkURI:    $7.expr(),
  5369            Options:    $8.kvOptions(),
  5370          },
  5371          ScheduleLabelSpec:  *($3.scheduleLabelSpec()),
  5372          Recurrence:         $9.expr(),
  5373  				ScheduleOptions:    $10.kvOptions(),
  5374       }
  5375    }
  5376  | CREATE SCHEDULE /*$3=*/schedule_label_spec FOR CHANGEFEED /*$6=*/changefeed_sink
  5377    /*$7=*/opt_with_options AS SELECT /*$10=*/target_list FROM /*$12=*/changefeed_target_expr /*$13=*/opt_where_clause
  5378    /*$14=*/cron_expr /*$15=*/opt_with_schedule_options
  5379    {
  5380      target, err := tree.ChangefeedTargetFromTableExpr($12.tblExpr())
  5381      if err != nil {
  5382        return setErr(sqllex, err)
  5383      }
  5384  
  5385      createChangefeedNode := &tree.CreateChangefeed{
  5386        SinkURI: $6.expr(),
  5387        Options: $7.kvOptions(),
  5388        Targets: tree.ChangefeedTargets{target},
  5389        Select:  &tree.SelectClause{
  5390           Exprs: $10.selExprs(),
  5391           From:  tree.From{Tables: tree.TableExprs{$12.tblExpr()}},
  5392           Where: tree.NewWhere(tree.AstWhere, $13.expr()),
  5393        },
  5394      }
  5395  
  5396      $$.val = &tree.ScheduledChangefeed{
  5397  			CreateChangefeed:  	createChangefeedNode,
  5398  			ScheduleLabelSpec:  *($3.scheduleLabelSpec()),
  5399  			Recurrence:         $14.expr(),
  5400  			ScheduleOptions:    $15.kvOptions(),
  5401  	 }
  5402    }
  5403   | CREATE SCHEDULE schedule_label_spec FOR CHANGEFEED error  // SHOW HELP: CREATE SCHEDULE FOR CHANGEFEED
  5404  
  5405  changefeed_targets:
  5406    changefeed_target
  5407    {
  5408      $$.val = tree.ChangefeedTargets{$1.changefeedTarget()}
  5409    }
  5410  | changefeed_targets ',' changefeed_target
  5411    {
  5412      $$.val = append($1.changefeedTargets(), $3.changefeedTarget())
  5413    }
  5414  
  5415  changefeed_target:
  5416    opt_table_prefix table_name opt_changefeed_family
  5417    {
  5418      $$.val = tree.ChangefeedTarget{
  5419        TableName:  $2.unresolvedObjectName().ToUnresolvedName(),
  5420        FamilyName: tree.Name($3),
  5421      }
  5422    }
  5423  
  5424  changefeed_target_expr: insert_target
  5425  
  5426  opt_table_prefix:
  5427    TABLE
  5428    {}
  5429  | /* EMPTY */
  5430    {}
  5431  
  5432  opt_changefeed_family:
  5433    FAMILY family_name
  5434    {
  5435      $$ = $2
  5436    }
  5437  | /* EMPTY */
  5438    {
  5439      $$ = ""
  5440    }
  5441  
  5442  opt_changefeed_sink:
  5443    INTO string_or_placeholder
  5444    {
  5445      $$.val = $2.expr()
  5446    }
  5447  | /* EMPTY */
  5448    {
  5449      /* SKIP DOC */
  5450      $$.val = nil
  5451    }
  5452  
  5453  changefeed_sink:
  5454    INTO string_or_placeholder
  5455    {
  5456      $$.val = $2.expr()
  5457    }
  5458  // %Help: DELETE - delete rows from a table
  5459  // %Category: DML
  5460  // %Text:
  5461  // DELETE
  5462  //    [BATCH [SIZE <expr>]]
  5463  //    FROM <tablename>
  5464  //    [WHERE <expr>]
  5465  //    [ORDER BY <exprs...>]
  5466  //    [USING <exprs...>]
  5467  //    [LIMIT <expr>]
  5468  //    [RETURNING <exprs...>]
  5469  // %SeeAlso: WEBDOCS/delete.html
  5470  delete_stmt:
  5471    opt_with_clause DELETE opt_batch_clause FROM table_expr_opt_alias_idx opt_using_clause opt_where_clause opt_sort_clause opt_limit_clause returning_clause
  5472    {
  5473      $$.val = &tree.Delete{
  5474        With: $1.with(),
  5475        Batch: $3.batch(),
  5476        Table: $5.tblExpr(),
  5477        Using: $6.tblExprs(),
  5478        Where: tree.NewWhere(tree.AstWhere, $7.expr()),
  5479        OrderBy: $8.orderBy(),
  5480        Limit: $9.limit(),
  5481        Returning: $10.retClause(),
  5482      }
  5483    }
  5484  | opt_with_clause DELETE error // SHOW HELP: DELETE
  5485  
  5486  opt_batch_clause:
  5487    BATCH
  5488    {
  5489      $$.val = &tree.Batch{}
  5490    }
  5491  | BATCH '(' batch_param_list ')'
  5492    {
  5493      $$.val = &tree.Batch{Params: $3.batchParams()}
  5494    }
  5495  | /* EMPTY */
  5496    {
  5497      $$.val = (*tree.Batch)(nil)
  5498    }
  5499  
  5500  batch_param_list:
  5501    batch_param
  5502    {
  5503      $$.val = []tree.BatchParam{$1.batchParam()}
  5504    }
  5505  | batch_param_list ',' batch_param
  5506    {
  5507      $$.val = append($1.batchParams(), $3.batchParam())
  5508    }
  5509  
  5510  batch_param:
  5511    SIZE a_expr
  5512    {
  5513      $$.val = &tree.SizeBatchParam{Size: $2.expr()}
  5514    }
  5515  
  5516  opt_using_clause:
  5517    USING from_list
  5518    {
  5519      $$.val = $2.tblExprs()
  5520    }
  5521  | /* EMPTY */
  5522    {
  5523      $$.val = tree.TableExprs{}
  5524    }
  5525  
  5526  
  5527  // %Help: DISCARD - reset the session to its initial state
  5528  // %Category: Cfg
  5529  // %Text: DISCARD ALL
  5530  discard_stmt:
  5531    DISCARD ALL
  5532    {
  5533      $$.val = &tree.Discard{Mode: tree.DiscardModeAll}
  5534    }
  5535  | DISCARD PLANS { return unimplemented(sqllex, "discard plans") }
  5536  | DISCARD SEQUENCES
  5537    {
  5538      $$.val = &tree.Discard{Mode: tree.DiscardModeSequences}
  5539    }
  5540  | DISCARD TEMP
  5541    {
  5542      $$.val = &tree.Discard{Mode: tree.DiscardModeTemp}
  5543    }
  5544  | DISCARD TEMPORARY
  5545    {
  5546      $$.val = &tree.Discard{Mode: tree.DiscardModeTemp}
  5547    }
  5548  | DISCARD error // SHOW HELP: DISCARD
  5549  
  5550  // %Help: DROP
  5551  // %Category: Group
  5552  // %Text:
  5553  // DROP DATABASE, DROP INDEX, DROP TABLE, DROP VIEW, DROP SEQUENCE,
  5554  // DROP USER, DROP ROLE, DROP TYPE
  5555  drop_stmt:
  5556    drop_ddl_stmt                 // help texts in sub-rule
  5557  | drop_role_stmt                // EXTEND WITH HELP: DROP ROLE
  5558  | drop_schedule_stmt            // EXTEND WITH HELP: DROP SCHEDULES
  5559  | drop_external_connection_stmt // EXTEND WITH HELP: DROP EXTERNAL CONNECTION
  5560  | drop_virtual_cluster_stmt     // EXTEND WITH HELP: DROP VIRTUAL CLUSTER
  5561  | drop_unsupported   {}
  5562  | DROP error                    // SHOW HELP: DROP
  5563  
  5564  drop_ddl_stmt:
  5565    drop_database_stmt // EXTEND WITH HELP: DROP DATABASE
  5566  | drop_index_stmt    // EXTEND WITH HELP: DROP INDEX
  5567  | drop_table_stmt    // EXTEND WITH HELP: DROP TABLE
  5568  | drop_view_stmt     // EXTEND WITH HELP: DROP VIEW
  5569  | drop_sequence_stmt // EXTEND WITH HELP: DROP SEQUENCE
  5570  | drop_schema_stmt   // EXTEND WITH HELP: DROP SCHEMA
  5571  | drop_type_stmt     // EXTEND WITH HELP: DROP TYPE
  5572  | drop_func_stmt     // EXTEND WITH HELP: DROP FUNCTION
  5573  | drop_proc_stmt     // EXTEND WITH HELP: DROP FUNCTION
  5574  
  5575  // %Help: DROP VIEW - remove a view
  5576  // %Category: DDL
  5577  // %Text: DROP [MATERIALIZED] VIEW [IF EXISTS] <tablename> [, ...] [CASCADE | RESTRICT]
  5578  // %SeeAlso: WEBDOCS/drop-index.html
  5579  drop_view_stmt:
  5580    DROP VIEW view_name_list opt_drop_behavior
  5581    {
  5582      $$.val = &tree.DropView{Names: $3.tableNames(), IfExists: false, DropBehavior: $4.dropBehavior()}
  5583    }
  5584  | DROP VIEW IF EXISTS view_name_list opt_drop_behavior
  5585    {
  5586      $$.val = &tree.DropView{Names: $5.tableNames(), IfExists: true, DropBehavior: $6.dropBehavior()}
  5587    }
  5588  | DROP MATERIALIZED VIEW view_name_list opt_drop_behavior
  5589    {
  5590      $$.val = &tree.DropView{
  5591        Names: $4.tableNames(),
  5592        IfExists: false,
  5593        DropBehavior: $5.dropBehavior(),
  5594        IsMaterialized: true,
  5595      }
  5596    }
  5597  | DROP MATERIALIZED VIEW IF EXISTS view_name_list opt_drop_behavior
  5598    {
  5599      $$.val = &tree.DropView{
  5600        Names: $6.tableNames(),
  5601        IfExists: true,
  5602        DropBehavior: $7.dropBehavior(),
  5603        IsMaterialized: true,
  5604      }
  5605    }
  5606  | DROP VIEW error // SHOW HELP: DROP VIEW
  5607  
  5608  // %Help: DROP SEQUENCE - remove a sequence
  5609  // %Category: DDL
  5610  // %Text: DROP SEQUENCE [IF EXISTS] <sequenceName> [, ...] [CASCADE | RESTRICT]
  5611  // %SeeAlso: DROP
  5612  drop_sequence_stmt:
  5613    DROP SEQUENCE sequence_name_list opt_drop_behavior
  5614    {
  5615      $$.val = &tree.DropSequence{Names: $3.tableNames(), IfExists: false, DropBehavior: $4.dropBehavior()}
  5616    }
  5617  | DROP SEQUENCE IF EXISTS sequence_name_list opt_drop_behavior
  5618    {
  5619      $$.val = &tree.DropSequence{Names: $5.tableNames(), IfExists: true, DropBehavior: $6.dropBehavior()}
  5620    }
  5621  | DROP SEQUENCE error // SHOW HELP: DROP VIEW
  5622  
  5623  // %Help: DROP TABLE - remove a table
  5624  // %Category: DDL
  5625  // %Text: DROP TABLE [IF EXISTS] <tablename> [, ...] [CASCADE | RESTRICT]
  5626  // %SeeAlso: WEBDOCS/drop-table.html
  5627  drop_table_stmt:
  5628    DROP TABLE table_name_list opt_drop_behavior
  5629    {
  5630      $$.val = &tree.DropTable{Names: $3.tableNames(), IfExists: false, DropBehavior: $4.dropBehavior()}
  5631    }
  5632  | DROP TABLE IF EXISTS table_name_list opt_drop_behavior
  5633    {
  5634      $$.val = &tree.DropTable{Names: $5.tableNames(), IfExists: true, DropBehavior: $6.dropBehavior()}
  5635    }
  5636  | DROP TABLE error // SHOW HELP: DROP TABLE
  5637  
  5638  // %Help: DROP INDEX - remove an index
  5639  // %Category: DDL
  5640  // %Text: DROP INDEX [CONCURRENTLY] [IF EXISTS] <idxname> [, ...] [CASCADE | RESTRICT]
  5641  // %SeeAlso: WEBDOCS/drop-index.html
  5642  drop_index_stmt:
  5643    DROP INDEX opt_concurrently table_index_name_list opt_drop_behavior
  5644    {
  5645      $$.val = &tree.DropIndex{
  5646        IndexList: $4.newTableIndexNames(),
  5647        IfExists: false,
  5648        DropBehavior: $5.dropBehavior(),
  5649        Concurrently: $3.bool(),
  5650      }
  5651    }
  5652  | DROP INDEX opt_concurrently IF EXISTS table_index_name_list opt_drop_behavior
  5653    {
  5654      $$.val = &tree.DropIndex{
  5655        IndexList: $6.newTableIndexNames(),
  5656        IfExists: true,
  5657        DropBehavior: $7.dropBehavior(),
  5658        Concurrently: $3.bool(),
  5659      }
  5660    }
  5661  | DROP INDEX error // SHOW HELP: DROP INDEX
  5662  
  5663  // %Help: DROP DATABASE - remove a database
  5664  // %Category: DDL
  5665  // %Text: DROP DATABASE [IF EXISTS] <databasename> [CASCADE | RESTRICT]
  5666  // %SeeAlso: WEBDOCS/drop-database.html
  5667  drop_database_stmt:
  5668    DROP DATABASE database_name opt_drop_behavior
  5669    {
  5670      $$.val = &tree.DropDatabase{
  5671        Name: tree.Name($3),
  5672        IfExists: false,
  5673        DropBehavior: $4.dropBehavior(),
  5674      }
  5675    }
  5676  | DROP DATABASE IF EXISTS database_name opt_drop_behavior
  5677    {
  5678      $$.val = &tree.DropDatabase{
  5679        Name: tree.Name($5),
  5680        IfExists: true,
  5681        DropBehavior: $6.dropBehavior(),
  5682      }
  5683    }
  5684  | DROP DATABASE error // SHOW HELP: DROP DATABASE
  5685  
  5686  // %Help: DROP TYPE - remove a type
  5687  // %Category: DDL
  5688  // %Text: DROP TYPE [IF EXISTS] <type_name> [, ...] [CASCASE | RESTRICT]
  5689  drop_type_stmt:
  5690    DROP TYPE type_name_list opt_drop_behavior
  5691    {
  5692      $$.val = &tree.DropType{
  5693        Names: $3.unresolvedObjectNames(),
  5694        IfExists: false,
  5695        DropBehavior: $4.dropBehavior(),
  5696      }
  5697    }
  5698  | DROP TYPE IF EXISTS type_name_list opt_drop_behavior
  5699    {
  5700      $$.val = &tree.DropType{
  5701        Names: $5.unresolvedObjectNames(),
  5702        IfExists: true,
  5703        DropBehavior: $6.dropBehavior(),
  5704      }
  5705    }
  5706  | DROP TYPE error // SHOW HELP: DROP TYPE
  5707  
  5708  // %Help: DROP VIRTUAL CLUSTER - remove a virtual cluster
  5709  // %Category: Experimental
  5710  // %Text: DROP VIRTUAL CLUSTER [IF EXISTS] <virtual_cluster_spec> [IMMEDIATE]
  5711  drop_virtual_cluster_stmt:
  5712    DROP virtual_cluster virtual_cluster_spec opt_immediate
  5713    {
  5714     /* SKIP DOC */
  5715     $$.val = &tree.DropTenant{
  5716        TenantSpec: $3.tenantSpec(),
  5717        IfExists: false,
  5718        Immediate: $4.bool(),
  5719      }
  5720    }
  5721  | DROP virtual_cluster IF EXISTS virtual_cluster_spec opt_immediate
  5722    {
  5723      /* SKIP DOC */
  5724      $$.val = &tree.DropTenant{
  5725        TenantSpec: $5.tenantSpec(),
  5726        IfExists: true,
  5727        Immediate: $6.bool(),
  5728      }
  5729    }
  5730  | DROP virtual_cluster error // SHOW HELP: DROP VIRTUAL CLUSTER
  5731  
  5732  opt_immediate:
  5733    /* EMPTY */
  5734    { $$.val = false }
  5735  | IMMEDIATE
  5736    { $$.val = true }
  5737  
  5738  target_types:
  5739    type_name_list
  5740    {
  5741      $$.val = tree.GrantTargetList{Types: $1.unresolvedObjectNames()}
  5742    }
  5743  
  5744  type_name_list:
  5745    type_name
  5746    {
  5747      $$.val = []*tree.UnresolvedObjectName{$1.unresolvedObjectName()}
  5748    }
  5749  | type_name_list ',' type_name
  5750    {
  5751      $$.val = append($1.unresolvedObjectNames(), $3.unresolvedObjectName())
  5752    }
  5753  
  5754  // %Help: DROP SCHEMA - remove a schema
  5755  // %Category: DDL
  5756  // %Text: DROP SCHEMA [IF EXISTS] <schema_name> [, ...] [CASCADE | RESTRICT]
  5757  drop_schema_stmt:
  5758    DROP SCHEMA schema_name_list opt_drop_behavior
  5759    {
  5760      $$.val = &tree.DropSchema{
  5761        Names: $3.objectNamePrefixList(),
  5762        IfExists: false,
  5763        DropBehavior: $4.dropBehavior(),
  5764      }
  5765    }
  5766  | DROP SCHEMA IF EXISTS schema_name_list opt_drop_behavior
  5767    {
  5768      $$.val = &tree.DropSchema{
  5769        Names: $5.objectNamePrefixList(),
  5770        IfExists: true,
  5771        DropBehavior: $6.dropBehavior(),
  5772      }
  5773    }
  5774  | DROP SCHEMA error // SHOW HELP: DROP SCHEMA
  5775  
  5776  // %Help: DROP ROLE - remove a user
  5777  // %Category: Priv
  5778  // %Text: DROP ROLE [IF EXISTS] <user> [, ...]
  5779  // %SeeAlso: CREATE ROLE, SHOW ROLE
  5780  drop_role_stmt:
  5781    DROP role_or_group_or_user role_spec_list
  5782    {
  5783      $$.val = &tree.DropRole{Names: $3.roleSpecList(), IfExists: false, IsRole: $2.bool()}
  5784    }
  5785  | DROP role_or_group_or_user IF EXISTS role_spec_list
  5786    {
  5787      $$.val = &tree.DropRole{Names: $5.roleSpecList(), IfExists: true, IsRole: $2.bool()}
  5788    }
  5789  | DROP role_or_group_or_user error // SHOW HELP: DROP ROLE
  5790  
  5791  db_object_name_list:
  5792    db_object_name
  5793    {
  5794      name := $1.unresolvedObjectName().ToTableName()
  5795      $$.val = tree.TableNames{name}
  5796    }
  5797  | db_object_name_list ',' db_object_name
  5798    {
  5799      name := $3.unresolvedObjectName().ToTableName()
  5800      $$.val = append($1.tableNames(), name)
  5801    }
  5802  
  5803  table_name_list:
  5804    db_object_name_list
  5805  
  5806  sequence_name_list:
  5807    db_object_name_list
  5808  
  5809  view_name_list:
  5810    db_object_name_list
  5811  
  5812  // %Help: ANALYZE - collect table statistics
  5813  // %Category: Misc
  5814  // %Text:
  5815  // ANALYZE <tablename>
  5816  //
  5817  // %SeeAlso: CREATE STATISTICS
  5818  analyze_stmt:
  5819    ANALYZE analyze_target
  5820    {
  5821      $$.val = &tree.Analyze{
  5822        Table: $2.tblExpr(),
  5823      }
  5824    }
  5825  | ANALYZE error // SHOW HELP: ANALYZE
  5826  | ANALYSE analyze_target
  5827    {
  5828      $$.val = &tree.Analyze{
  5829        Table: $2.tblExpr(),
  5830      }
  5831    }
  5832  | ANALYSE error // SHOW HELP: ANALYZE
  5833  
  5834  analyze_target:
  5835    table_name
  5836    {
  5837      $$.val = $1.unresolvedObjectName()
  5838    }
  5839  
  5840  // %Help: EXPLAIN - show the logical plan of a query
  5841  // %Category: Misc
  5842  // %Text:
  5843  // EXPLAIN <statement>
  5844  // EXPLAIN ([PLAN ,] <planoptions...> ) <statement>
  5845  // EXPLAIN (DISTSQL) <statement>
  5846  // EXPLAIN ANALYZE [(DISTSQL)] <statement>
  5847  // EXPLAIN ANALYZE (PLAN <planoptions...>) <statement>
  5848  //
  5849  // Explainable statements:
  5850  //     SELECT, CREATE, DROP, ALTER, INSERT, UPSERT, UPDATE, DELETE,
  5851  //     SHOW, EXPLAIN
  5852  //
  5853  // Plan options:
  5854  //     TYPES, VERBOSE, OPT
  5855  //
  5856  // %SeeAlso: WEBDOCS/explain.html
  5857  explain_stmt:
  5858    EXPLAIN explainable_stmt
  5859    {
  5860      var err error
  5861      $$.val, err = tree.MakeExplain(nil /* options */, $2.stmt())
  5862      if err != nil {
  5863        return setErr(sqllex, err)
  5864      }
  5865    }
  5866  | EXPLAIN error // SHOW HELP: EXPLAIN
  5867  | EXPLAIN '(' explain_option_list ')' explainable_stmt
  5868    {
  5869      var err error
  5870      $$.val, err = tree.MakeExplain($3.strs(), $5.stmt())
  5871      if err != nil {
  5872        return setErr(sqllex, err)
  5873      }
  5874    }
  5875  | EXPLAIN ANALYZE explainable_stmt
  5876    {
  5877      var err error
  5878      $$.val, err = tree.MakeExplain([]string{"ANALYZE"}, $3.stmt())
  5879      if err != nil {
  5880        return setErr(sqllex, err)
  5881      }
  5882    }
  5883  | EXPLAIN ANALYSE explainable_stmt
  5884    {
  5885      var err error
  5886      $$.val, err = tree.MakeExplain([]string{"ANALYZE"}, $3.stmt())
  5887      if err != nil {
  5888        return setErr(sqllex, err)
  5889      }
  5890    }
  5891  | EXPLAIN ANALYZE '(' explain_option_list ')' explainable_stmt
  5892    {
  5893      var err error
  5894      $$.val, err = tree.MakeExplain(append($4.strs(), "ANALYZE"), $6.stmt())
  5895      if err != nil {
  5896        return setErr(sqllex, err)
  5897      }
  5898    }
  5899  | EXPLAIN ANALYSE '(' explain_option_list ')' explainable_stmt
  5900    {
  5901      var err error
  5902      $$.val, err = tree.MakeExplain(append($4.strs(), "ANALYZE"), $6.stmt())
  5903      if err != nil {
  5904        return setErr(sqllex, err)
  5905      }
  5906    }
  5907  // This second error rule is necessary, because otherwise
  5908  // preparable_stmt also provides "selectclause := '(' error ..." and
  5909  // cause a help text for the select clause, which will be confusing in
  5910  // the context of EXPLAIN.
  5911  | EXPLAIN '(' error // SHOW HELP: EXPLAIN
  5912  
  5913  explainable_stmt:
  5914    preparable_stmt
  5915  | comment_stmt
  5916  | execute_stmt
  5917  | call_stmt
  5918  
  5919  preparable_stmt:
  5920    alter_stmt     // help texts in sub-rule
  5921  | backup_stmt    // EXTEND WITH HELP: BACKUP
  5922  | cancel_stmt    // help texts in sub-rule
  5923  | create_stmt    // help texts in sub-rule
  5924  | delete_stmt    // EXTEND WITH HELP: DELETE
  5925  | drop_stmt      // help texts in sub-rule
  5926  | explain_stmt   // EXTEND WITH HELP: EXPLAIN
  5927  | import_stmt    // EXTEND WITH HELP: IMPORT
  5928  | insert_stmt    // EXTEND WITH HELP: INSERT
  5929  | pause_stmt     // help texts in sub-rule
  5930  | reset_stmt     // help texts in sub-rule
  5931  | restore_stmt   // EXTEND WITH HELP: RESTORE
  5932  | resume_stmt    // help texts in sub-rule
  5933  | export_stmt    // EXTEND WITH HELP: EXPORT
  5934  | scrub_stmt     // help texts in sub-rule
  5935  | select_stmt    // help texts in sub-rule
  5936    {
  5937      $$.val = $1.slct()
  5938    }
  5939  | preparable_set_stmt // help texts in sub-rule
  5940  | show_stmt         // help texts in sub-rule
  5941  | truncate_stmt     // EXTEND WITH HELP: TRUNCATE
  5942  | update_stmt       // EXTEND WITH HELP: UPDATE
  5943  | upsert_stmt       // EXTEND WITH HELP: UPSERT
  5944  
  5945  // These are statements that can be used as a data source using the special
  5946  // syntax with brackets. These are a subset of preparable_stmt.
  5947  row_source_extension_stmt:
  5948    delete_stmt       // EXTEND WITH HELP: DELETE
  5949  | explain_stmt      // EXTEND WITH HELP: EXPLAIN
  5950  | insert_stmt       // EXTEND WITH HELP: INSERT
  5951  | select_stmt       // help texts in sub-rule
  5952    {
  5953      $$.val = $1.slct()
  5954    }
  5955  | show_stmt         // help texts in sub-rule
  5956  | update_stmt       // EXTEND WITH HELP: UPDATE
  5957  | upsert_stmt       // EXTEND WITH HELP: UPSERT
  5958  
  5959  copy_to_stmt:
  5960    delete_stmt       // EXTEND WITH HELP: DELETE
  5961  | insert_stmt       // EXTEND WITH HELP: INSERT
  5962  | select_stmt       // help texts in sub-rule
  5963    {
  5964      $$.val = $1.slct()
  5965    }
  5966  | update_stmt       // EXTEND WITH HELP: UPDATE
  5967  | upsert_stmt       // EXTEND WITH HELP: UPSERT
  5968  
  5969  explain_option_list:
  5970    explain_option_name
  5971    {
  5972      $$.val = []string{$1}
  5973    }
  5974  | explain_option_list ',' explain_option_name
  5975    {
  5976      $$.val = append($1.strs(), $3)
  5977    }
  5978  
  5979  // %Help: ALTER CHANGEFEED - alter an existing changefeed
  5980  // %Category: CCL
  5981  // %Text:
  5982  // ALTER CHANGEFEED <job_id> {{ADD|DROP <targets...>} | SET <options...>}...
  5983  alter_changefeed_stmt:
  5984    ALTER CHANGEFEED a_expr alter_changefeed_cmds
  5985    {
  5986      $$.val = &tree.AlterChangefeed{
  5987        Jobs: $3.expr(),
  5988        Cmds: $4.alterChangefeedCmds(),
  5989      }
  5990    }
  5991  | ALTER CHANGEFEED error // SHOW HELP: ALTER CHANGEFEED
  5992  
  5993  alter_changefeed_cmds:
  5994    alter_changefeed_cmd
  5995    {
  5996      $$.val = tree.AlterChangefeedCmds{$1.alterChangefeedCmd()}
  5997    }
  5998  | alter_changefeed_cmds alter_changefeed_cmd
  5999    {
  6000      $$.val = append($1.alterChangefeedCmds(), $2.alterChangefeedCmd())
  6001    }
  6002  
  6003  alter_changefeed_cmd:
  6004    // ALTER CHANGEFEED <job_id> ADD [TABLE] ...
  6005    ADD changefeed_targets opt_with_options
  6006    {
  6007      $$.val = &tree.AlterChangefeedAddTarget{
  6008        Targets: $2.changefeedTargets(),
  6009        Options: $3.kvOptions(),
  6010      }
  6011    }
  6012    // ALTER CHANGEFEED <job_id> DROP [TABLE] ...
  6013  | DROP changefeed_targets
  6014    {
  6015      $$.val = &tree.AlterChangefeedDropTarget{
  6016        Targets: $2.changefeedTargets(),
  6017      }
  6018    }
  6019  | SET kv_option_list
  6020    {
  6021      $$.val = &tree.AlterChangefeedSetOptions{
  6022        Options: $2.kvOptions(),
  6023      }
  6024    }
  6025  | UNSET name_list
  6026    {
  6027      $$.val = &tree.AlterChangefeedUnsetOptions{
  6028        Options: $2.nameList(),
  6029      }
  6030    }
  6031  
  6032  // %Help: ALTER BACKUP - alter an existing backup's encryption keys
  6033  // %Category: CCL
  6034  // %Text:
  6035  // ALTER BACKUP <location...>
  6036  //        [ ADD NEW_KMS = <kms...> ]
  6037  //        [ WITH OLD_KMS = <kms...> ]
  6038  // Locations:
  6039  //    "[scheme]://[host]/[path to backup]?[parameters]"
  6040  //
  6041  // KMS:
  6042  //    "[kms_provider]://[kms_host]/[master_key_identifier]?[parameters]" : add new kms keys to backup
  6043  alter_backup_stmt:
  6044    ALTER BACKUP string_or_placeholder alter_backup_cmds
  6045    {
  6046      $$.val = &tree.AlterBackup {
  6047        Backup:	$3.expr(),
  6048        Cmds:	$4.alterBackupCmds(),
  6049      }
  6050    }
  6051  | ALTER BACKUP string_or_placeholder IN string_or_placeholder alter_backup_cmds
  6052  	{
  6053      $$.val = &tree.AlterBackup {
  6054        Subdir:	$3.expr(),
  6055        Backup:	$5.expr(),
  6056        Cmds:	$6.alterBackupCmds(),
  6057      }
  6058  	}
  6059  | ALTER BACKUP error // SHOW HELP: ALTER BACKUP
  6060  
  6061  alter_backup_cmds:
  6062  	alter_backup_cmd
  6063  	{
  6064      $$.val = tree.AlterBackupCmds{$1.alterBackupCmd()}
  6065  	}
  6066  |	alter_backup_cmds alter_backup_cmd
  6067  	{
  6068      $$.val = append($1.alterBackupCmds(), $2.alterBackupCmd())
  6069  	}
  6070  
  6071  alter_backup_cmd:
  6072  	ADD backup_kms
  6073  	{
  6074      $$.val = &tree.AlterBackupKMS{
  6075        KMSInfo:	$2.backupKMS(),
  6076      }
  6077  	}
  6078  
  6079  backup_kms:
  6080  	NEW_KMS '=' string_or_placeholder_opt_list WITH OLD_KMS '=' string_or_placeholder_opt_list
  6081  	{
  6082      $$.val = tree.BackupKMS{
  6083        NewKMSURI:	$3.stringOrPlaceholderOptList(),
  6084        OldKMSURI:	$7.stringOrPlaceholderOptList(),
  6085      }
  6086  	}
  6087  
  6088  // %Help: SHOW VIRTUAL CLUSTER - display metadata about virtual clusters
  6089  // %Category: Experimental
  6090  // %Text:
  6091  // SHOW VIRTUAL CLUSTER { <virtual_cluster_spec> | ALL } [ WITH <options> ]
  6092  // SHOW VIRTUAL CLUSTERS                                 [ WITH <options> ]
  6093  //
  6094  // Options:
  6095  //     REPLICATION STATUS
  6096  //     CAPABILITIES
  6097  show_virtual_cluster_stmt:
  6098    SHOW virtual_cluster_spec_opt_all opt_show_virtual_cluster_options
  6099    {
  6100      /* SKIP DOC */
  6101      $$.val = &tree.ShowTenant{
  6102        TenantSpec: $2.tenantSpec(),
  6103        ShowTenantOptions: $3.showTenantOpts(),
  6104      }
  6105    }
  6106  | SHOW virtual_cluster error // SHOW HELP: SHOW VIRTUAL CLUSTER
  6107  
  6108  virtual_cluster_spec_opt_all:
  6109    TENANT_ALL ALL
  6110    {
  6111      /* SKIP DOC */
  6112      $$.val = &tree.TenantSpec{All: true}
  6113    }
  6114  | TENANTS
  6115    {
  6116      /* SKIP DOC */
  6117      $$.val = &tree.TenantSpec{All: true}
  6118    }
  6119  | TENANT virtual_cluster_spec
  6120    {
  6121      /* SKIP DOC */
  6122      $$.val = $2.tenantSpec()
  6123    }
  6124  | VIRTUAL CLUSTER_ALL ALL
  6125    {
  6126      $$.val = &tree.TenantSpec{All: true}
  6127    }
  6128  | VIRTUAL CLUSTERS
  6129    {
  6130      $$.val = &tree.TenantSpec{All: true}
  6131    }
  6132  | VIRTUAL CLUSTER virtual_cluster_spec
  6133    {
  6134      $$.val = $3.tenantSpec()
  6135    }
  6136  
  6137  opt_show_virtual_cluster_options:
  6138    /* EMPTY */
  6139    {
  6140      /* SKIP DOC */
  6141      $$.val = tree.ShowTenantOptions{}
  6142    }
  6143  | WITH show_virtual_cluster_options
  6144    {
  6145      /* SKIP DOC */
  6146      $$.val = $2.showTenantOpts()
  6147    }
  6148  
  6149  show_virtual_cluster_options:
  6150    REPLICATION STATUS
  6151    {
  6152      /* SKIP DOC */
  6153      $$.val = tree.ShowTenantOptions{WithReplication: true}
  6154    }
  6155  | CAPABILITIES
  6156    {
  6157      /* SKIP DOC */
  6158      $$.val = tree.ShowTenantOptions{WithCapabilities: true}
  6159    }
  6160  | show_virtual_cluster_options ',' REPLICATION STATUS
  6161    {
  6162      /* SKIP DOC */
  6163      o := $1.showTenantOpts()
  6164      o.WithReplication = true
  6165      $$.val = o
  6166    }
  6167  | show_virtual_cluster_options ',' CAPABILITIES
  6168    {
  6169      /* SKIP DOC */
  6170      o := $1.showTenantOpts()
  6171      o.WithCapabilities = true
  6172      $$.val = o
  6173    }
  6174  
  6175  // %Help: PREPARE - prepare a statement for later execution
  6176  // %Category: Misc
  6177  // %Text: PREPARE <name> [ ( <types...> ) ] AS <query>
  6178  // %SeeAlso: EXECUTE, DEALLOCATE, DISCARD
  6179  prepare_stmt:
  6180    PREPARE table_alias_name prep_type_clause AS preparable_stmt
  6181    {
  6182      $$.val = &tree.Prepare{
  6183        Name: tree.Name($2),
  6184        Types: $3.typeReferences(),
  6185        Statement: $5.stmt(),
  6186      }
  6187    }
  6188  | PREPARE table_alias_name prep_type_clause AS OPT PLAN SCONST
  6189    {
  6190      /* SKIP DOC */
  6191      $$.val = &tree.Prepare{
  6192        Name: tree.Name($2),
  6193        Types: $3.typeReferences(),
  6194        Statement: &tree.CannedOptPlan{Plan: $7},
  6195      }
  6196    }
  6197  | PREPARE error // SHOW HELP: PREPARE
  6198  
  6199  prep_type_clause:
  6200    '(' type_list ')'
  6201    {
  6202      $$.val = $2.typeReferences();
  6203    }
  6204  | /* EMPTY */
  6205    {
  6206      $$.val = []tree.ResolvableTypeReference(nil)
  6207    }
  6208  
  6209  // %Help: EXECUTE - execute a statement prepared previously
  6210  // %Category: Misc
  6211  // %Text: EXECUTE <name> [ ( <exprs...> ) ]
  6212  // %SeeAlso: PREPARE, DEALLOCATE, DISCARD
  6213  execute_stmt:
  6214    EXECUTE table_alias_name execute_param_clause
  6215    {
  6216      $$.val = &tree.Execute{
  6217        Name: tree.Name($2),
  6218        Params: $3.exprs(),
  6219      }
  6220    }
  6221  | EXECUTE table_alias_name execute_param_clause DISCARD ROWS
  6222    {
  6223      /* SKIP DOC */
  6224      $$.val = &tree.Execute{
  6225        Name: tree.Name($2),
  6226        Params: $3.exprs(),
  6227        DiscardRows: true,
  6228      }
  6229    }
  6230  | EXECUTE error // SHOW HELP: EXECUTE
  6231  
  6232  execute_param_clause:
  6233    '(' expr_list ')'
  6234    {
  6235      $$.val = $2.exprs()
  6236    }
  6237  | /* EMPTY */
  6238    {
  6239      $$.val = tree.Exprs(nil)
  6240    }
  6241  
  6242  // %Help: DEALLOCATE - remove a prepared statement
  6243  // %Category: Misc
  6244  // %Text: DEALLOCATE [PREPARE] { <name> | ALL }
  6245  // %SeeAlso: PREPARE, EXECUTE, DISCARD
  6246  deallocate_stmt:
  6247    DEALLOCATE name
  6248    {
  6249      $$.val = &tree.Deallocate{Name: tree.Name($2)}
  6250    }
  6251  | DEALLOCATE PREPARE name
  6252    {
  6253      $$.val = &tree.Deallocate{Name: tree.Name($3)}
  6254    }
  6255  | DEALLOCATE ALL
  6256    {
  6257      $$.val = &tree.Deallocate{}
  6258    }
  6259  | DEALLOCATE PREPARE ALL
  6260    {
  6261      $$.val = &tree.Deallocate{}
  6262    }
  6263  | DEALLOCATE error // SHOW HELP: DEALLOCATE
  6264  
  6265  // %Help: GRANT - define access privileges and role memberships
  6266  // %Category: Priv
  6267  // %Text:
  6268  // Grant privileges:
  6269  //   GRANT {ALL [PRIVILEGES] | <privileges...> } ON <targets...> TO <grantees...>
  6270  // Grant role membership:
  6271  //   GRANT <roles...> TO <grantees...> [WITH ADMIN OPTION]
  6272  //
  6273  // Privileges:
  6274  //   CREATE, DROP, GRANT, SELECT, INSERT, DELETE, UPDATE, USAGE, EXECUTE
  6275  //
  6276  // Targets:
  6277  //   DATABASE <databasename> [, ...]
  6278  //   [TABLE] [<databasename> .] { <tablename> | * } [, ...]
  6279  //   TYPE <typename> [, <typename>]...
  6280  //   FUNCTION <functionname> [ ( [ [ argmode ] [ argname ] argtype [, ...] ] ) ] [, ...]
  6281  //   SCHEMA [<databasename> .]<schemaname> [, [<databasename> .]<schemaname>]...
  6282  //   ALL TABLES IN SCHEMA schema_name [, ...]
  6283  //
  6284  // %SeeAlso: REVOKE, WEBDOCS/grant.html
  6285  grant_stmt:
  6286    GRANT privileges ON grant_targets TO role_spec_list opt_with_grant_option
  6287    {
  6288      $$.val = &tree.Grant{Privileges: $2.privilegeList(), Grantees: $6.roleSpecList(), Targets: $4.grantTargetList(), WithGrantOption: $7.bool(),}
  6289    }
  6290  | GRANT privilege_list TO role_spec_list
  6291    {
  6292      $$.val = &tree.GrantRole{Roles: $2.nameList(), Members: $4.roleSpecList(), AdminOption: false}
  6293    }
  6294  | GRANT privilege_list TO role_spec_list WITH ADMIN OPTION
  6295    {
  6296      $$.val = &tree.GrantRole{Roles: $2.nameList(), Members: $4.roleSpecList(), AdminOption: true}
  6297    }
  6298  | GRANT privileges ON TYPE target_types TO role_spec_list opt_with_grant_option
  6299    {
  6300      $$.val = &tree.Grant{Privileges: $2.privilegeList(), Targets: $5.grantTargetList(), Grantees: $7.roleSpecList(), WithGrantOption: $8.bool(),}
  6301    }
  6302  | GRANT privileges ON SCHEMA schema_name_list TO role_spec_list opt_with_grant_option
  6303    {
  6304      $$.val = &tree.Grant{
  6305        Privileges: $2.privilegeList(),
  6306        Targets: tree.GrantTargetList{
  6307          Schemas: $5.objectNamePrefixList(),
  6308        },
  6309        Grantees: $7.roleSpecList(),
  6310        WithGrantOption: $8.bool(),
  6311      }
  6312    }
  6313  | GRANT privileges ON SCHEMA schema_name_list TO role_spec_list WITH error
  6314    {
  6315      return unimplemented(sqllex, "grant privileges on schema with")
  6316    }
  6317  | GRANT privileges ON ALL SEQUENCES IN SCHEMA schema_name_list TO role_spec_list opt_with_grant_option
  6318    {
  6319      $$.val = &tree.Grant{
  6320        Privileges: $2.privilegeList(),
  6321        Targets: tree.GrantTargetList{
  6322          Schemas: $8.objectNamePrefixList(),
  6323          AllSequencesInSchema: true,
  6324        },
  6325        Grantees: $10.roleSpecList(),
  6326        WithGrantOption: $11.bool(),
  6327      }
  6328    }
  6329  | GRANT privileges ON ALL TABLES IN SCHEMA schema_name_list TO role_spec_list opt_with_grant_option
  6330    {
  6331      $$.val = &tree.Grant{
  6332        Privileges: $2.privilegeList(),
  6333        Targets: tree.GrantTargetList{
  6334          Schemas: $8.objectNamePrefixList(),
  6335          AllTablesInSchema: true,
  6336        },
  6337        Grantees: $10.roleSpecList(),
  6338        WithGrantOption: $11.bool(),
  6339      }
  6340    }
  6341  | GRANT privileges ON ALL FUNCTIONS IN SCHEMA schema_name_list TO role_spec_list opt_with_grant_option
  6342    {
  6343      $$.val = &tree.Grant{
  6344        Privileges: $2.privilegeList(),
  6345        Targets: tree.GrantTargetList{
  6346          Schemas: $8.objectNamePrefixList(),
  6347          AllFunctionsInSchema: true,
  6348        },
  6349        Grantees: $10.roleSpecList(),
  6350        WithGrantOption: $11.bool(),
  6351      }
  6352    }
  6353  | GRANT privileges ON ALL PROCEDURES IN SCHEMA schema_name_list TO role_spec_list opt_with_grant_option
  6354    {
  6355      $$.val = &tree.Grant{
  6356        Privileges: $2.privilegeList(),
  6357        Targets: tree.GrantTargetList{
  6358          Schemas: $8.objectNamePrefixList(),
  6359          AllProceduresInSchema: true,
  6360        },
  6361        Grantees: $10.roleSpecList(),
  6362        WithGrantOption: $11.bool(),
  6363      }
  6364    }
  6365  | GRANT SYSTEM privileges TO role_spec_list opt_with_grant_option
  6366    {
  6367      $$.val = &tree.Grant{
  6368        Privileges: $3.privilegeList(),
  6369        Targets: tree.GrantTargetList{
  6370          System: true,
  6371        },
  6372        Grantees: $5.roleSpecList(),
  6373        WithGrantOption: $6.bool(),
  6374      }
  6375    }
  6376  | GRANT error // SHOW HELP: GRANT
  6377  
  6378  // %Help: REVOKE - remove access privileges and role memberships
  6379  // %Category: Priv
  6380  // %Text:
  6381  // Revoke privileges:
  6382  //   REVOKE {ALL | <privileges...> } ON <targets...> FROM <grantees...>
  6383  // Revoke role membership:
  6384  //   REVOKE [ADMIN OPTION FOR] <roles...> FROM <grantees...>
  6385  //
  6386  // Privileges:
  6387  //   CREATE, DROP, GRANT, SELECT, INSERT, DELETE, UPDATE, USAGE, EXECUTE
  6388  //
  6389  // Targets:
  6390  //   DATABASE <databasename> [, <databasename>]...
  6391  //   [TABLE] [<databasename> .] { <tablename> | * } [, ...]
  6392  //   TYPE <typename> [, <typename>]...
  6393  //   FUNCTION <functionname> [ ( [ [ argmode ] [ argname ] argtype [, ...] ] ) ] [, ...]
  6394  //   SCHEMA [<databasename> .]<schemaname> [, [<databasename> .]<schemaname]...
  6395  //   ALL TABLES IN SCHEMA schema_name [, ...]
  6396  //
  6397  // %SeeAlso: GRANT, WEBDOCS/revoke.html
  6398  revoke_stmt:
  6399    REVOKE privileges ON grant_targets FROM role_spec_list
  6400    {
  6401      $$.val = &tree.Revoke{Privileges: $2.privilegeList(), Grantees: $6.roleSpecList(), Targets: $4.grantTargetList(), GrantOptionFor: false}
  6402    }
  6403  | REVOKE GRANT OPTION FOR privileges ON grant_targets FROM role_spec_list
  6404    {
  6405      $$.val = &tree.Revoke{Privileges: $5.privilegeList(), Grantees: $9.roleSpecList(), Targets: $7.grantTargetList(), GrantOptionFor: true}
  6406    }
  6407  | REVOKE privilege_list FROM role_spec_list
  6408    {
  6409      $$.val = &tree.RevokeRole{Roles: $2.nameList(), Members: $4.roleSpecList(), AdminOption: false }
  6410    }
  6411  | REVOKE ADMIN OPTION FOR privilege_list FROM role_spec_list
  6412    {
  6413      $$.val = &tree.RevokeRole{Roles: $5.nameList(), Members: $7.roleSpecList(), AdminOption: true }
  6414    }
  6415  | REVOKE privileges ON TYPE target_types FROM role_spec_list
  6416    {
  6417      $$.val = &tree.Revoke{Privileges: $2.privilegeList(), Targets: $5.grantTargetList(), Grantees: $7.roleSpecList(), GrantOptionFor: false}
  6418    }
  6419  | REVOKE GRANT OPTION FOR privileges ON TYPE target_types FROM role_spec_list
  6420    {
  6421      $$.val = &tree.Revoke{Privileges: $5.privilegeList(), Targets: $8.grantTargetList(), Grantees: $10.roleSpecList(), GrantOptionFor: true}
  6422    }
  6423  | REVOKE privileges ON SCHEMA schema_name_list FROM role_spec_list
  6424    {
  6425      $$.val = &tree.Revoke{
  6426        Privileges: $2.privilegeList(),
  6427        Targets: tree.GrantTargetList{
  6428          Schemas: $5.objectNamePrefixList(),
  6429        },
  6430        Grantees: $7.roleSpecList(),
  6431        GrantOptionFor: false,
  6432      }
  6433    }
  6434  | REVOKE GRANT OPTION FOR privileges ON SCHEMA schema_name_list FROM role_spec_list
  6435    {
  6436      $$.val = &tree.Revoke{
  6437        Privileges: $5.privilegeList(),
  6438        Targets: tree.GrantTargetList{
  6439          Schemas: $8.objectNamePrefixList(),
  6440        },
  6441        Grantees: $10.roleSpecList(),
  6442        GrantOptionFor: true,
  6443      }
  6444    }
  6445  | REVOKE privileges ON ALL TABLES IN SCHEMA schema_name_list FROM role_spec_list
  6446    {
  6447      $$.val = &tree.Revoke{
  6448        Privileges: $2.privilegeList(),
  6449        Targets: tree.GrantTargetList{
  6450          Schemas: $8.objectNamePrefixList(),
  6451          AllTablesInSchema: true,
  6452        },
  6453        Grantees: $10.roleSpecList(),
  6454        GrantOptionFor: false,
  6455      }
  6456    }
  6457  | REVOKE privileges ON ALL SEQUENCES IN SCHEMA schema_name_list FROM role_spec_list
  6458    {
  6459      $$.val = &tree.Revoke{
  6460        Privileges: $2.privilegeList(),
  6461        Targets: tree.GrantTargetList{
  6462          Schemas: $8.objectNamePrefixList(),
  6463          AllSequencesInSchema: true,
  6464        },
  6465        Grantees: $10.roleSpecList(),
  6466        GrantOptionFor: false,
  6467      }
  6468    }
  6469  | REVOKE GRANT OPTION FOR privileges ON ALL TABLES IN SCHEMA schema_name_list FROM role_spec_list
  6470    {
  6471      $$.val = &tree.Revoke{
  6472        Privileges: $5.privilegeList(),
  6473        Targets: tree.GrantTargetList{
  6474          Schemas: $11.objectNamePrefixList(),
  6475          AllTablesInSchema: true,
  6476        },
  6477        Grantees: $13.roleSpecList(),
  6478        GrantOptionFor: true,
  6479      }
  6480    }
  6481  | REVOKE privileges ON ALL FUNCTIONS IN SCHEMA schema_name_list FROM role_spec_list
  6482    {
  6483      $$.val = &tree.Revoke{
  6484        Privileges: $2.privilegeList(),
  6485        Targets: tree.GrantTargetList{
  6486          Schemas: $8.objectNamePrefixList(),
  6487          AllFunctionsInSchema: true,
  6488        },
  6489        Grantees: $10.roleSpecList(),
  6490        GrantOptionFor: false,
  6491      }
  6492    }
  6493  | REVOKE GRANT OPTION FOR privileges ON ALL FUNCTIONS IN SCHEMA schema_name_list FROM role_spec_list
  6494    {
  6495      $$.val = &tree.Revoke{
  6496        Privileges: $5.privilegeList(),
  6497        Targets: tree.GrantTargetList{
  6498          Schemas: $11.objectNamePrefixList(),
  6499          AllFunctionsInSchema: true,
  6500        },
  6501        Grantees: $13.roleSpecList(),
  6502        GrantOptionFor: true,
  6503      }
  6504    }
  6505  | REVOKE privileges ON ALL PROCEDURES IN SCHEMA schema_name_list FROM role_spec_list
  6506    {
  6507      $$.val = &tree.Revoke{
  6508        Privileges: $2.privilegeList(),
  6509        Targets: tree.GrantTargetList{
  6510          Schemas: $8.objectNamePrefixList(),
  6511          AllProceduresInSchema: true,
  6512        },
  6513        Grantees: $10.roleSpecList(),
  6514        GrantOptionFor: false,
  6515      }
  6516    }
  6517  | REVOKE GRANT OPTION FOR privileges ON ALL PROCEDURES IN SCHEMA schema_name_list FROM role_spec_list
  6518    {
  6519      $$.val = &tree.Revoke{
  6520        Privileges: $5.privilegeList(),
  6521        Targets: tree.GrantTargetList{
  6522          Schemas: $11.objectNamePrefixList(),
  6523          AllProceduresInSchema: true,
  6524        },
  6525        Grantees: $13.roleSpecList(),
  6526        GrantOptionFor: true,
  6527      }
  6528    }
  6529  | REVOKE SYSTEM privileges FROM role_spec_list
  6530    {
  6531      $$.val = &tree.Revoke{
  6532        Privileges: $3.privilegeList(),
  6533        Targets: tree.GrantTargetList{
  6534          System: true,
  6535        },
  6536        Grantees: $5.roleSpecList(),
  6537      }
  6538    }
  6539  | REVOKE GRANT OPTION FOR SYSTEM privileges FROM role_spec_list
  6540    {
  6541      $$.val = &tree.Revoke{
  6542        Privileges: $6.privilegeList(),
  6543        Targets: tree.GrantTargetList{
  6544          System: true,
  6545        },
  6546        Grantees: $8.roleSpecList(),
  6547        GrantOptionFor: true,
  6548      }
  6549    }
  6550  | REVOKE privileges ON SEQUENCE error
  6551    {
  6552      return unimplemented(sqllex, "revoke privileges on sequence")
  6553    }
  6554  | REVOKE error // SHOW HELP: REVOKE
  6555  
  6556  
  6557  // ALL can either be by itself, or with the optional PRIVILEGES keyword (which no-ops)
  6558  privileges:
  6559    ALL opt_privileges_clause
  6560    {
  6561      $$.val = privilege.List{privilege.ALL}
  6562    }
  6563  | privilege_list
  6564    {
  6565       privList, err := privilege.ListFromStrings($1.nameList().ToStrings(), privilege.OriginFromUserInput)
  6566       if err != nil {
  6567         return setErr(sqllex, err)
  6568       }
  6569       $$.val = privList
  6570    }
  6571  
  6572  privilege_list:
  6573    privilege
  6574    {
  6575      $$.val = tree.NameList{tree.Name($1)}
  6576    }
  6577  | privilege_list ',' privilege
  6578    {
  6579      $$.val = append($1.nameList(), tree.Name($3))
  6580    }
  6581  
  6582  // Privileges are parsed at execution time to avoid having to make them reserved.
  6583  // Any privileges above `col_name_keyword` should be listed here.
  6584  // The full list is in sql/privilege/privilege.go.
  6585  privilege:
  6586    name
  6587  | CREATE
  6588  | GRANT
  6589  | SELECT
  6590  
  6591  reset_stmt:
  6592    reset_session_stmt  // EXTEND WITH HELP: RESET
  6593  | reset_csetting_stmt // EXTEND WITH HELP: RESET CLUSTER SETTING
  6594  
  6595  // %Help: RESET - reset a session variable to its default value
  6596  // %Category: Cfg
  6597  // %Text: RESET [SESSION] <var>
  6598  // %SeeAlso: RESET CLUSTER SETTING, WEBDOCS/set-vars.html
  6599  reset_session_stmt:
  6600    RESET session_var
  6601    {
  6602      $$.val = &tree.SetVar{Name: $2, Values:tree.Exprs{tree.DefaultVal{}}, Reset: true}
  6603    }
  6604  | RESET SESSION session_var
  6605    {
  6606      $$.val = &tree.SetVar{Name: $3, Values:tree.Exprs{tree.DefaultVal{}}, Reset: true}
  6607    }
  6608  | RESET_ALL ALL
  6609    {
  6610      $$.val = &tree.SetVar{ResetAll: true, Reset: true}
  6611    }
  6612  | RESET error // SHOW HELP: RESET
  6613  
  6614  // %Help: RESET CLUSTER SETTING - reset a cluster setting to its default value
  6615  // %Category: Cfg
  6616  // %Text: RESET CLUSTER SETTING <var>
  6617  // %SeeAlso: SET CLUSTER SETTING, RESET
  6618  reset_csetting_stmt:
  6619    RESET CLUSTER SETTING var_name
  6620    {
  6621      $$.val = &tree.SetClusterSetting{Name: strings.Join($4.strs(), "."), Value:tree.DefaultVal{}}
  6622    }
  6623  | RESET CLUSTER error // SHOW HELP: RESET CLUSTER SETTING
  6624  
  6625  // USE is the MSSQL/MySQL equivalent of SET DATABASE. Alias it for convenience.
  6626  // %Help: USE - set the current database
  6627  // %Category: Cfg
  6628  // %Text: USE <dbname>
  6629  //
  6630  // "USE <dbname>" is an alias for "SET [SESSION] database = <dbname>".
  6631  // %SeeAlso: SET SESSION, WEBDOCS/set-vars.html
  6632  use_stmt:
  6633    USE var_value
  6634    {
  6635      $$.val = &tree.SetVar{Name: "database", Values: tree.Exprs{$2.expr()}}
  6636    }
  6637  | USE error // SHOW HELP: USE
  6638  
  6639  // SET remainder, e.g. SET TRANSACTION
  6640  nonpreparable_set_stmt:
  6641    set_transaction_stmt // EXTEND WITH HELP: SET TRANSACTION
  6642  | set_exprs_internal   { /* SKIP DOC */ }
  6643  | SET CONSTRAINTS error { return unimplemented(sqllex, "set constraints") }
  6644  
  6645  // SET SESSION / SET LOCAL / SET CLUSTER SETTING
  6646  preparable_set_stmt:
  6647    set_session_stmt     // EXTEND WITH HELP: SET SESSION
  6648  | set_local_stmt       // EXTEND WITH HELP: SET LOCAL
  6649  | set_csetting_stmt    // EXTEND WITH HELP: SET CLUSTER SETTING
  6650  | use_stmt             // EXTEND WITH HELP: USE
  6651  
  6652  // %Help: SCRUB - run checks against databases or tables
  6653  // %Category: Experimental
  6654  // %Text:
  6655  // EXPERIMENTAL SCRUB TABLE <table> ...
  6656  // EXPERIMENTAL SCRUB DATABASE <database>
  6657  //
  6658  // The various checks that ca be run with SCRUB includes:
  6659  //   - Physical table data (encoding)
  6660  //   - Secondary index integrity
  6661  //   - Constraint integrity (NOT NULL, CHECK, FOREIGN KEY, UNIQUE)
  6662  // %SeeAlso: SCRUB TABLE, SCRUB DATABASE
  6663  scrub_stmt:
  6664    scrub_table_stmt
  6665  | scrub_database_stmt
  6666  | EXPERIMENTAL SCRUB error // SHOW HELP: SCRUB
  6667  
  6668  // %Help: SCRUB DATABASE - run scrub checks on a database
  6669  // %Category: Experimental
  6670  // %Text:
  6671  // EXPERIMENTAL SCRUB DATABASE <database>
  6672  //                             [AS OF SYSTEM TIME <expr>]
  6673  //
  6674  // All scrub checks will be run on the database. This includes:
  6675  //   - Physical table data (encoding)
  6676  //   - Secondary index integrity
  6677  //   - Constraint integrity (NOT NULL, CHECK, FOREIGN KEY, UNIQUE)
  6678  // %SeeAlso: SCRUB TABLE, SCRUB
  6679  scrub_database_stmt:
  6680    EXPERIMENTAL SCRUB DATABASE database_name opt_as_of_clause
  6681    {
  6682      $$.val = &tree.Scrub{Typ: tree.ScrubDatabase, Database: tree.Name($4), AsOf: $5.asOfClause()}
  6683    }
  6684  | EXPERIMENTAL SCRUB DATABASE error // SHOW HELP: SCRUB DATABASE
  6685  
  6686  // %Help: SCRUB TABLE - run scrub checks on a table
  6687  // %Category: Experimental
  6688  // %Text:
  6689  // SCRUB TABLE <tablename>
  6690  //             [AS OF SYSTEM TIME <expr>]
  6691  //             [WITH OPTIONS <option> [, ...]]
  6692  //
  6693  // Options:
  6694  //   EXPERIMENTAL SCRUB TABLE ... WITH OPTIONS INDEX ALL
  6695  //   EXPERIMENTAL SCRUB TABLE ... WITH OPTIONS INDEX (<index>...)
  6696  //   EXPERIMENTAL SCRUB TABLE ... WITH OPTIONS CONSTRAINT ALL
  6697  //   EXPERIMENTAL SCRUB TABLE ... WITH OPTIONS CONSTRAINT (<constraint>...)
  6698  //   EXPERIMENTAL SCRUB TABLE ... WITH OPTIONS PHYSICAL
  6699  // %SeeAlso: SCRUB DATABASE, SRUB
  6700  scrub_table_stmt:
  6701    EXPERIMENTAL SCRUB TABLE table_name opt_as_of_clause opt_scrub_options_clause
  6702    {
  6703      $$.val = &tree.Scrub{
  6704        Typ: tree.ScrubTable,
  6705        Table: $4.unresolvedObjectName(),
  6706        AsOf: $5.asOfClause(),
  6707        Options: $6.scrubOptions(),
  6708      }
  6709    }
  6710  | EXPERIMENTAL SCRUB TABLE error // SHOW HELP: SCRUB TABLE
  6711  
  6712  opt_scrub_options_clause:
  6713    WITH OPTIONS scrub_option_list
  6714    {
  6715      $$.val = $3.scrubOptions()
  6716    }
  6717  | /* EMPTY */
  6718    {
  6719      $$.val = tree.ScrubOptions{}
  6720    }
  6721  
  6722  scrub_option_list:
  6723    scrub_option
  6724    {
  6725      $$.val = tree.ScrubOptions{$1.scrubOption()}
  6726    }
  6727  | scrub_option_list ',' scrub_option
  6728    {
  6729      $$.val = append($1.scrubOptions(), $3.scrubOption())
  6730    }
  6731  
  6732  scrub_option:
  6733    INDEX ALL
  6734    {
  6735      $$.val = &tree.ScrubOptionIndex{}
  6736    }
  6737  | INDEX_BEFORE_PAREN '(' name_list ')'
  6738    {
  6739      $$.val = &tree.ScrubOptionIndex{IndexNames: $3.nameList()}
  6740    }
  6741  | CONSTRAINT ALL
  6742    {
  6743      $$.val = &tree.ScrubOptionConstraint{}
  6744    }
  6745  | CONSTRAINT '(' name_list ')'
  6746    {
  6747      $$.val = &tree.ScrubOptionConstraint{ConstraintNames: $3.nameList()}
  6748    }
  6749  | PHYSICAL
  6750    {
  6751      $$.val = &tree.ScrubOptionPhysical{}
  6752    }
  6753  
  6754  // %Help: SET CLUSTER SETTING - change a cluster setting
  6755  // %Category: Cfg
  6756  // %Text: SET CLUSTER SETTING <var> { TO | = } <value>
  6757  // %SeeAlso: SHOW CLUSTER SETTING, RESET CLUSTER SETTING, SET SESSION, SET LOCAL
  6758  // WEBDOCS/cluster-settings.html
  6759  set_csetting_stmt:
  6760    SET CLUSTER SETTING var_name to_or_eq var_value
  6761    {
  6762      $$.val = &tree.SetClusterSetting{Name: strings.Join($4.strs(), "."), Value: $6.expr()}
  6763    }
  6764  | SET CLUSTER error // SHOW HELP: SET CLUSTER SETTING
  6765  
  6766  
  6767  // %Help: ALTER VIRTUAL CLUSTER - alter configuration of virtual clusters
  6768  // %Category: Group
  6769  // %Text:
  6770  // ALTER VIRTUAL CLUSTER REPLICATION, ALTER VIRTUAL CLUSTER SETTING,
  6771  // ALTER VIRTUAL CLUSTER CAPABILITY, ALTER VIRTUAL CLUSTER RENAME,
  6772  // ALTER VIRTUAL CLUSTER SERVICE
  6773  alter_virtual_cluster_stmt:
  6774    alter_virtual_cluster_replication_stmt // EXTEND WITH HELP: ALTER VIRTUAL CLUSTER REPLICATION
  6775  | alter_virtual_cluster_csetting_stmt    // EXTEND WITH HELP: ALTER VIRTUAL CLUSTER SETTING
  6776  | alter_virtual_cluster_capability_stmt  // EXTEND WITH HELP: ALTER VIRTUAL CLUSTER CAPABILITY
  6777  | alter_virtual_cluster_rename_stmt      // EXTEND WITH HELP: ALTER VIRTUAL CLUSTER RENAME
  6778  | alter_virtual_cluster_service_stmt     // EXTEND WITH HELP: ALTER VIRTUAL CLUSTER SERVICE
  6779  | ALTER virtual_cluster error   // SHOW HELP: ALTER VIRTUAL CLUSTER
  6780  
  6781  virtual_cluster_spec:
  6782    d_expr
  6783    { $$.val = &tree.TenantSpec{IsName: true, Expr: $1.expr()} }
  6784  | '[' a_expr ']'
  6785    { $$.val = &tree.TenantSpec{IsName: false, Expr: $2.expr()} }
  6786  
  6787  // %Help: ALTER VIRTUAL CLUSTER RENAME - rename a virtual cluster
  6788  // %Category: Experimental
  6789  // %Text:
  6790  // ALTER VIRTUAL CLUSTER <virtual_cluster_spec> RENAME TO <name>
  6791  alter_virtual_cluster_rename_stmt:
  6792    ALTER virtual_cluster virtual_cluster_spec RENAME TO d_expr
  6793    {
  6794      /* SKIP DOC */
  6795      $$.val = &tree.AlterTenantRename{
  6796        TenantSpec: $3.tenantSpec(),
  6797        NewName: &tree.TenantSpec{IsName: true, Expr: $6.expr()},
  6798      }
  6799    }
  6800  
  6801  // %Help: ALTER VIRTUAL CLUSTER SERVICE - alter service mode of a virtual cluster
  6802  // %Category: Experimental
  6803  // %Text:
  6804  // ALTER VIRTUAL CLUSTER <virtual_cluster_spec> START SERVICE EXTERNAL
  6805  // ALTER VIRTUAL CLUSTER <virtual_cluster_spec> START SERVICE SHARED
  6806  // ALTER VIRTUAL CLUSTER <virtual_cluster_spec> STOP SERVICE
  6807  alter_virtual_cluster_service_stmt:
  6808    ALTER virtual_cluster virtual_cluster_spec START SERVICE EXTERNAL
  6809    {
  6810      /* SKIP DOC */
  6811      $$.val = &tree.AlterTenantService{
  6812        TenantSpec: $3.tenantSpec(),
  6813        Command: tree.TenantStartServiceExternal,
  6814      }
  6815    }
  6816  | ALTER virtual_cluster virtual_cluster_spec START SERVICE SHARED
  6817    {
  6818      /* SKIP DOC */
  6819      $$.val = &tree.AlterTenantService{
  6820        TenantSpec: $3.tenantSpec(),
  6821        Command: tree.TenantStartServiceShared,
  6822      }
  6823    }
  6824  | ALTER virtual_cluster virtual_cluster_spec STOP SERVICE
  6825    {
  6826      /* SKIP DOC */
  6827      $$.val = &tree.AlterTenantService{
  6828        TenantSpec: $3.tenantSpec(),
  6829        Command: tree.TenantStopService,
  6830      }
  6831    }
  6832  | ALTER virtual_cluster virtual_cluster_spec START error // SHOW HELP: ALTER VIRTUAL CLUSTER SERVICE
  6833  | ALTER virtual_cluster virtual_cluster_spec STOP error // SHOW HELP: ALTER VIRTUAL CLUSTER SERVICE
  6834  
  6835  
  6836  // %Help: ALTER VIRTUAL CLUSTER REPLICATION - alter replication stream between virtual clusters
  6837  // %Category: Experimental
  6838  // %Text:
  6839  // ALTER VIRTUAL CLUSTER <virtual_cluster_spec> PAUSE REPLICATION
  6840  // ALTER VIRTUAL CLUSTER <virtual_cluster_spec> RESUME REPLICATION
  6841  // ALTER VIRTUAL CLUSTER <virtual_cluster_spec> COMPLETE REPLICATION TO LATEST
  6842  // ALTER VIRTUAL CLUSTER <virtual_cluster_spec> COMPLETE REPLICATION TO SYSTEM TIME 'time'
  6843  // ALTER VIRTUAL CLUSTER <virtual_cluster_spec> SET REPLICATION opt=value,...
  6844  alter_virtual_cluster_replication_stmt:
  6845    ALTER virtual_cluster virtual_cluster_spec PAUSE REPLICATION
  6846    {
  6847      /* SKIP DOC */
  6848      $$.val = &tree.AlterTenantReplication{
  6849        TenantSpec: $3.tenantSpec(),
  6850        Command: tree.PauseJob,
  6851      }
  6852    }
  6853  | ALTER virtual_cluster virtual_cluster_spec RESUME REPLICATION
  6854    {
  6855      /* SKIP DOC */
  6856      $$.val = &tree.AlterTenantReplication{
  6857        TenantSpec: $3.tenantSpec(),
  6858        Command: tree.ResumeJob,
  6859      }
  6860    }
  6861  | ALTER virtual_cluster virtual_cluster_spec COMPLETE REPLICATION TO SYSTEM TIME a_expr
  6862    {
  6863      /* SKIP DOC */
  6864      $$.val = &tree.AlterTenantReplication{
  6865        TenantSpec: $3.tenantSpec(),
  6866        Cutover: &tree.ReplicationCutoverTime{
  6867          Timestamp: $9.expr(),
  6868        },
  6869      }
  6870    }
  6871  | ALTER virtual_cluster virtual_cluster_spec COMPLETE REPLICATION TO LATEST
  6872    {
  6873      /* SKIP DOC */
  6874      $$.val = &tree.AlterTenantReplication{
  6875        TenantSpec: $3.tenantSpec(),
  6876        Cutover: &tree.ReplicationCutoverTime{
  6877          Latest: true,
  6878        },
  6879      }
  6880    }
  6881  | ALTER virtual_cluster virtual_cluster_spec SET REPLICATION replication_options_list
  6882    {
  6883      /* SKIP DOC */
  6884      $$.val = &tree.AlterTenantReplication{
  6885        TenantSpec: $3.tenantSpec(),
  6886        Options: *$6.tenantReplicationOptions(),
  6887      }
  6888    }
  6889  
  6890  
  6891  // %Help: ALTER VIRTUAL CLUSTER SETTING - alter cluster setting overrides for virtual clusters
  6892  // %Category: Group
  6893  // %Text:
  6894  // ALTER VIRTUAL CLUSTER { <virtual_cluster_spec> | ALL } SET CLUSTER SETTING <var> { TO | = } <value>
  6895  // ALTER VIRTUAL CLUSTER { <virtual_cluster_spec> | ALL } RESET CLUSTER SETTING <var>
  6896  // %SeeAlso: SET CLUSTER SETTING
  6897  alter_virtual_cluster_csetting_stmt:
  6898    ALTER virtual_cluster virtual_cluster_spec set_or_reset_csetting_stmt
  6899    {
  6900      /* SKIP DOC */
  6901      csettingStmt := $4.stmt().(*tree.SetClusterSetting)
  6902      $$.val = &tree.AlterTenantSetClusterSetting{
  6903        SetClusterSetting: *csettingStmt,
  6904        TenantSpec: $3.tenantSpec(),
  6905      }
  6906    }
  6907  | ALTER TENANT_ALL ALL set_or_reset_csetting_stmt
  6908    {
  6909      /* SKIP DOC */
  6910      csettingStmt := $4.stmt().(*tree.SetClusterSetting)
  6911      $$.val = &tree.AlterTenantSetClusterSetting{
  6912        SetClusterSetting: *csettingStmt,
  6913        TenantSpec: &tree.TenantSpec{All: true},
  6914      }
  6915    }
  6916  | ALTER VIRTUAL CLUSTER_ALL ALL set_or_reset_csetting_stmt
  6917    {
  6918      /* SKIP DOC */
  6919      csettingStmt := $5.stmt().(*tree.SetClusterSetting)
  6920      $$.val = &tree.AlterTenantSetClusterSetting{
  6921        SetClusterSetting: *csettingStmt,
  6922        TenantSpec: &tree.TenantSpec{All: true},
  6923      }
  6924    }
  6925  | ALTER VIRTUAL CLUSTER_ALL ALL error // SHOW HELP: ALTER VIRTUAL CLUSTER SETTING
  6926  | ALTER TENANT_ALL ALL error // SHOW HELP: ALTER VIRTUAL CLUSTER SETTING
  6927  
  6928  set_or_reset_csetting_stmt:
  6929    reset_csetting_stmt
  6930  | set_csetting_stmt
  6931  
  6932  to_or_eq:
  6933    '='
  6934  | TO
  6935  
  6936  // %Help: ALTER VIRTUAL CLUSTER CAPABILITY - alter system capability of virtual cluster
  6937  // %Category: Group
  6938  // %Text:
  6939  // ALTER VIRTUAL CLUSTER <tenant_id> GRANT CAPABILITY <var> { TO | = } <value>
  6940  // ALTER VIRTUAL CLUSTER <tenant_id> REVOKE CAPABILITY <var>
  6941  alter_virtual_cluster_capability_stmt:
  6942    ALTER virtual_cluster virtual_cluster_spec GRANT CAPABILITY virtual_cluster_capability_list
  6943    {
  6944      /* SKIP DOC */
  6945      $$.val = &tree.AlterTenantCapability{
  6946        TenantSpec: $3.tenantSpec(),
  6947        Capabilities: $6.tenantCapabilities(),
  6948      }
  6949    }
  6950  | ALTER virtual_cluster virtual_cluster_spec GRANT ALL CAPABILITIES
  6951    {
  6952      /* SKIP DOC */
  6953      $$.val = &tree.AlterTenantCapability{
  6954        TenantSpec: $3.tenantSpec(),
  6955        AllCapabilities: true,
  6956      }
  6957    }
  6958  | ALTER virtual_cluster virtual_cluster_spec REVOKE CAPABILITY virtual_cluster_capability_list
  6959    {
  6960      /* SKIP DOC */
  6961      $$.val = &tree.AlterTenantCapability{
  6962        TenantSpec: $3.tenantSpec(),
  6963        Capabilities: $6.tenantCapabilities(),
  6964        IsRevoke: true,
  6965      }
  6966    }
  6967  | ALTER virtual_cluster virtual_cluster_spec REVOKE ALL CAPABILITIES
  6968    {
  6969      /* SKIP DOC */
  6970      $$.val = &tree.AlterTenantCapability{
  6971        TenantSpec: $3.tenantSpec(),
  6972        AllCapabilities: true,
  6973        IsRevoke: true,
  6974      }
  6975    }
  6976  | ALTER virtual_cluster virtual_cluster_spec GRANT error // SHOW HELP: ALTER VIRTUAL CLUSTER CAPABILITY
  6977  | ALTER virtual_cluster virtual_cluster_spec REVOKE error // SHOW HELP: ALTER VIRTUAL CLUSTER CAPABILITY
  6978  
  6979  virtual_cluster_capability:
  6980    var_name
  6981    {
  6982      /* SKIP DOC */
  6983      $$.val = tree.TenantCapability{
  6984        Name: strings.Join($1.strs(), "."),
  6985      }
  6986    }
  6987  | var_name to_or_eq var_value
  6988    {
  6989      /* SKIP DOC */
  6990      $$.val = tree.TenantCapability{
  6991        Name: strings.Join($1.strs(), "."),
  6992        Value: $3.expr(),
  6993      }
  6994    }
  6995  
  6996  virtual_cluster_capability_list:
  6997    virtual_cluster_capability
  6998    {
  6999      /* SKIP DOC */
  7000      $$.val = []tree.TenantCapability{$1.tenantCapability()}
  7001    }
  7002  | virtual_cluster_capability_list ',' virtual_cluster_capability
  7003    {
  7004      /* SKIP DOC */
  7005      $$.val = append($1.tenantCapabilities(), $3.tenantCapability())
  7006    }
  7007  
  7008  set_exprs_internal:
  7009    /* SET ROW serves to accelerate parser.parseExprs().
  7010       It cannot be used by clients. */
  7011    SET ROW '(' expr_list ')'
  7012    {
  7013      $$.val = &tree.SetVar{Values: $4.exprs(), SetRow: true}
  7014    }
  7015  
  7016  // %Help: SET SESSION - change a session variable
  7017  // %Category: Cfg
  7018  // %Text:
  7019  // SET [SESSION] <var> { TO | = } <values...>
  7020  // SET [SESSION] TIME ZONE <tz>
  7021  // SET [SESSION] CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL { READ COMMITTED | SERIALIZABLE }
  7022  // SET [SESSION] TRACING { TO | = } { on | off | cluster | kv | results } [,...]
  7023  //
  7024  // %SeeAlso: SHOW SESSION, RESET, DISCARD, SHOW, SET CLUSTER SETTING, SET TRANSACTION, SET LOCAL
  7025  // WEBDOCS/set-vars.html
  7026  set_session_stmt:
  7027    SET_TRACING TRACING to_or_eq var_list
  7028  	{
  7029      /* SKIP DOC */
  7030      // We need to recognize the "set tracing" specially here using syntax lookahead.
  7031      $$.val = &tree.SetTracing{Values: $4.exprs()}
  7032  	}
  7033  | SET_TRACING SESSION TRACING to_or_eq var_list
  7034  	{
  7035      /* SKIP DOC */
  7036      // We need to recognize the "set tracing" specially here using syntax lookahead.
  7037      $$.val = &tree.SetTracing{Values: $5.exprs()}
  7038  	}
  7039  | SET SESSION set_rest_more
  7040    {
  7041      $$.val = $3.stmt()
  7042    }
  7043  | SET SESSION error  // SHOW HELP: SET SESSION
  7044  | SET set_rest_more
  7045    {
  7046      $$.val = $2.stmt()
  7047    }
  7048  | SET error  // SHOW HELP: SET SESSION
  7049  // Special form for pg compatibility:
  7050  | SET SESSION CHARACTERISTICS AS TRANSACTION transaction_mode_list
  7051    {
  7052      $$.val = &tree.SetSessionCharacteristics{Modes: $6.transactionModes()}
  7053    }
  7054  
  7055  // %Help: SET LOCAL - change a session variable scoped to the current transaction
  7056  // %Category: Cfg
  7057  // %Text:
  7058  // SET LOCAL <var> { TO | = } <values...>
  7059  // SET LOCAL TIME ZONE <tz>
  7060  //
  7061  // %SeeAlso: SHOW SESSION, RESET, DISCARD, SHOW, SET CLUSTER SETTING, SET TRANSACTION, SET SESSION
  7062  // WEBDOCS/set-vars.html
  7063  set_local_stmt:
  7064    SET LOCAL set_rest
  7065    {
  7066      ret := $3.setVar()
  7067      ret.Local = true
  7068      $$.val = ret
  7069    }
  7070  | SET LOCAL error  // SHOW HELP: SET LOCAL
  7071  
  7072  // %Help: SET TRANSACTION - configure the transaction settings
  7073  // %Category: Txn
  7074  // %Text:
  7075  // SET [SESSION] TRANSACTION <txnparameters...>
  7076  //
  7077  // Transaction parameters:
  7078  //    ISOLATION LEVEL { READ COMMITTED | SERIALIZABLE }
  7079  //    PRIORITY { LOW | NORMAL | HIGH }
  7080  //    AS OF SYSTEM TIME <expr>
  7081  //    [NOT] DEFERRABLE
  7082  //
  7083  // %SeeAlso: SHOW TRANSACTION, SET SESSION, SET LOCAL
  7084  // WEBDOCS/set-transaction.html
  7085  set_transaction_stmt:
  7086    SET TRANSACTION transaction_mode_list
  7087    {
  7088      $$.val = &tree.SetTransaction{Modes: $3.transactionModes()}
  7089    }
  7090  | SET TRANSACTION error // SHOW HELP: SET TRANSACTION
  7091  | SET SESSION TRANSACTION transaction_mode_list
  7092    {
  7093      $$.val = &tree.SetTransaction{Modes: $4.transactionModes()}
  7094    }
  7095  | SET SESSION TRANSACTION error // SHOW HELP: SET TRANSACTION
  7096  
  7097  generic_set:
  7098    var_name to_or_eq var_list
  7099    {
  7100      $$.val = &tree.SetVar{Name: strings.Join($1.strs(), "."), Values: $3.exprs()}
  7101    }
  7102  
  7103  set_rest:
  7104  // Generic SET syntaxes:
  7105     generic_set
  7106  // Special SET syntax forms in addition to the generic form.
  7107  // See: https://www.postgresql.org/docs/10/static/sql-set.html
  7108  //
  7109  // "SET TIME ZONE value is an alias for SET timezone TO value."
  7110  | TIME ZONE zone_value
  7111    {
  7112      /* SKIP DOC */
  7113      $$.val = &tree.SetVar{Name: "timezone", Values: tree.Exprs{$3.expr()}}
  7114    }
  7115  | var_name FROM CURRENT { return unimplemented(sqllex, "set from current") }
  7116  // "SET SCHEMA 'value' is an alias for SET search_path TO value. Only
  7117  // one schema can be specified using this syntax."
  7118  | SCHEMA var_value
  7119    {
  7120      /* SKIP DOC */
  7121      $$.val = &tree.SetVar{Name: "search_path", Values: tree.Exprs{$2.expr()}}
  7122    }
  7123  | ROLE var_value
  7124  	{
  7125  		/* SKIP DOC */
  7126      $$.val = &tree.SetVar{Name: "role", Values: tree.Exprs{$2.expr()}}
  7127  	}
  7128  
  7129  set_rest_more:
  7130  // SET syntaxes supported as a clause of other statements:
  7131    set_rest
  7132  | SESSION AUTHORIZATION DEFAULT
  7133    {
  7134      /* SKIP DOC */
  7135      $$.val = &tree.SetSessionAuthorizationDefault{}
  7136    }
  7137  | SESSION AUTHORIZATION IDENT
  7138    {
  7139      return unimplementedWithIssue(sqllex, 40283)
  7140    }
  7141  | SESSION AUTHORIZATION SCONST
  7142    {
  7143      return unimplementedWithIssue(sqllex, 40283)
  7144    }
  7145  // See comment for the non-terminal for SET NAMES below.
  7146  | set_names
  7147  
  7148  // SET NAMES is the SQL standard syntax for SET client_encoding.
  7149  // "SET NAMES value is an alias for SET client_encoding TO value."
  7150  // See https://www.postgresql.org/docs/10/static/sql-set.html
  7151  // Also see https://www.postgresql.org/docs/9.6/static/multibyte.html#AEN39236
  7152  set_names:
  7153    NAMES var_value
  7154    {
  7155      /* SKIP DOC */
  7156      $$.val = &tree.SetVar{Name: "client_encoding", Values: tree.Exprs{$2.expr()}}
  7157    }
  7158  | NAMES
  7159    {
  7160      /* SKIP DOC */
  7161      $$.val = &tree.SetVar{Name: "client_encoding", Values: tree.Exprs{tree.DefaultVal{}}}
  7162    }
  7163  
  7164  var_name:
  7165    name
  7166    {
  7167      $$.val = []string{$1}
  7168    }
  7169  | name attrs
  7170    {
  7171      $$.val = append([]string{$1}, $2.strs()...)
  7172    }
  7173  
  7174  attrs:
  7175    '.' unrestricted_name
  7176    {
  7177      $$.val = []string{$2}
  7178    }
  7179  | attrs '.' unrestricted_name
  7180    {
  7181      $$.val = append($1.strs(), $3)
  7182    }
  7183  
  7184  var_value:
  7185    a_expr
  7186  | extra_var_value
  7187    {
  7188      $$.val = tree.Expr(&tree.UnresolvedName{NumParts: 1, Parts: tree.NameParts{$1}})
  7189    }
  7190  
  7191  // The RHS of a SET statement can contain any valid expression, which
  7192  // themselves can contain identifiers like TRUE, FALSE. These are parsed
  7193  // as column names (via a_expr) and later during semantic analysis
  7194  // assigned their special value.
  7195  //
  7196  // In addition, for compatibility with CockroachDB we need to support
  7197  // the reserved keyword ON (to go along OFF, which is a valid column name).
  7198  // Similarly, NONE is specially allowed here.
  7199  //
  7200  // Finally, in PostgreSQL the CockroachDB-reserved words "index",
  7201  // "nothing", etc. are not special and are valid in SET. These need to
  7202  // be allowed here too.
  7203  extra_var_value:
  7204    ON
  7205  | NONE
  7206  | cockroachdb_extra_reserved_keyword
  7207  
  7208  var_list:
  7209    var_value
  7210    {
  7211      $$.val = tree.Exprs{$1.expr()}
  7212    }
  7213  | var_list ',' var_value
  7214    {
  7215      $$.val = append($1.exprs(), $3.expr())
  7216    }
  7217  
  7218  iso_level:
  7219    READ UNCOMMITTED
  7220    {
  7221      $$.val = tree.ReadUncommittedIsolation
  7222    }
  7223  | READ COMMITTED
  7224    {
  7225      $$.val = tree.ReadCommittedIsolation
  7226    }
  7227  | SNAPSHOT
  7228    {
  7229      $$.val = tree.SnapshotIsolation
  7230    }
  7231  | REPEATABLE READ
  7232    {
  7233      $$.val = tree.RepeatableReadIsolation
  7234    }
  7235  | SERIALIZABLE
  7236    {
  7237      $$.val = tree.SerializableIsolation
  7238    }
  7239  
  7240  user_priority:
  7241    LOW
  7242    {
  7243      $$.val = tree.Low
  7244    }
  7245  | NORMAL
  7246    {
  7247      $$.val = tree.Normal
  7248    }
  7249  | HIGH
  7250    {
  7251      $$.val = tree.High
  7252    }
  7253  
  7254  // Timezone values can be:
  7255  // - a string such as 'pst8pdt'
  7256  // - an identifier such as "pst8pdt"
  7257  // - an integer or floating point number
  7258  // - a time interval per SQL99
  7259  zone_value:
  7260    SCONST
  7261    {
  7262      $$.val = tree.NewStrVal($1)
  7263    }
  7264  | IDENT
  7265    {
  7266      $$.val = tree.NewStrVal($1)
  7267    }
  7268  | interval_value
  7269    {
  7270      $$.val = $1.expr()
  7271    }
  7272  | numeric_only
  7273  | DEFAULT
  7274    {
  7275      $$.val = tree.DefaultVal{}
  7276    }
  7277  | LOCAL
  7278    {
  7279      $$.val = tree.NewStrVal($1)
  7280    }
  7281  
  7282  // %Help: SHOW
  7283  // %Category: Group
  7284  // %Text:
  7285  // SHOW BACKUP, SHOW CLUSTER SETTING, SHOW COLUMNS, SHOW CONSTRAINTS,
  7286  // SHOW CREATE, SHOW CREATE SCHEDULES, SHOW DATABASES, SHOW ENUMS, SHOW
  7287  // FUNCTION, SHOW FUNCTIONS, SHOW HISTOGRAM, SHOW INDEXES, SHOW PARTITIONS, SHOW JOBS,
  7288  // SHOW STATEMENTS, SHOW RANGE, SHOW RANGES, SHOW REGIONS, SHOW SURVIVAL GOAL,
  7289  // SHOW ROLES, SHOW SCHEMAS, SHOW SEQUENCES, SHOW SESSION, SHOW SESSIONS,
  7290  // SHOW STATISTICS, SHOW SYNTAX, SHOW TABLES, SHOW TRACE, SHOW TRANSACTION,
  7291  // SHOW TRANSACTIONS, SHOW TRANSFER, SHOW TYPES, SHOW USERS, SHOW LAST QUERY STATISTICS,
  7292  // SHOW SCHEDULES, SHOW LOCALITY, SHOW ZONE CONFIGURATION, SHOW COMMIT TIMESTAMP,
  7293  // SHOW FULL TABLE SCANS, SHOW CREATE EXTERNAL CONNECTIONS
  7294  show_stmt:
  7295    show_backup_stmt           // EXTEND WITH HELP: SHOW BACKUP
  7296  | show_columns_stmt          // EXTEND WITH HELP: SHOW COLUMNS
  7297  | show_constraints_stmt      // EXTEND WITH HELP: SHOW CONSTRAINTS
  7298  | show_create_stmt           // EXTEND WITH HELP: SHOW CREATE
  7299  | show_create_schedules_stmt // EXTEND WITH HELP: SHOW CREATE SCHEDULES
  7300  | show_create_external_connections_stmt // EXTEND WITH HELP: SHOW CREATE EXTERNAL CONNECTIONS
  7301  | show_local_or_virtual_cluster_csettings_stmt // EXTEND WITH HELP: SHOW CLUSTER SETTING
  7302  | show_databases_stmt        // EXTEND WITH HELP: SHOW DATABASES
  7303  | show_enums_stmt            // EXTEND WITH HELP: SHOW ENUMS
  7304  | show_types_stmt            // EXTEND WITH HELP: SHOW TYPES
  7305  | show_fingerprints_stmt
  7306  | show_functions_stmt        // EXTEND WITH HELP: SHOW FUNCTIONS
  7307  | show_procedures_stmt       // EXTEND WITH HELP: SHOW PROCEDURES
  7308  | show_grants_stmt           // EXTEND WITH HELP: SHOW GRANTS
  7309  | show_histogram_stmt        // EXTEND WITH HELP: SHOW HISTOGRAM
  7310  | show_indexes_stmt          // EXTEND WITH HELP: SHOW INDEXES
  7311  | show_partitions_stmt       // EXTEND WITH HELP: SHOW PARTITIONS
  7312  | show_jobs_stmt             // EXTEND WITH HELP: SHOW JOBS
  7313  | show_locality_stmt
  7314  | show_schedules_stmt        // EXTEND WITH HELP: SHOW SCHEDULES
  7315  | show_statements_stmt       // EXTEND WITH HELP: SHOW STATEMENTS
  7316  | show_ranges_stmt           // EXTEND WITH HELP: SHOW RANGES
  7317  | show_range_for_row_stmt
  7318  | show_regions_stmt          // EXTEND WITH HELP: SHOW REGIONS
  7319  | show_survival_goal_stmt    // EXTEND_WITH_HELP: SHOW SURVIVAL GOAL
  7320  | show_roles_stmt            // EXTEND WITH HELP: SHOW ROLES
  7321  | show_savepoint_stmt        // EXTEND WITH HELP: SHOW SAVEPOINT
  7322  | show_schemas_stmt          // EXTEND WITH HELP: SHOW SCHEMAS
  7323  | show_sequences_stmt        // EXTEND WITH HELP: SHOW SEQUENCES
  7324  | show_session_stmt          // EXTEND WITH HELP: SHOW SESSION
  7325  | show_sessions_stmt         // EXTEND WITH HELP: SHOW SESSIONS
  7326  | show_stats_stmt            // EXTEND WITH HELP: SHOW STATISTICS
  7327  | show_syntax_stmt           // EXTEND WITH HELP: SHOW SYNTAX
  7328  | show_tables_stmt           // EXTEND WITH HELP: SHOW TABLES
  7329  | show_virtual_cluster_stmt  // EXTEND WITH HELP: SHOW VIRTUAL CLUSTER
  7330  | show_trace_stmt            // EXTEND WITH HELP: SHOW TRACE
  7331  | show_transaction_stmt      // EXTEND WITH HELP: SHOW TRANSACTION
  7332  | show_transactions_stmt     // EXTEND WITH HELP: SHOW TRANSACTIONS
  7333  | show_transfer_stmt         // EXTEND WITH HELP: SHOW TRANSFER
  7334  | show_users_stmt            // EXTEND WITH HELP: SHOW USERS
  7335  | show_zone_stmt             // EXTEND WITH HELP: SHOW ZONE CONFIGURATION
  7336  | SHOW error                 // SHOW HELP: SHOW
  7337  | show_last_query_stats_stmt
  7338  | show_full_scans_stmt
  7339  | show_default_privileges_stmt // EXTEND WITH HELP: SHOW DEFAULT PRIVILEGES
  7340  | show_completions_stmt
  7341  
  7342  // %Help: CLOSE - close SQL cursor
  7343  // %Category: Misc
  7344  // %Text: CLOSE [ ALL | <name> ]
  7345  // %SeeAlso: DECLARE, FETCH
  7346  close_cursor_stmt:
  7347  	CLOSE ALL
  7348  	{
  7349  	  $$.val = &tree.CloseCursor{
  7350  	    All: true,
  7351  	  }
  7352  	}
  7353  | CLOSE cursor_name
  7354    {
  7355  	  $$.val = &tree.CloseCursor{
  7356  	    Name: tree.Name($2),
  7357  	  }
  7358  	}
  7359  | CLOSE error // SHOW HELP: CLOSE
  7360  
  7361  // %Help: DECLARE - declare SQL cursor
  7362  // %Category: Misc
  7363  // %Text: DECLARE <name> [ options ] CURSOR p [ WITH | WITHOUT HOLD ] FOR <query>
  7364  // %SeeAlso: CLOSE, FETCH
  7365  declare_cursor_stmt:
  7366    // TODO(jordan): the options here should be supported in any order, not just
  7367    // the fixed one here.
  7368  	DECLARE cursor_name opt_binary opt_sensitivity opt_scroll CURSOR opt_hold FOR select_stmt
  7369  	{
  7370  	  $$.val = &tree.DeclareCursor{
  7371  	    Binary: $3.bool(),
  7372  	    Name: tree.Name($2),
  7373  	    Sensitivity: $4.cursorSensitivity(),
  7374  	    Scroll: $5.cursorScrollOption(),
  7375  	    Hold: $7.bool(),
  7376  	    Select: $9.slct(),
  7377  	  }
  7378    }
  7379  | DECLARE error // SHOW HELP: DECLARE
  7380  
  7381  opt_binary:
  7382    BINARY
  7383    {
  7384      $$.val = true
  7385    }
  7386  | /* EMPTY */
  7387    {
  7388      $$.val = false
  7389    }
  7390  
  7391  opt_sensitivity:
  7392    INSENSITIVE
  7393    {
  7394      $$.val = tree.Insensitive
  7395    }
  7396  | ASENSITIVE
  7397    {
  7398      $$.val = tree.Asensitive
  7399    }
  7400  | /* EMPTY */
  7401    {
  7402      $$.val = tree.UnspecifiedSensitivity
  7403    }
  7404  
  7405  opt_scroll:
  7406    SCROLL
  7407    {
  7408      $$.val = tree.Scroll
  7409    }
  7410  | NO SCROLL
  7411    {
  7412      $$.val = tree.NoScroll
  7413    }
  7414  | /* EMPTY */
  7415    {
  7416      $$.val = tree.UnspecifiedScroll
  7417    }
  7418  
  7419  opt_hold:
  7420    WITH HOLD
  7421    {
  7422      $$.val = true
  7423    }
  7424  | WITHOUT HOLD
  7425    {
  7426      $$.val = false
  7427    }
  7428  | /* EMPTY */
  7429    {
  7430      $$.val = false
  7431    }
  7432  
  7433  // %Help: FETCH - fetch rows from a SQL cursor
  7434  // %Category: Misc
  7435  // %Text: FETCH [ direction [ FROM | IN ] ] <name>
  7436  // %SeeAlso: MOVE, CLOSE, DECLARE
  7437  fetch_cursor_stmt:
  7438    FETCH cursor_movement_specifier
  7439    {
  7440      $$.val = &tree.FetchCursor{
  7441        CursorStmt: $2.cursorStmt(),
  7442      }
  7443    }
  7444  | FETCH error // SHOW HELP: FETCH
  7445  
  7446  // %Help: MOVE - move a SQL cursor without fetching rows
  7447  // %Category: Misc
  7448  // %Text: MOVE [ direction [ FROM | IN ] ] <name>
  7449  // %SeeAlso: FETCH, CLOSE, DECLARE
  7450  move_cursor_stmt:
  7451    MOVE cursor_movement_specifier
  7452    {
  7453      $$.val = &tree.MoveCursor{
  7454        CursorStmt: $2.cursorStmt(),
  7455      }
  7456    }
  7457  | MOVE error // SHOW HELP: MOVE
  7458  
  7459  cursor_movement_specifier:
  7460    cursor_name
  7461    {
  7462      $$.val = tree.CursorStmt{
  7463        Name: tree.Name($1),
  7464        Count: 1,
  7465      }
  7466    }
  7467  | from_or_in cursor_name
  7468    {
  7469      $$.val = tree.CursorStmt{
  7470        Name: tree.Name($2),
  7471        Count: 1,
  7472      }
  7473    }
  7474  | next_prior opt_from_or_in cursor_name
  7475    {
  7476      $$.val = tree.CursorStmt{
  7477        Name: tree.Name($3),
  7478        Count: $1.int64(),
  7479      }
  7480    }
  7481  | forward_backward opt_from_or_in cursor_name
  7482    {
  7483      $$.val = tree.CursorStmt{
  7484        Name: tree.Name($3),
  7485        Count: $1.int64(),
  7486      }
  7487    }
  7488  | opt_forward_backward signed_iconst64 opt_from_or_in cursor_name
  7489    {
  7490      $$.val = tree.CursorStmt{
  7491        Name: tree.Name($4),
  7492        Count: $2.int64() * $1.int64(),
  7493      }
  7494    }
  7495  | opt_forward_backward ALL opt_from_or_in cursor_name
  7496    {
  7497      fetchType := tree.FetchAll
  7498      count := $1.int64()
  7499      if count < 0 {
  7500        fetchType = tree.FetchBackwardAll
  7501      }
  7502      $$.val = tree.CursorStmt{
  7503        Name: tree.Name($4),
  7504        FetchType: fetchType,
  7505      }
  7506    }
  7507  | ABSOLUTE signed_iconst64 opt_from_or_in cursor_name
  7508    {
  7509      $$.val = tree.CursorStmt{
  7510        Name: tree.Name($4),
  7511        FetchType: tree.FetchAbsolute,
  7512        Count: $2.int64(),
  7513      }
  7514    }
  7515  | RELATIVE signed_iconst64 opt_from_or_in cursor_name
  7516    {
  7517      $$.val = tree.CursorStmt{
  7518        Name: tree.Name($4),
  7519        FetchType: tree.FetchRelative,
  7520        Count: $2.int64(),
  7521      }
  7522    }
  7523  | FIRST opt_from_or_in cursor_name
  7524    {
  7525      $$.val = tree.CursorStmt{
  7526        Name: tree.Name($3),
  7527        FetchType: tree.FetchFirst,
  7528      }
  7529    }
  7530  | LAST opt_from_or_in cursor_name
  7531    {
  7532      $$.val = tree.CursorStmt{
  7533        Name: tree.Name($3),
  7534        FetchType: tree.FetchLast,
  7535      }
  7536    }
  7537  
  7538  next_prior:
  7539    NEXT  { $$.val = int64(1) }
  7540  | PRIOR { $$.val = int64(-1) }
  7541  
  7542  opt_forward_backward:
  7543    forward_backward { $$.val = $1.int64() }
  7544  | /* EMPTY */ { $$.val = int64(1) }
  7545  
  7546  forward_backward:
  7547    FORWARD  { $$.val = int64(1) }
  7548  | BACKWARD { $$.val = int64(-1) }
  7549  
  7550  opt_from_or_in:
  7551    from_or_in { }
  7552  | /* EMPTY */ { }
  7553  
  7554  from_or_in:
  7555    FROM { }
  7556  | IN { }
  7557  
  7558  reindex_stmt:
  7559    REINDEX TABLE error
  7560    {
  7561      /* SKIP DOC */
  7562      return purposelyUnimplemented(sqllex, "reindex table", "CockroachDB does not require reindexing.")
  7563    }
  7564  | REINDEX INDEX error
  7565    {
  7566      /* SKIP DOC */
  7567      return purposelyUnimplemented(sqllex, "reindex index", "CockroachDB does not require reindexing.")
  7568    }
  7569  | REINDEX SCHEMA error
  7570    {
  7571      /* SKIP DOC */
  7572      return purposelyUnimplemented(sqllex, "reindex schema", "CockroachDB does not require reindexing.")
  7573    }
  7574  | REINDEX DATABASE error
  7575    {
  7576      /* SKIP DOC */
  7577      return purposelyUnimplemented(sqllex, "reindex database", "CockroachDB does not require reindexing.")
  7578    }
  7579  | REINDEX SYSTEM error
  7580    {
  7581      /* SKIP DOC */
  7582      return purposelyUnimplemented(sqllex, "reindex system", "CockroachDB does not require reindexing.")
  7583    }
  7584  
  7585  // %Help: SHOW SESSION - display session variables
  7586  // %Category: Cfg
  7587  // %Text: SHOW [SESSION] { <var> | ALL }
  7588  // %SeeAlso: WEBDOCS/show-vars.html
  7589  show_session_stmt:
  7590    SHOW session_var         { $$.val = &tree.ShowVar{Name: $2} }
  7591  | SHOW SESSION session_var { $$.val = &tree.ShowVar{Name: $3} }
  7592  | SHOW SESSION error // SHOW HELP: SHOW SESSION
  7593  
  7594  session_var:
  7595    IDENT
  7596  | IDENT session_var_parts
  7597    {
  7598      $$ = $1 + "." + strings.Join($2.strs(), ".")
  7599    }
  7600  // Although ALL, SESSION_USER, DATABASE, LC_COLLATE, LC_CTYPE, and TRACING are
  7601  // identifiers for the purpose of SHOW, they lex as separate token types, so
  7602  // they need separate rules.
  7603  | ALL
  7604  | DATABASE
  7605  // SET NAMES is standard SQL for SET client_encoding.
  7606  // See https://www.postgresql.org/docs/9.6/static/multibyte.html#AEN39236
  7607  | NAMES { $$ = "client_encoding" }
  7608  | ROLE
  7609  | SESSION_USER
  7610  | LC_COLLATE
  7611  | LC_CTYPE
  7612  | TRACING { /* SKIP DOC */ }
  7613  | TRACING session_var_parts
  7614    {
  7615      /* SKIP DOC */
  7616      $$ = $1 + "." + strings.Join($2.strs(), ".")
  7617    }
  7618  // TIME ZONE is special: it is two tokens, but is really the identifier "TIME ZONE".
  7619  | TIME ZONE { $$ = "timezone" }
  7620  | TIME error // SHOW HELP: SHOW SESSION
  7621  | VIRTUAL_CLUSTER_NAME
  7622  
  7623  session_var_parts:
  7624    '.' IDENT
  7625    {
  7626      $$.val = []string{$2}
  7627    }
  7628  | session_var_parts '.' IDENT
  7629    {
  7630      $$.val = append($1.strs(), $3)
  7631    }
  7632  
  7633  // %Help: SHOW STATISTICS - display table statistics
  7634  // %Category: Misc
  7635  // %Text: SHOW STATISTICS [USING JSON] FOR TABLE <table_name> [WITH FORECAST]
  7636  //
  7637  // Returns the available statistics for a table. The statistics can include a
  7638  // histogram ID, which can be used with SHOW HISTOGRAM.
  7639  //
  7640  // If USING JSON is specified, the statistics and histograms are encoded in JSON
  7641  // format.
  7642  //
  7643  // If WITH FORECAST is specified, forecasted statistics are included if
  7644  // available.
  7645  //
  7646  // %SeeAlso: SHOW HISTOGRAM
  7647  show_stats_stmt:
  7648    SHOW STATISTICS FOR TABLE table_name opt_with_options
  7649    {
  7650        $$.val = &tree.ShowTableStats{
  7651          Table:   $5.unresolvedObjectName(),
  7652          Options: $6.kvOptions(),
  7653        }
  7654    }
  7655  | SHOW STATISTICS USING JSON FOR TABLE table_name opt_with_options
  7656    {
  7657      /* SKIP DOC */
  7658      $$.val = &tree.ShowTableStats{
  7659        Table:     $7.unresolvedObjectName(),
  7660        UsingJSON: true,
  7661        Options:   $8.kvOptions(),
  7662      }
  7663    }
  7664  | SHOW STATISTICS error // SHOW HELP: SHOW STATISTICS
  7665  
  7666  
  7667  
  7668  // %Help: SHOW HISTOGRAM - display histogram (experimental)
  7669  // %Category: Experimental
  7670  // %Text: SHOW HISTOGRAM <histogram_id>
  7671  //
  7672  // Returns the data in the histogram with the
  7673  // given ID (as returned by SHOW STATISTICS).
  7674  // %SeeAlso: SHOW STATISTICS
  7675  show_histogram_stmt:
  7676    SHOW HISTOGRAM ICONST
  7677    {
  7678      /* SKIP DOC */
  7679      id, err := $3.numVal().AsInt64()
  7680      if err != nil {
  7681        return setErr(sqllex, err)
  7682      }
  7683      $$.val = &tree.ShowHistogram{HistogramID: id}
  7684    }
  7685  | SHOW HISTOGRAM error // SHOW HELP: SHOW HISTOGRAM
  7686  
  7687  // %Help: SHOW BACKUP - list backup contents
  7688  // %Category: CCL
  7689  // %Text: SHOW BACKUP [SCHEMAS|FILES|RANGES] <location>
  7690  // %SeeAlso: WEBDOCS/show-backup.html
  7691  show_backup_stmt:
  7692    SHOW BACKUPS IN string_or_placeholder_opt_list
  7693   {
  7694      $$.val = &tree.ShowBackup{
  7695        InCollection:    $4.stringOrPlaceholderOptList(),
  7696      }
  7697    }
  7698  | SHOW BACKUP show_backup_details FROM string_or_placeholder IN string_or_placeholder_opt_list opt_with_show_backup_options
  7699  	{
  7700  		$$.val = &tree.ShowBackup{
  7701  			From:    true,
  7702  			Details:    $3.showBackupDetails(),
  7703  			Path:    $5.expr(),
  7704  			InCollection: $7.stringOrPlaceholderOptList(),
  7705  			Options: *$8.showBackupOptions(),
  7706  		}
  7707  	}
  7708  | SHOW BACKUP string_or_placeholder IN string_or_placeholder_opt_list opt_with_show_backup_options
  7709  	{
  7710  		$$.val = &tree.ShowBackup{
  7711  			Details:  tree.BackupDefaultDetails,
  7712  			Path:    $3.expr(),
  7713  			InCollection: $5.stringOrPlaceholderOptList(),
  7714  			Options: *$6.showBackupOptions(),
  7715  		}
  7716  	}
  7717  | SHOW BACKUP string_or_placeholder opt_with_show_backup_options
  7718  	{
  7719  		$$.val = &tree.ShowBackup{
  7720  		  Details:  tree.BackupDefaultDetails,
  7721  			Path:    $3.expr(),
  7722  			Options: *$4.showBackupOptions(),
  7723  		}
  7724  	}
  7725  | SHOW BACKUP SCHEMAS string_or_placeholder opt_with_show_backup_options
  7726  	{
  7727  		$$.val = &tree.ShowBackup{
  7728  		  Details:  tree.BackupSchemaDetails,
  7729  			Path:    $4.expr(),
  7730  			Options: *$5.showBackupOptions(),
  7731  		}
  7732  	}
  7733  | SHOW BACKUP FILES string_or_placeholder opt_with_show_backup_options
  7734  	{
  7735  		$$.val = &tree.ShowBackup{
  7736  		  Details:  tree.BackupFileDetails,
  7737  			Path:    $4.expr(),
  7738  			Options: *$5.showBackupOptions(),
  7739  		}
  7740  	}
  7741  | SHOW BACKUP RANGES string_or_placeholder opt_with_show_backup_options
  7742  	{
  7743  		$$.val = &tree.ShowBackup{
  7744  		  Details:  tree.BackupRangeDetails,
  7745  			Path:    $4.expr(),
  7746  			Options: *$5.showBackupOptions(),
  7747  		}
  7748  	}
  7749  | SHOW BACKUP VALIDATE string_or_placeholder opt_with_show_backup_options
  7750    	{
  7751    		$$.val = &tree.ShowBackup{
  7752    		  Details:  tree.BackupValidateDetails,
  7753    			Path:    $4.expr(),
  7754    			Options: *$5.showBackupOptions(),
  7755    		}
  7756    	}
  7757  | SHOW BACKUP CONNECTION string_or_placeholder opt_with_show_backup_connection_options_list
  7758    	{
  7759    		$$.val = &tree.ShowBackup{
  7760    		  Details:  tree.BackupConnectionTest,
  7761    			Path:    $4.expr(),
  7762    			Options: *$5.showBackupOptions(),
  7763    		}
  7764    	}
  7765  | SHOW BACKUP error // SHOW HELP: SHOW BACKUP
  7766  
  7767  show_backup_details:
  7768    /* EMPTY -- default */
  7769    {
  7770      $$.val = tree.BackupDefaultDetails
  7771    }
  7772  | SCHEMAS
  7773    {
  7774      $$.val = tree.BackupSchemaDetails
  7775    }
  7776  | FILES
  7777  	{
  7778  	$$.val = tree.BackupFileDetails
  7779  	}
  7780  | RANGES
  7781  	{
  7782  	$$.val = tree.BackupRangeDetails
  7783  	}
  7784  | VALIDATE
  7785  	{
  7786  	$$.val = tree.BackupValidateDetails
  7787  	}
  7788  
  7789  opt_with_show_backup_options:
  7790    WITH show_backup_options_list
  7791    {
  7792      $$.val = $2.showBackupOptions()
  7793    }
  7794  | WITH OPTIONS '(' show_backup_options_list ')'
  7795    {
  7796      $$.val = $4.showBackupOptions()
  7797    }
  7798  | /* EMPTY */
  7799    {
  7800      $$.val = &tree.ShowBackupOptions{}
  7801    }
  7802  
  7803  show_backup_options_list:
  7804    // Require at least one option
  7805    show_backup_options
  7806    {
  7807      $$.val = $1.showBackupOptions()
  7808    }
  7809  | show_backup_options_list ',' show_backup_options
  7810    {
  7811      if err := $1.showBackupOptions().CombineWith($3.showBackupOptions()); err != nil {
  7812        return setErr(sqllex, err)
  7813      }
  7814    }
  7815  
  7816  show_backup_options:
  7817   AS_JSON
  7818   {
  7819   $$.val = &tree.ShowBackupOptions{AsJson: true}
  7820   }
  7821   | CHECK_FILES
  7822   {
  7823   $$.val = &tree.ShowBackupOptions{CheckFiles: true}
  7824   }
  7825   | SKIP SIZE
  7826   {
  7827   $$.val = &tree.ShowBackupOptions{SkipSize: true}
  7828   }
  7829   | NOWAIT
  7830   {
  7831   /* SKIP DOC */
  7832   $$.val = &tree.ShowBackupOptions{SkipSize: true}
  7833   }
  7834   | DEBUG_IDS
  7835   {
  7836   $$.val = &tree.ShowBackupOptions{DebugIDs: true}
  7837   }
  7838   | INCREMENTAL_LOCATION '=' string_or_placeholder_opt_list
  7839   {
  7840   $$.val = &tree.ShowBackupOptions{IncrementalStorage: $3.stringOrPlaceholderOptList()}
  7841   }
  7842   | KMS '=' string_or_placeholder_opt_list
  7843   {
  7844   $$.val = &tree.ShowBackupOptions{DecryptionKMSURI: $3.stringOrPlaceholderOptList()}
  7845   }
  7846   | ENCRYPTION_PASSPHRASE '=' string_or_placeholder
  7847   {
  7848   $$.val = &tree.ShowBackupOptions{EncryptionPassphrase: $3.expr()}
  7849   }
  7850   | PRIVILEGES
  7851   {
  7852   $$.val = &tree.ShowBackupOptions{Privileges: true}
  7853   }
  7854   | ENCRYPTION_INFO_DIR '=' string_or_placeholder
  7855   {
  7856   $$.val = &tree.ShowBackupOptions{EncryptionInfoDir: $3.expr()}
  7857   }
  7858   | DEBUG_DUMP_METADATA_SST
  7859   {
  7860   $$.val = &tree.ShowBackupOptions{DebugMetadataSST: true}
  7861   }
  7862  
  7863  opt_with_show_backup_connection_options_list:
  7864    WITH show_backup_connection_options_list
  7865    {
  7866      $$.val = $2.showBackupOptions()
  7867    }
  7868  | WITH OPTIONS '(' show_backup_connection_options_list ')'
  7869    {
  7870      $$.val = $4.showBackupOptions()
  7871    }
  7872  | /* EMPTY */
  7873    {
  7874      $$.val = &tree.ShowBackupOptions{}
  7875    }
  7876  
  7877  show_backup_connection_options_list:
  7878    // Require at least one option
  7879    show_backup_connection_options
  7880    {
  7881      $$.val = $1.showBackupOptions()
  7882    }
  7883  | show_backup_connection_options_list ',' show_backup_connection_options
  7884    {
  7885      if err := $1.showBackupOptions().CombineWith($3.showBackupOptions()); err != nil {
  7886        return setErr(sqllex, err)
  7887      }
  7888    }
  7889  
  7890  show_backup_connection_options:
  7891    TRANSFER '=' string_or_placeholder
  7892   {
  7893    $$.val = &tree.ShowBackupOptions{CheckConnectionTransferSize: $3.expr()}
  7894   }
  7895   | TIME '=' string_or_placeholder
  7896   {
  7897    $$.val = &tree.ShowBackupOptions{CheckConnectionDuration: $3.expr()}
  7898   }
  7899   | CONCURRENTLY '=' a_expr
  7900   {
  7901    $$.val = &tree.ShowBackupOptions{CheckConnectionConcurrency: $3.expr()}
  7902   }
  7903  
  7904  // %Help: SHOW CLUSTER SETTING - display cluster settings
  7905  // %Category: Cfg
  7906  // %Text:
  7907  // SHOW CLUSTER SETTING <var> [ FOR VIRTUAL CLUSTER <virtual_cluster_spec> ]
  7908  // SHOW [ PUBLIC | ALL ] CLUSTER SETTINGS [ FOR VIRTUAL CLUSTER <virtual_cluster_spec> ]
  7909  // %SeeAlso: WEBDOCS/cluster-settings.html
  7910  show_csettings_stmt:
  7911    SHOW CLUSTER SETTING var_name
  7912    {
  7913      $$.val = &tree.ShowClusterSetting{Name: strings.Join($4.strs(), ".")}
  7914    }
  7915  | SHOW CLUSTER SETTING ALL
  7916    {
  7917      $$.val = &tree.ShowClusterSettingList{All: true}
  7918    }
  7919  | SHOW CLUSTER error // SHOW HELP: SHOW CLUSTER SETTING
  7920  | SHOW ALL CLUSTER SETTINGS
  7921    {
  7922      $$.val = &tree.ShowClusterSettingList{All: true}
  7923    }
  7924  | SHOW ALL CLUSTER error // SHOW HELP: SHOW CLUSTER SETTING
  7925  | SHOW CLUSTER SETTINGS
  7926    {
  7927      $$.val = &tree.ShowClusterSettingList{}
  7928    }
  7929  | SHOW PUBLIC CLUSTER SETTINGS
  7930    {
  7931      $$.val = &tree.ShowClusterSettingList{}
  7932    }
  7933  | SHOW PUBLIC CLUSTER error // SHOW HELP: SHOW CLUSTER SETTING
  7934  
  7935  show_local_or_virtual_cluster_csettings_stmt:
  7936    show_csettings_stmt
  7937    {
  7938      /* SKIP DOC */
  7939      $$.val = $1.stmt()
  7940    }
  7941  | show_csettings_stmt FOR virtual_cluster virtual_cluster_spec
  7942    {
  7943      /* SKIP DOC */
  7944      switch t := $1.stmt().(type) {
  7945      case *tree.ShowClusterSetting:
  7946         $$.val = &tree.ShowTenantClusterSetting{
  7947            ShowClusterSetting: t,
  7948            TenantSpec: $4.tenantSpec(),
  7949         }
  7950      case *tree.ShowClusterSettingList:
  7951         $$.val = &tree.ShowTenantClusterSettingList{
  7952            ShowClusterSettingList: t,
  7953            TenantSpec: $4.tenantSpec(),
  7954         }
  7955      }
  7956    }
  7957  | show_csettings_stmt FOR virtual_cluster error // SHOW HELP: SHOW CLUSTER SETTING
  7958  
  7959  // %Help: SHOW COLUMNS - list columns in relation
  7960  // %Category: DDL
  7961  // %Text: SHOW COLUMNS FROM <tablename>
  7962  // %SeeAlso: WEBDOCS/show-columns.html
  7963  show_columns_stmt:
  7964    SHOW COLUMNS FROM table_name with_comment
  7965    {
  7966      $$.val = &tree.ShowColumns{Table: $4.unresolvedObjectName(), WithComment: $5.bool()}
  7967    }
  7968  | SHOW COLUMNS error // SHOW HELP: SHOW COLUMNS
  7969  
  7970  // %Help: SHOW PARTITIONS - list partition information
  7971  // %Category: DDL
  7972  // %Text: SHOW PARTITIONS FROM { TABLE <table> | INDEX <index> | DATABASE <database> }
  7973  // %SeeAlso: WEBDOCS/show-partitions.html
  7974  show_partitions_stmt:
  7975    SHOW PARTITIONS FROM TABLE table_name
  7976    {
  7977      $$.val = &tree.ShowPartitions{IsTable: true, Table: $5.unresolvedObjectName()}
  7978    }
  7979  | SHOW PARTITIONS FROM DATABASE database_name
  7980    {
  7981      $$.val = &tree.ShowPartitions{IsDB: true, Database: tree.Name($5)}
  7982    }
  7983  | SHOW PARTITIONS FROM INDEX table_index_name
  7984    {
  7985      $$.val = &tree.ShowPartitions{IsIndex: true, Index: $5.tableIndexName()}
  7986    }
  7987  | SHOW PARTITIONS FROM INDEX table_name '@' '*'
  7988    {
  7989      $$.val = &tree.ShowPartitions{IsTable: true, Table: $5.unresolvedObjectName()}
  7990    }
  7991  | SHOW PARTITIONS error // SHOW HELP: SHOW PARTITIONS
  7992  
  7993  // %Help: SHOW DATABASES - list databases
  7994  // %Category: DDL
  7995  // %Text: SHOW DATABASES
  7996  // %SeeAlso: WEBDOCS/show-databases.html
  7997  show_databases_stmt:
  7998    SHOW DATABASES with_comment
  7999    {
  8000      $$.val = &tree.ShowDatabases{WithComment: $3.bool()}
  8001    }
  8002  | SHOW DATABASES error // SHOW HELP: SHOW DATABASES
  8003  
  8004  // %Help: SHOW DEFAULT PRIVILEGES - list default privileges
  8005  // %Category: DDL
  8006  // %Text: SHOW DEFAULT PRIVILEGES
  8007  // %SeeAlso: WEBDOCS/show-default-privileges
  8008  show_default_privileges_stmt:
  8009    SHOW DEFAULT PRIVILEGES opt_for_roles opt_in_schema {
  8010      $$.val = &tree.ShowDefaultPrivileges{
  8011        Roles: $4.roleSpecList(),
  8012        Schema: tree.Name($5),
  8013      }
  8014    }
  8015  | SHOW DEFAULT PRIVILEGES FOR GRANTEE role_spec_list opt_in_schema {
  8016      $$.val = &tree.ShowDefaultPrivileges{
  8017        Roles: $6.roleSpecList(),
  8018        ForGrantee: true,
  8019        Schema: tree.Name($7),
  8020      }
  8021    }
  8022  | SHOW DEFAULT PRIVILEGES FOR ALL ROLES opt_in_schema {
  8023      $$.val = &tree.ShowDefaultPrivileges{
  8024        ForAllRoles: true,
  8025        Schema: tree.Name($7),
  8026      }
  8027    }
  8028  | SHOW DEFAULT PRIVILEGES error // SHOW HELP: SHOW DEFAULT PRIVILEGES
  8029  
  8030  // %Help: SHOW ENUMS - list enums
  8031  // %Category: Misc
  8032  // %Text: SHOW ENUMS
  8033  show_enums_stmt:
  8034    SHOW ENUMS
  8035    {
  8036      $$.val = &tree.ShowEnums{}
  8037    }
  8038  | SHOW ENUMS FROM name '.' name
  8039    {
  8040      $$.val = &tree.ShowEnums{ObjectNamePrefix:tree.ObjectNamePrefix{
  8041          CatalogName: tree.Name($4),
  8042          ExplicitCatalog: true,
  8043          SchemaName: tree.Name($6),
  8044          ExplicitSchema: true,
  8045        },
  8046      }
  8047    }
  8048  | SHOW ENUMS FROM name
  8049  {
  8050      $$.val = &tree.ShowEnums{ObjectNamePrefix:tree.ObjectNamePrefix{
  8051          // Note: the schema name may be interpreted as database name,
  8052          // see name_resolution.go.
  8053          SchemaName: tree.Name($4),
  8054          ExplicitSchema: true,
  8055        },
  8056      }
  8057  }
  8058  | SHOW ENUMS error // SHOW HELP: SHOW ENUMS
  8059  
  8060  // %Help: SHOW TYPES - list user defined types
  8061  // %Category: Misc
  8062  // %Text: SHOW TYPES
  8063  show_types_stmt:
  8064    SHOW TYPES
  8065    {
  8066      $$.val = &tree.ShowTypes{}
  8067    }
  8068  | SHOW TYPES error // SHOW HELP: SHOW TYPES
  8069  
  8070  // %Help: SHOW GRANTS - list grants
  8071  // %Category: Priv
  8072  // %Text:
  8073  // Show privilege grants:
  8074  //   SHOW GRANTS [ON <targets...>] [FOR <users...>]
  8075  // Show role grants:
  8076  //   SHOW GRANTS ON ROLE [<roles...>] [FOR <grantees...>]
  8077  //
  8078  // %SeeAlso: WEBDOCS/show-grants.html
  8079  show_grants_stmt:
  8080    SHOW GRANTS opt_on_targets_roles for_grantee_clause
  8081    {
  8082      lst := $3.grantTargetListPtr()
  8083      if lst != nil && lst.ForRoles {
  8084        $$.val = &tree.ShowRoleGrants{Roles: lst.Roles, Grantees: $4.roleSpecList()}
  8085      } else {
  8086        $$.val = &tree.ShowGrants{Targets: lst, Grantees: $4.roleSpecList()}
  8087      }
  8088    }
  8089  | SHOW SYSTEM GRANTS for_grantee_clause
  8090    {
  8091      $$.val = &tree.ShowGrants{
  8092        Targets: &tree.GrantTargetList{System: true},
  8093          Grantees: $4.roleSpecList(),
  8094        }
  8095    }
  8096  | SHOW GRANTS error // SHOW HELP: SHOW GRANTS
  8097  
  8098  // %Help: SHOW INDEXES - list indexes
  8099  // %Category: DDL
  8100  // %Text: SHOW INDEXES FROM { <tablename> | DATABASE <database_name> } [WITH COMMENT]
  8101  // %SeeAlso: WEBDOCS/show-index.html
  8102  show_indexes_stmt:
  8103    SHOW INDEX FROM table_name with_comment
  8104    {
  8105      $$.val = &tree.ShowIndexes{Table: $4.unresolvedObjectName(), WithComment: $5.bool()}
  8106    }
  8107  | SHOW INDEX error // SHOW HELP: SHOW INDEXES
  8108  | SHOW INDEX FROM DATABASE database_name with_comment
  8109    {
  8110      $$.val = &tree.ShowDatabaseIndexes{Database: tree.Name($5), WithComment: $6.bool()}
  8111    }
  8112  | SHOW INDEXES FROM table_name with_comment
  8113    {
  8114      $$.val = &tree.ShowIndexes{Table: $4.unresolvedObjectName(), WithComment: $5.bool()}
  8115    }
  8116  | SHOW INDEXES FROM DATABASE database_name with_comment
  8117    {
  8118      $$.val = &tree.ShowDatabaseIndexes{Database: tree.Name($5), WithComment: $6.bool()}
  8119    }
  8120  | SHOW INDEXES error // SHOW HELP: SHOW INDEXES
  8121  | SHOW KEYS FROM table_name with_comment
  8122    {
  8123      $$.val = &tree.ShowIndexes{Table: $4.unresolvedObjectName(), WithComment: $5.bool()}
  8124    }
  8125  | SHOW KEYS FROM DATABASE database_name with_comment
  8126    {
  8127      $$.val = &tree.ShowDatabaseIndexes{Database: tree.Name($5), WithComment: $6.bool()}
  8128    }
  8129  | SHOW KEYS error // SHOW HELP: SHOW INDEXES
  8130  
  8131  // %Help: SHOW COMMIT TIMESTAMP - show timestamp commit timestamp of last transaction
  8132  // %Category: Misc
  8133  // %Text: SHOW COMMIT TIMESTAMP
  8134  //
  8135  // Shows the commit timestamp of the last committed transaction if not currently
  8136  // in a transaction. If currently in a transaction, implicitly commits the
  8137  // transaction, returning any errors which may have occurred during the commit.
  8138  // The transaction state will remain open from the perspective of the client,
  8139  // meaning that a COMMIT must be issued to move the connection back to a state
  8140  // where new statements may be issued.
  8141  show_commit_timestamp_stmt:
  8142    SHOW COMMIT TIMESTAMP
  8143    {
  8144      $$.val = &tree.ShowCommitTimestamp{}
  8145    }
  8146  
  8147  // %Help: SHOW CONSTRAINTS - list constraints
  8148  // %Category: DDL
  8149  // %Text: SHOW CONSTRAINTS FROM <tablename>
  8150  // %SeeAlso: WEBDOCS/show-constraints.html
  8151  show_constraints_stmt:
  8152    SHOW CONSTRAINT FROM table_name with_comment
  8153    {
  8154      $$.val = &tree.ShowConstraints{Table: $4.unresolvedObjectName(), WithComment: $5.bool()}
  8155    }
  8156  | SHOW CONSTRAINT error // SHOW HELP: SHOW CONSTRAINTS
  8157  | SHOW CONSTRAINTS FROM table_name with_comment
  8158    {
  8159      $$.val = &tree.ShowConstraints{Table: $4.unresolvedObjectName(), WithComment: $5.bool()}
  8160    }
  8161  | SHOW CONSTRAINTS error // SHOW HELP: SHOW CONSTRAINTS
  8162  
  8163  // %Help: SHOW STATEMENTS - list running statements
  8164  // %Category: Misc
  8165  // %Text: SHOW [ALL] [CLUSTER | LOCAL] STATEMENTS
  8166  // %SeeAlso: CANCEL QUERIES
  8167  show_statements_stmt:
  8168    SHOW opt_cluster statements_or_queries
  8169    {
  8170      $$.val = &tree.ShowQueries{All: false, Cluster: $2.bool()}
  8171    }
  8172  | SHOW opt_cluster statements_or_queries error // SHOW HELP: SHOW STATEMENTS
  8173  | SHOW ALL opt_cluster statements_or_queries
  8174    {
  8175      $$.val = &tree.ShowQueries{All: true, Cluster: $3.bool()}
  8176    }
  8177  | SHOW ALL opt_cluster statements_or_queries error // SHOW HELP: SHOW STATEMENTS
  8178  
  8179  opt_cluster:
  8180    /* EMPTY */
  8181    { $$.val = true }
  8182  | CLUSTER
  8183    { $$.val = true }
  8184  | LOCAL
  8185    { $$.val = false }
  8186  
  8187  // SHOW QUERIES is now an alias for SHOW STATEMENTS
  8188  // https://github.com/cockroachdb/cockroach/issues/56240
  8189  statements_or_queries:
  8190    STATEMENTS
  8191  | QUERIES
  8192  
  8193  // %Help: SHOW JOBS - list background jobs
  8194  // %Category: Misc
  8195  // %Text:
  8196  // SHOW [AUTOMATIC | CHANGEFEED] JOBS [select clause] [WITH EXECUTION DETAILS]
  8197  // SHOW JOBS FOR SCHEDULES [select clause]
  8198  // SHOW [CHANGEFEED] JOB <jobid> [WITH EXECUTION DETAILS]
  8199  // %SeeAlso: CANCEL JOBS, PAUSE JOBS, RESUME JOBS
  8200  show_jobs_stmt:
  8201    SHOW AUTOMATIC JOBS
  8202    {
  8203      $$.val = &tree.ShowJobs{Automatic: true}
  8204    }
  8205  | SHOW JOBS
  8206    {
  8207      $$.val = &tree.ShowJobs{
  8208        Automatic: false,
  8209      }
  8210    }
  8211  | SHOW JOBS WITH show_job_options_list
  8212    {
  8213      $$.val = &tree.ShowJobs{
  8214        Automatic: false,
  8215        Options: $4.showJobOptions(),
  8216      }
  8217    }
  8218  | SHOW CHANGEFEED JOBS
  8219    {
  8220      $$.val = &tree.ShowChangefeedJobs{}
  8221    }
  8222  | SHOW AUTOMATIC JOBS error // SHOW HELP: SHOW JOBS
  8223  | SHOW JOBS error // SHOW HELP: SHOW JOBS
  8224  | SHOW CHANGEFEED JOBS error // SHOW HELP: SHOW JOBS
  8225  | SHOW JOBS select_stmt
  8226    {
  8227      $$.val = &tree.ShowJobs{Jobs: $3.slct()}
  8228    }
  8229  | SHOW JOBS select_stmt WITH show_job_options_list
  8230    {
  8231      $$.val = &tree.ShowJobs{
  8232        Jobs: $3.slct(),
  8233        Options: $5.showJobOptions(),
  8234      }
  8235    }
  8236  | SHOW JOBS WHEN COMPLETE select_stmt
  8237    {
  8238      $$.val = &tree.ShowJobs{Jobs: $5.slct(), Block: true}
  8239    }
  8240  | SHOW JOBS for_schedules_clause
  8241    {
  8242      $$.val = &tree.ShowJobs{Schedules: $3.slct()}
  8243    }
  8244  | SHOW CHANGEFEED JOBS select_stmt
  8245    {
  8246      $$.val = &tree.ShowChangefeedJobs{Jobs: $4.slct()}
  8247    }
  8248  | SHOW JOBS select_stmt error // SHOW HELP: SHOW JOBS
  8249  | SHOW JOB a_expr
  8250    {
  8251      $$.val = &tree.ShowJobs{
  8252        Jobs: &tree.Select{
  8253          Select: &tree.ValuesClause{Rows: []tree.Exprs{tree.Exprs{$3.expr()}}},
  8254        },
  8255      }
  8256    }
  8257  | SHOW JOB a_expr WITH show_job_options_list
  8258    {
  8259      $$.val = &tree.ShowJobs{
  8260        Jobs: &tree.Select{
  8261          Select: &tree.ValuesClause{Rows: []tree.Exprs{tree.Exprs{$3.expr()}}},
  8262        },
  8263        Options: $5.showJobOptions(),
  8264      }
  8265    }
  8266  | SHOW CHANGEFEED JOB a_expr
  8267    {
  8268      $$.val = &tree.ShowChangefeedJobs{
  8269        Jobs: &tree.Select{
  8270          Select: &tree.ValuesClause{Rows: []tree.Exprs{tree.Exprs{$4.expr()}}},
  8271        },
  8272      }
  8273    }
  8274  | SHOW JOB WHEN COMPLETE a_expr
  8275    {
  8276      $$.val = &tree.ShowJobs{
  8277        Jobs: &tree.Select{
  8278          Select: &tree.ValuesClause{Rows: []tree.Exprs{tree.Exprs{$5.expr()}}},
  8279        },
  8280        Block: true,
  8281      }
  8282    }
  8283  | SHOW JOB error // SHOW HELP: SHOW JOBS
  8284  | SHOW CHANGEFEED JOB error // SHOW HELP: SHOW JOBS
  8285  
  8286  
  8287  show_job_options_list:
  8288    // Require at least one option
  8289    show_job_options
  8290    {
  8291      $$.val = $1.showJobOptions()
  8292    }
  8293  | show_job_options_list ',' show_job_options
  8294    {
  8295      if err := $1.showJobOptions().CombineWith($3.showJobOptions()); err != nil {
  8296        return setErr(sqllex, err)
  8297      }
  8298    }
  8299  
  8300  // List of valid SHOW JOB options.
  8301  show_job_options:
  8302    EXECUTION DETAILS
  8303    {
  8304      $$.val = &tree.ShowJobOptions{
  8305        ExecutionDetails: true,
  8306      }
  8307    }
  8308  
  8309  // %Help: SHOW SCHEDULES - list periodic schedules
  8310  // %Category: Misc
  8311  // %Text:
  8312  // SHOW [RUNNING | PAUSED] SCHEDULES [FOR BACKUP]
  8313  // SHOW SCHEDULE <schedule_id>
  8314  // %SeeAlso: PAUSE SCHEDULES, RESUME SCHEDULES, DROP SCHEDULES
  8315  show_schedules_stmt:
  8316    SHOW SCHEDULES opt_schedule_executor_type
  8317    {
  8318      $$.val = &tree.ShowSchedules{
  8319        WhichSchedules: tree.SpecifiedSchedules,
  8320        ExecutorType: $3.executorType(),
  8321      }
  8322    }
  8323  | SHOW SCHEDULES opt_schedule_executor_type error // SHOW HELP: SHOW SCHEDULES
  8324  | SHOW schedule_state SCHEDULES opt_schedule_executor_type
  8325    {
  8326      $$.val = &tree.ShowSchedules{
  8327        WhichSchedules: $2.scheduleState(),
  8328        ExecutorType: $4.executorType(),
  8329      }
  8330    }
  8331  | SHOW schedule_state SCHEDULES opt_schedule_executor_type error // SHOW HELP: SHOW SCHEDULES
  8332  | SHOW SCHEDULE a_expr
  8333    {
  8334      $$.val = &tree.ShowSchedules{
  8335        WhichSchedules: tree.SpecifiedSchedules,
  8336        ScheduleID:  $3.expr(),
  8337      }
  8338    }
  8339  | SHOW SCHEDULE error  // SHOW HELP: SHOW SCHEDULES
  8340  
  8341  schedule_state:
  8342    RUNNING
  8343    {
  8344      $$.val = tree.ActiveSchedules
  8345    }
  8346  | PAUSED
  8347    {
  8348      $$.val = tree.PausedSchedules
  8349    }
  8350  
  8351  opt_schedule_executor_type:
  8352    /* Empty */
  8353    {
  8354      $$.val = tree.InvalidExecutor
  8355    }
  8356  | FOR BACKUP
  8357    {
  8358      $$.val = tree.ScheduledBackupExecutor
  8359    }
  8360  | FOR SQL STATISTICS
  8361    {
  8362      $$.val = tree.ScheduledSQLStatsCompactionExecutor
  8363    }
  8364  | FOR CHANGEFEED
  8365  	{
  8366  		$$.val = tree.ScheduledChangefeedExecutor
  8367  	}
  8368  
  8369  // %Help: SHOW TRACE - display an execution trace
  8370  // %Category: Misc
  8371  // %Text:
  8372  // SHOW [COMPACT] [KV] TRACE FOR SESSION
  8373  // %SeeAlso: EXPLAIN
  8374  show_trace_stmt:
  8375    SHOW opt_compact TRACE FOR SESSION
  8376    {
  8377      $$.val = &tree.ShowTraceForSession{TraceType: tree.ShowTraceRaw, Compact: $2.bool()}
  8378    }
  8379  | SHOW opt_compact TRACE error // SHOW HELP: SHOW TRACE
  8380  | SHOW opt_compact KV TRACE FOR SESSION
  8381    {
  8382      $$.val = &tree.ShowTraceForSession{TraceType: tree.ShowTraceKV, Compact: $2.bool()}
  8383    }
  8384  | SHOW opt_compact KV error // SHOW HELP: SHOW TRACE
  8385  | SHOW opt_compact EXPERIMENTAL_REPLICA TRACE FOR SESSION
  8386    {
  8387      /* SKIP DOC */
  8388      $$.val = &tree.ShowTraceForSession{TraceType: tree.ShowTraceReplica, Compact: $2.bool()}
  8389    }
  8390  | SHOW opt_compact EXPERIMENTAL_REPLICA error // SHOW HELP: SHOW TRACE
  8391  
  8392  opt_compact:
  8393    COMPACT { $$.val = true }
  8394  | /* EMPTY */ { $$.val = false }
  8395  
  8396  // %Help: SHOW SESSIONS - list open client sessions
  8397  // %Category: Misc
  8398  // %Text: SHOW [ALL] [CLUSTER | LOCAL] SESSIONS
  8399  // %SeeAlso: CANCEL SESSIONS
  8400  show_sessions_stmt:
  8401    SHOW opt_cluster SESSIONS
  8402    {
  8403      $$.val = &tree.ShowSessions{Cluster: $2.bool()}
  8404    }
  8405  | SHOW opt_cluster SESSIONS error // SHOW HELP: SHOW SESSIONS
  8406  | SHOW ALL opt_cluster SESSIONS
  8407    {
  8408      $$.val = &tree.ShowSessions{All: true, Cluster: $3.bool()}
  8409    }
  8410  | SHOW ALL opt_cluster SESSIONS error // SHOW HELP: SHOW SESSIONS
  8411  
  8412  // %Help: SHOW TABLES - list tables
  8413  // %Category: DDL
  8414  // %Text: SHOW TABLES [FROM <databasename> [ . <schemaname> ] ] [WITH COMMENT]
  8415  // %SeeAlso: WEBDOCS/show-tables.html
  8416  show_tables_stmt:
  8417    SHOW TABLES FROM name '.' name with_comment
  8418    {
  8419      $$.val = &tree.ShowTables{ObjectNamePrefix:tree.ObjectNamePrefix{
  8420          CatalogName: tree.Name($4),
  8421          ExplicitCatalog: true,
  8422          SchemaName: tree.Name($6),
  8423          ExplicitSchema: true,
  8424      },
  8425      WithComment: $7.bool()}
  8426    }
  8427  | SHOW TABLES FROM name with_comment
  8428    {
  8429      $$.val = &tree.ShowTables{ObjectNamePrefix:tree.ObjectNamePrefix{
  8430          // Note: the schema name may be interpreted as database name,
  8431          // see name_resolution.go.
  8432          SchemaName: tree.Name($4),
  8433          ExplicitSchema: true,
  8434      },
  8435      WithComment: $5.bool()}
  8436    }
  8437  | SHOW TABLES with_comment
  8438    {
  8439      $$.val = &tree.ShowTables{WithComment: $3.bool()}
  8440    }
  8441  | SHOW TABLES error // SHOW HELP: SHOW TABLES
  8442  
  8443  // %Help: SHOW FUNCTIONS - list functions
  8444  // %Category: DDL
  8445  // %Text: SHOW FUNCTIONS [FROM <databasename> [ . <schemaname> ] ]
  8446  show_functions_stmt:
  8447    SHOW FUNCTIONS FROM name '.' name
  8448    {
  8449      $$.val = &tree.ShowRoutines{ObjectNamePrefix:tree.ObjectNamePrefix{
  8450          CatalogName: tree.Name($4),
  8451          ExplicitCatalog: true,
  8452          SchemaName: tree.Name($6),
  8453          ExplicitSchema: true,
  8454      }}
  8455    }
  8456  | SHOW FUNCTIONS FROM name
  8457    {
  8458      $$.val = &tree.ShowRoutines{ObjectNamePrefix:tree.ObjectNamePrefix{
  8459          // Note: the schema name may be interpreted as database name,
  8460          // see name_resolution.go.
  8461          SchemaName: tree.Name($4),
  8462          ExplicitSchema: true,
  8463      }}
  8464    }
  8465  | SHOW FUNCTIONS
  8466    {
  8467      $$.val = &tree.ShowRoutines{}
  8468    }
  8469  | SHOW FUNCTIONS error // SHOW HELP: SHOW FUNCTIONS
  8470  
  8471  // %Help: SHOW PROCEDURES - list procedures
  8472  // %Category: DDL
  8473  // %Text: SHOW PROCEDURES [FROM <databasename> [ . <schemaname> ] ]
  8474  show_procedures_stmt:
  8475    SHOW PROCEDURES FROM name '.' name
  8476    {
  8477      $$.val = &tree.ShowRoutines{ObjectNamePrefix:tree.ObjectNamePrefix{
  8478          CatalogName: tree.Name($4),
  8479          ExplicitCatalog: true,
  8480          SchemaName: tree.Name($6),
  8481          ExplicitSchema: true,
  8482      }, Procedure: true}
  8483    }
  8484  | SHOW PROCEDURES FROM name
  8485    {
  8486      $$.val = &tree.ShowRoutines{ObjectNamePrefix:tree.ObjectNamePrefix{
  8487          // Note: the schema name may be interpreted as database name,
  8488          // see name_resolution.go.
  8489          SchemaName: tree.Name($4),
  8490          ExplicitSchema: true,
  8491      }, Procedure: true}
  8492    }
  8493  | SHOW PROCEDURES
  8494    {
  8495      $$.val = &tree.ShowRoutines{Procedure: true}
  8496    }
  8497  | SHOW PROCEDURES error // SHOW HELP: SHOW PROCEDURES
  8498  
  8499  // %Help: SHOW TRANSACTIONS - list open client transactions across the cluster
  8500  // %Category: Misc
  8501  // %Text: SHOW [ALL] [CLUSTER | LOCAL] TRANSACTIONS
  8502  show_transactions_stmt:
  8503    SHOW opt_cluster TRANSACTIONS
  8504    {
  8505      $$.val = &tree.ShowTransactions{Cluster: $2.bool()}
  8506    }
  8507  | SHOW opt_cluster TRANSACTIONS error // SHOW HELP: SHOW TRANSACTIONS
  8508  | SHOW ALL opt_cluster TRANSACTIONS
  8509    {
  8510      $$.val = &tree.ShowTransactions{All: true, Cluster: $3.bool()}
  8511    }
  8512  | SHOW ALL opt_cluster TRANSACTIONS error // SHOW HELP: SHOW TRANSACTIONS
  8513  
  8514  with_comment:
  8515    WITH COMMENT { $$.val = true }
  8516  | /* EMPTY */  { $$.val = false }
  8517  
  8518  // %Help: SHOW SCHEMAS - list schemas
  8519  // %Category: DDL
  8520  // %Text: SHOW SCHEMAS [FROM <databasename> ]
  8521  show_schemas_stmt:
  8522    SHOW SCHEMAS FROM name
  8523    {
  8524      $$.val = &tree.ShowSchemas{Database: tree.Name($4)}
  8525    }
  8526  | SHOW SCHEMAS
  8527    {
  8528      $$.val = &tree.ShowSchemas{}
  8529    }
  8530  | SHOW SCHEMAS error // SHOW HELP: SHOW SCHEMAS
  8531  
  8532  // %Help: SHOW SEQUENCES - list sequences
  8533  // %Category: DDL
  8534  // %Text: SHOW SEQUENCES [FROM <databasename> ]
  8535  show_sequences_stmt:
  8536    SHOW SEQUENCES FROM name
  8537    {
  8538      $$.val = &tree.ShowSequences{Database: tree.Name($4)}
  8539    }
  8540  | SHOW SEQUENCES
  8541    {
  8542      $$.val = &tree.ShowSequences{}
  8543    }
  8544  | SHOW SEQUENCES error // SHOW HELP: SHOW SEQUENCES
  8545  
  8546  // %Help: SHOW SYNTAX - analyze SQL syntax
  8547  // %Category: Misc
  8548  // %Text: SHOW SYNTAX <string>
  8549  show_syntax_stmt:
  8550    SHOW SYNTAX SCONST
  8551    {
  8552      /* SKIP DOC */
  8553      $$.val = &tree.ShowSyntax{Statement: $3}
  8554    }
  8555  | SHOW SYNTAX error // SHOW HELP: SHOW SYNTAX
  8556  
  8557  show_completions_stmt:
  8558    SHOW COMPLETIONS AT OFFSET ICONST FOR SCONST
  8559    {
  8560      /* SKIP DOC */
  8561      $$.val = &tree.ShowCompletions{
  8562          Statement: tree.NewStrVal($7),
  8563          Offset: $5.numVal(),
  8564      }
  8565    }
  8566  
  8567  show_last_query_stats_stmt:
  8568    SHOW LAST QUERY STATISTICS query_stats_cols
  8569    {
  8570     /* SKIP DOC */
  8571     $$.val = &tree.ShowLastQueryStatistics{Columns: $5.nameList()}
  8572    }
  8573  
  8574  query_stats_cols:
  8575    RETURNING name_list
  8576    {
  8577      $$.val = $2.nameList()
  8578    }
  8579  | /* EMPTY */
  8580    {
  8581      // Note: the form that does not specify the RETURNING clause is deprecated.
  8582      // Remove it when there are no more clients using it (22.1 or later).
  8583      $$.val = tree.ShowLastQueryStatisticsDefaultColumns
  8584    }
  8585  
  8586  // %Help: SHOW SAVEPOINT - display current savepoint properties
  8587  // %Category: Cfg
  8588  // %Text: SHOW SAVEPOINT STATUS
  8589  show_savepoint_stmt:
  8590    SHOW SAVEPOINT STATUS
  8591    {
  8592      $$.val = &tree.ShowSavepointStatus{}
  8593    }
  8594  | SHOW SAVEPOINT error // SHOW HELP: SHOW SAVEPOINT
  8595  
  8596  // %Help: SHOW TRANSACTION - display current transaction properties
  8597  // %Category: Cfg
  8598  // %Text: SHOW TRANSACTION {ISOLATION LEVEL | PRIORITY | STATUS}
  8599  // %SeeAlso: WEBDOCS/show-vars.html
  8600  show_transaction_stmt:
  8601    SHOW TRANSACTION ISOLATION LEVEL
  8602    {
  8603      /* SKIP DOC */
  8604      $$.val = &tree.ShowVar{Name: "transaction_isolation"}
  8605    }
  8606  | SHOW TRANSACTION PRIORITY
  8607    {
  8608      /* SKIP DOC */
  8609      $$.val = &tree.ShowVar{Name: "transaction_priority"}
  8610    }
  8611  | SHOW TRANSACTION STATUS
  8612    {
  8613      /* SKIP DOC */
  8614      $$.val = &tree.ShowTransactionStatus{}
  8615    }
  8616  | SHOW TRANSACTION error // SHOW HELP: SHOW TRANSACTION
  8617  
  8618  // %Help: SHOW TRANSFER - display session state for connection migration
  8619  // %Category: Misc
  8620  // %Text: SHOW TRANSFER STATE [ WITH '<transfer_key>' ]
  8621  show_transfer_stmt:
  8622    SHOW TRANSFER STATE WITH SCONST
  8623    {
  8624       $$.val = &tree.ShowTransferState{TransferKey: tree.NewStrVal($5)}
  8625    }
  8626  | SHOW TRANSFER STATE
  8627    {
  8628       $$.val = &tree.ShowTransferState{}
  8629    }
  8630  | SHOW TRANSFER error // SHOW HELP: SHOW TRANSFER
  8631  
  8632  // %Help: SHOW CREATE - display the CREATE statement for a table, sequence, view, or database
  8633  // %Category: DDL
  8634  // %Text:
  8635  // SHOW CREATE [ TABLE | SEQUENCE | VIEW | DATABASE ] <object_name>
  8636  // SHOW CREATE [ SECONDARY ] INDEXES FROM <table_name>
  8637  // SHOW CREATE ALL SCHEMAS
  8638  // SHOW CREATE ALL TABLES
  8639  // SHOW CREATE ALL TYPES
  8640  // %SeeAlso: WEBDOCS/show-create.html
  8641  show_create_stmt:
  8642    SHOW CREATE table_name opt_show_create_format_options
  8643    {
  8644      $$.val = &tree.ShowCreate{
  8645        Name: $3.unresolvedObjectName(), FmtOpt: $4.showCreateFormatOption(),
  8646      }
  8647    }
  8648  | SHOW CREATE TABLE table_name opt_show_create_format_options
  8649    {
  8650      /* SKIP DOC */
  8651      $$.val = &tree.ShowCreate{
  8652        Mode: tree.ShowCreateModeTable,
  8653        Name: $4.unresolvedObjectName(),
  8654        FmtOpt: $5.showCreateFormatOption(),
  8655      }
  8656    }
  8657  | SHOW CREATE VIEW table_name opt_show_create_format_options
  8658    {
  8659      /* SKIP DOC */
  8660      $$.val = &tree.ShowCreate{
  8661        Mode: tree.ShowCreateModeView,
  8662        Name: $4.unresolvedObjectName(),
  8663        FmtOpt: $5.showCreateFormatOption(),
  8664      }
  8665    }
  8666  | SHOW CREATE SEQUENCE sequence_name
  8667    {
  8668      /* SKIP DOC */
  8669      $$.val = &tree.ShowCreate{Mode: tree.ShowCreateModeSequence, Name: $4.unresolvedObjectName()}
  8670    }
  8671  | SHOW CREATE DATABASE db_name
  8672    {
  8673      /* SKIP DOC */
  8674      $$.val = &tree.ShowCreate{Mode: tree.ShowCreateModeDatabase, Name: $4.unresolvedObjectName()}
  8675    }
  8676  | SHOW CREATE INDEXES FROM table_name
  8677    {
  8678      /* SKIP DOC */
  8679      $$.val = &tree.ShowCreate{Mode: tree.ShowCreateModeIndexes, Name: $5.unresolvedObjectName()}
  8680    }
  8681  | SHOW CREATE SECONDARY INDEXES FROM table_name
  8682    {
  8683      /* SKIP DOC */
  8684      $$.val = &tree.ShowCreate{Mode: tree.ShowCreateModeSecondaryIndexes, Name: $6.unresolvedObjectName()}
  8685    }
  8686  | SHOW CREATE FUNCTION db_object_name
  8687    {
  8688      /* SKIP DOC */
  8689      $$.val = &tree.ShowCreateRoutine{
  8690        Name: tree.ResolvableFunctionReference{
  8691          FunctionReference: $4.unresolvedObjectName().ToUnresolvedName(),
  8692        },
  8693      }
  8694    }
  8695  | SHOW CREATE PROCEDURE db_object_name
  8696    {
  8697      /* SKIP DOC */
  8698      $$.val = &tree.ShowCreateRoutine{
  8699        Name: tree.ResolvableFunctionReference{
  8700          FunctionReference: $4.unresolvedObjectName().ToUnresolvedName(),
  8701        },
  8702        Procedure: true,
  8703      }
  8704    }
  8705  | SHOW CREATE ALL SCHEMAS
  8706    {
  8707      $$.val = &tree.ShowCreateAllSchemas{}
  8708    }
  8709  | SHOW CREATE ALL TABLES
  8710    {
  8711      $$.val = &tree.ShowCreateAllTables{}
  8712    }
  8713  | SHOW CREATE ALL TYPES
  8714    {
  8715      $$.val = &tree.ShowCreateAllTypes{}
  8716    }
  8717  | SHOW CREATE error // SHOW HELP: SHOW CREATE
  8718  
  8719  opt_show_create_format_options:
  8720    /* EMPTY */
  8721    {
  8722      $$.val = tree.ShowCreateFormatOptionNone
  8723    }
  8724  | WITH REDACT
  8725    {
  8726      $$.val = tree.ShowCreateFormatOptionRedactedValues
  8727    }
  8728  
  8729  // %Help: SHOW CREATE SCHEDULES - list CREATE statements for scheduled jobs
  8730  // %Category: DDL
  8731  // %Text:
  8732  // SHOW CREATE ALL SCHEDULES
  8733  // SHOW CREATE SCHEDULE <schedule_id>
  8734  // %SeeAlso: SHOW SCHEDULES, PAUSE SCHEDULES, RESUME SCHEDULES, DROP SCHEDULES
  8735  show_create_schedules_stmt:
  8736    SHOW CREATE ALL SCHEDULES
  8737    {
  8738      $$.val = &tree.ShowCreateSchedules{}
  8739    }
  8740  | SHOW CREATE ALL SCHEDULES error // SHOW HELP: SHOW CREATE SCHEDULES
  8741  | SHOW CREATE SCHEDULE a_expr
  8742    {
  8743      $$.val = &tree.ShowCreateSchedules{ScheduleID: $4.expr()}
  8744    }
  8745  | SHOW CREATE SCHEDULE error // SHOW HELP: SHOW CREATE SCHEDULES
  8746  
  8747  // %Help: SHOW CREATE EXTERNAL CONNECTIONS - list CREATE statements for external connections
  8748  // %Category: DDL
  8749  // %Text:
  8750  // SHOW CREATE ALL EXTERNAL CONNECTIONS
  8751  // SHOW CREATE EXTERNAL CONNECTION <connection_name>
  8752  show_create_external_connections_stmt:
  8753    SHOW CREATE ALL EXTERNAL CONNECTIONS
  8754    {
  8755      $$.val = &tree.ShowCreateExternalConnections{}
  8756    }
  8757  | SHOW CREATE ALL EXTERNAL CONNECTIONS error // SHOW HELP: SHOW CREATE EXTERNAL CONNECTIONS
  8758  | SHOW CREATE EXTERNAL CONNECTION string_or_placeholder
  8759   {
  8760     $$.val = &tree.ShowCreateExternalConnections{ConnectionLabel: $5.expr()}
  8761   }
  8762  | SHOW CREATE EXTERNAL CONNECTION error // SHOW HELP: SHOW CREATE EXTERNAL CONNECTIONS
  8763  
  8764  // %Help: SHOW USERS - list defined users
  8765  // %Category: Priv
  8766  // %Text: SHOW USERS
  8767  // %SeeAlso: CREATE USER, DROP USER, WEBDOCS/show-users.html
  8768  show_users_stmt:
  8769    SHOW USERS
  8770    {
  8771      $$.val = &tree.ShowUsers{}
  8772    }
  8773  | SHOW USERS error // SHOW HELP: SHOW USERS
  8774  
  8775  // %Help: SHOW ROLES - list defined roles
  8776  // %Category: Priv
  8777  // %Text: SHOW ROLES
  8778  // %SeeAlso: CREATE ROLE, ALTER ROLE, DROP ROLE
  8779  show_roles_stmt:
  8780    SHOW ROLES
  8781    {
  8782      $$.val = &tree.ShowRoles{}
  8783    }
  8784  | SHOW ROLES error // SHOW HELP: SHOW ROLES
  8785  
  8786  // %Help: SHOW ZONE CONFIGURATION - display current zone configuration
  8787  // %Category: Cfg
  8788  // %Text: SHOW ZONE CONFIGURATION FROM [ RANGE | DATABASE | TABLE | INDEX ] <name>
  8789  // SHOW ZONE CONFIGURATION FROM PARTITION OF [ INDEX | TABLE ] <name>
  8790  // SHOW [ALL] ZONE CONFIGURATIONS
  8791  // %SeeAlso: WEBDOCS/show-zone-configurations.html
  8792  show_zone_stmt:
  8793    SHOW ZONE CONFIGURATION from_with_implicit_for_alias RANGE zone_name
  8794    {
  8795      $$.val = &tree.ShowZoneConfig{ZoneSpecifier: tree.ZoneSpecifier{NamedZone: tree.UnrestrictedName($6)}}
  8796    }
  8797  | SHOW ZONE CONFIGURATION from_with_implicit_for_alias DATABASE database_name
  8798    {
  8799      $$.val = &tree.ShowZoneConfig{ZoneSpecifier: tree.ZoneSpecifier{Database: tree.Name($6)}}
  8800    }
  8801  | SHOW ZONE CONFIGURATION from_with_implicit_for_alias TABLE table_name opt_partition
  8802    {
  8803      name := $6.unresolvedObjectName().ToTableName()
  8804      $$.val = &tree.ShowZoneConfig{ZoneSpecifier: tree.ZoneSpecifier{
  8805          TableOrIndex: tree.TableIndexName{Table: name},
  8806          Partition: tree.Name($7),
  8807      }}
  8808    }
  8809  | SHOW ZONE CONFIGURATION from_with_implicit_for_alias PARTITION partition_name OF TABLE table_name
  8810    {
  8811      name := $9.unresolvedObjectName().ToTableName()
  8812      $$.val = &tree.ShowZoneConfig{ZoneSpecifier: tree.ZoneSpecifier{
  8813        TableOrIndex: tree.TableIndexName{Table: name},
  8814        Partition: tree.Name($6),
  8815      }}
  8816    }
  8817  | SHOW ZONE CONFIGURATION from_with_implicit_for_alias INDEX table_index_name opt_partition
  8818    {
  8819      $$.val = &tree.ShowZoneConfig{ZoneSpecifier: tree.ZoneSpecifier{
  8820        TableOrIndex: $6.tableIndexName(),
  8821        Partition: tree.Name($7),
  8822      }}
  8823    }
  8824  | SHOW ZONE CONFIGURATION from_with_implicit_for_alias PARTITION partition_name OF INDEX table_index_name
  8825    {
  8826      $$.val = &tree.ShowZoneConfig{ZoneSpecifier: tree.ZoneSpecifier{
  8827        TableOrIndex: $9.tableIndexName(),
  8828        Partition: tree.Name($6),
  8829      }}
  8830    }
  8831  | SHOW ZONE CONFIGURATION error // SHOW HELP: SHOW ZONE CONFIGURATION
  8832  | SHOW ZONE CONFIGURATIONS
  8833    {
  8834      $$.val = &tree.ShowZoneConfig{}
  8835    }
  8836  | SHOW ZONE CONFIGURATIONS error // SHOW HELP: SHOW ZONE CONFIGURATION
  8837  | SHOW ALL ZONE CONFIGURATIONS
  8838    {
  8839      $$.val = &tree.ShowZoneConfig{}
  8840    }
  8841  | SHOW ALL ZONE CONFIGURATIONS error // SHOW HELP: SHOW ZONE CONFIGURATION
  8842  
  8843  from_with_implicit_for_alias:
  8844    FROM
  8845  | FOR { /* SKIP DOC */ }
  8846  
  8847  // %Help: SHOW RANGE - show range information for a row
  8848  // %Category: Misc
  8849  // %Text:
  8850  // SHOW RANGE FROM TABLE <tablename> FOR ROW (value1, value2, ...)
  8851  // SHOW RANGE FROM INDEX [ <tablename> @ ] <indexname> FOR ROW (value1, value2, ...)
  8852  show_range_for_row_stmt:
  8853    SHOW RANGE FROM TABLE table_name FOR ROW '(' expr_list ')'
  8854    {
  8855      name := $5.unresolvedObjectName().ToTableName()
  8856      $$.val = &tree.ShowRangeForRow{
  8857        Row: $9.exprs(),
  8858        TableOrIndex: tree.TableIndexName{Table: name},
  8859      }
  8860    }
  8861  | SHOW RANGE FROM INDEX table_index_name FOR ROW '(' expr_list ')'
  8862    {
  8863      $$.val = &tree.ShowRangeForRow{
  8864        Row: $9.exprs(),
  8865        TableOrIndex: $5.tableIndexName(),
  8866      }
  8867    }
  8868  | SHOW RANGE error // SHOW HELP: SHOW RANGE
  8869  
  8870  // %Help: SHOW RANGES - list ranges
  8871  // %Category: Misc
  8872  // %Text:
  8873  // SHOW CLUSTER RANGES                                  [ WITH <options...> ]
  8874  // SHOW RANGES FROM DATABASE <databasename>             [ WITH <options...> ]
  8875  // SHOW RANGES FROM CURRENT_CATALOG                     [ WITH <options...> ]
  8876  // SHOW RANGES FROM TABLE   <tablename>                 [ WITH <options...> ]
  8877  // SHOW RANGES FROM INDEX [ <tablename> @ ] <indexname> [ WITH <options...> ]
  8878  //
  8879  // Options:
  8880  //   INDEXES: list indexes contained per range
  8881  //   TABLES:  list tables contained per range
  8882  //   DETAILS: add range size, leaseholder and other details
  8883  //   KEYS:    include binary start/end keys
  8884  //   EXPLAIN: show the SQL queries that produces the result
  8885  //
  8886  // Note: the availability of some of the options listed above is subject
  8887  // to cluster configuration. See the documentation for details.
  8888  //
  8889  // %SeeAlso: WEBDOCS/show-ranges.html
  8890  show_ranges_stmt:
  8891    SHOW RANGES FROM INDEX table_index_name opt_show_ranges_options
  8892    {
  8893      $$.val = &tree.ShowRanges{Source: tree.ShowRangesIndex, TableOrIndex: $5.tableIndexName(), Options: $6.showRangesOpts()}
  8894    }
  8895  | SHOW RANGES FROM TABLE table_name opt_show_ranges_options
  8896    {
  8897      name := $5.unresolvedObjectName().ToTableName()
  8898      $$.val = &tree.ShowRanges{Source: tree.ShowRangesTable, TableOrIndex: tree.TableIndexName{Table: name}, Options: $6.showRangesOpts()}
  8899    }
  8900  | SHOW RANGES FROM DATABASE database_name opt_show_ranges_options
  8901    {
  8902      $$.val = &tree.ShowRanges{Source: tree.ShowRangesDatabase, DatabaseName: tree.Name($5), Options: $6.showRangesOpts()}
  8903    }
  8904  | SHOW RANGES FROM CURRENT_CATALOG opt_show_ranges_options
  8905    {
  8906      $$.val = &tree.ShowRanges{Source: tree.ShowRangesCurrentDatabase, Options: $5.showRangesOpts()}
  8907    }
  8908  | SHOW RANGES opt_show_ranges_options
  8909    {
  8910      $$.val = &tree.ShowRanges{Source: tree.ShowRangesCurrentDatabase, Options: $3.showRangesOpts()}
  8911    }
  8912  | SHOW RANGES error // SHOW HELP: SHOW RANGES
  8913  | SHOW CLUSTER RANGES opt_show_ranges_options
  8914    {
  8915      $$.val = &tree.ShowRanges{Source: tree.ShowRangesCluster, Options: $4.showRangesOpts()}
  8916    }
  8917  | SHOW CLUSTER RANGES error // SHOW HELP: SHOW RANGES
  8918  
  8919  opt_show_ranges_options:
  8920    /* EMPTY */
  8921    { $$.val = &tree.ShowRangesOptions{} }
  8922  | WITH show_ranges_options
  8923    { $$.val = $2.showRangesOpts() }
  8924  
  8925  show_ranges_options:
  8926    TABLES  {  $$.val = &tree.ShowRangesOptions{Mode: tree.ExpandTables} }
  8927  | INDEXES {  $$.val = &tree.ShowRangesOptions{Mode: tree.ExpandIndexes} }
  8928  | DETAILS {  $$.val = &tree.ShowRangesOptions{Details: true} }
  8929  | KEYS    {  $$.val = &tree.ShowRangesOptions{Keys: true} }
  8930  | EXPLAIN {  $$.val = &tree.ShowRangesOptions{Explain: true} }
  8931  | show_ranges_options ',' TABLES
  8932    {
  8933      o := $1.showRangesOpts()
  8934      if o.Mode != 0 { return setErr(sqllex, errors.New("conflicting modes")) }
  8935      o.Mode = tree.ExpandTables
  8936      $$.val = o
  8937    }
  8938  | show_ranges_options ',' INDEXES
  8939    {
  8940      o := $1.showRangesOpts()
  8941      if o.Mode != 0 { return setErr(sqllex, errors.New("conflicting modes")) }
  8942      o.Mode = tree.ExpandIndexes
  8943      $$.val = o
  8944    }
  8945  | show_ranges_options ',' DETAILS
  8946    {
  8947      o := $1.showRangesOpts()
  8948      o.Details = true
  8949      $$.val = o
  8950    }
  8951  | show_ranges_options ',' EXPLAIN
  8952    {
  8953      o := $1.showRangesOpts()
  8954      o.Explain = true
  8955      $$.val = o
  8956    }
  8957  | show_ranges_options ',' KEYS
  8958    {
  8959      o := $1.showRangesOpts()
  8960      o.Keys = true
  8961      $$.val = o
  8962    }
  8963  
  8964  
  8965  // %Help: SHOW SURVIVAL GOAL - list survival goals
  8966  // %Category: DDL
  8967  // %Text:
  8968  // SHOW SURVIVAL GOAL FROM DATABASE
  8969  // SHOW SURVIVAL GOAL FROM DATABASE <database>
  8970  show_survival_goal_stmt:
  8971    SHOW SURVIVAL GOAL FROM DATABASE
  8972    {
  8973      $$.val = &tree.ShowSurvivalGoal{}
  8974    }
  8975  | SHOW SURVIVAL GOAL FROM DATABASE database_name
  8976    {
  8977      $$.val = &tree.ShowSurvivalGoal{
  8978        DatabaseName: tree.Name($6),
  8979      }
  8980    }
  8981  
  8982  // %Help: SHOW REGIONS - list regions
  8983  // %Category: DDL
  8984  // %Text:
  8985  // SHOW REGIONS
  8986  // SHOW REGIONS FROM ALL DATABASES
  8987  // SHOW REGIONS FROM CLUSTER
  8988  // SHOW REGIONS FROM DATABASE
  8989  // SHOW REGIONS FROM DATABASE <database>
  8990  show_regions_stmt:
  8991    SHOW REGIONS FROM CLUSTER
  8992    {
  8993      $$.val = &tree.ShowRegions{
  8994        ShowRegionsFrom: tree.ShowRegionsFromCluster,
  8995      }
  8996    }
  8997  | SHOW REGIONS FROM DATABASE
  8998    {
  8999      $$.val = &tree.ShowRegions{
  9000        ShowRegionsFrom: tree.ShowRegionsFromDatabase,
  9001      }
  9002    }
  9003  | SHOW REGIONS FROM ALL DATABASES
  9004    {
  9005      $$.val = &tree.ShowRegions{
  9006        ShowRegionsFrom: tree.ShowRegionsFromAllDatabases,
  9007      }
  9008    }
  9009  | SHOW REGIONS FROM DATABASE database_name
  9010    {
  9011      $$.val = &tree.ShowRegions{
  9012        ShowRegionsFrom: tree.ShowRegionsFromDatabase,
  9013        DatabaseName: tree.Name($5),
  9014      }
  9015    }
  9016  | SHOW REGIONS
  9017    {
  9018      $$.val = &tree.ShowRegions{
  9019        ShowRegionsFrom: tree.ShowRegionsFromDefault,
  9020      }
  9021    }
  9022  | SHOW SUPER REGIONS FROM DATABASE database_name
  9023    {
  9024      $$.val = &tree.ShowRegions{
  9025        ShowRegionsFrom: tree.ShowSuperRegionsFromDatabase,
  9026        DatabaseName: tree.Name($6),
  9027      }
  9028    }
  9029  | SHOW REGIONS error // SHOW HELP: SHOW REGIONS
  9030  
  9031  show_locality_stmt:
  9032    SHOW LOCALITY
  9033    {
  9034      $$.val = &tree.ShowVar{Name: "locality"}
  9035    }
  9036  
  9037  show_fingerprints_stmt:
  9038    SHOW EXPERIMENTAL_FINGERPRINTS FROM TABLE table_name
  9039    {
  9040      /* SKIP DOC */
  9041      $$.val = &tree.ShowFingerprints{Table: $5.unresolvedObjectName()}
  9042    }
  9043  |
  9044    SHOW EXPERIMENTAL_FINGERPRINTS FROM virtual_cluster virtual_cluster_spec
  9045    {
  9046      /* SKIP DOC */
  9047      $$.val = &tree.ShowFingerprints{TenantSpec: $5.tenantSpec()}
  9048    }
  9049  
  9050  show_full_scans_stmt:
  9051    SHOW FULL TABLE SCANS
  9052    {
  9053      $$.val = &tree.ShowFullTableScans{}
  9054    }
  9055  
  9056  opt_on_targets_roles:
  9057    ON targets_roles
  9058    {
  9059      tmp := $2.grantTargetList()
  9060      $$.val = &tmp
  9061    }
  9062  | /* EMPTY */
  9063    {
  9064      $$.val = (*tree.GrantTargetList)(nil)
  9065    }
  9066  
  9067  // grant_targets is a non-terminal for a list of privilege targets, either a
  9068  // list of databases or a list of tables.
  9069  //
  9070  // This rule is complex and cannot be decomposed as a tree of
  9071  // non-terminals because it must resolve syntax ambiguities in the
  9072  // SHOW GRANTS ON ROLE statement. It was constructed as follows.
  9073  //
  9074  // 1. Start with the desired definition of targets:
  9075  //
  9076  //    targets ::=
  9077  //        table_pattern_list
  9078  //        TABLE table_pattern_list
  9079  //        DATABASE name_list
  9080  //
  9081  // 2. Now we must disambiguate the first rule "table_pattern_list"
  9082  //    between one that recognizes ROLE and one that recognizes
  9083  //    "<some table pattern list>". So first, inline the definition of
  9084  //    table_pattern_list.
  9085  //
  9086  //    targets ::=
  9087  //        table_pattern                          # <- here
  9088  //        table_pattern_list ',' table_pattern   # <- here
  9089  //        TABLE table_pattern_list
  9090  //        DATABASE name_list
  9091  //
  9092  // 3. We now must disambiguate the "ROLE" inside the prefix "table_pattern".
  9093  //    However having "table_pattern_list" as prefix is cumbersome, so swap it.
  9094  //
  9095  //    targets ::=
  9096  //        table_pattern
  9097  //        table_pattern ',' table_pattern_list   # <- here
  9098  //        TABLE table_pattern_list
  9099  //        DATABASE name_list
  9100  //
  9101  // 4. The rule that has table_pattern followed by a comma is now
  9102  //    non-problematic, because it will never match "ROLE" followed
  9103  //    by an optional name list (neither "ROLE;" nor "ROLE <ident>"
  9104  //    would match). We just need to focus on the first one "table_pattern".
  9105  //    This needs to tweak "table_pattern".
  9106  //
  9107  //    Here we could inline table_pattern but now we do not have to any
  9108  //    more, we just need to create a variant of it which is
  9109  //    unambiguous with a single ROLE keyword. That is, we need a
  9110  //    table_pattern which cannot contain a single name. We do
  9111  //    this as follows.
  9112  //
  9113  //    targets ::=
  9114  //        complex_table_pattern                  # <- here
  9115  //        table_pattern ',' table_pattern_list
  9116  //        TABLE table_pattern_list
  9117  //        DATABASE name_list
  9118  //    complex_table_pattern ::=
  9119  //        name '.' unrestricted_name
  9120  //        name '.' unrestricted_name '.' unrestricted_name
  9121  //        name '.' unrestricted_name '.' '*'
  9122  //        name '.' '*'
  9123  //        '*'
  9124  //
  9125  // 5. At this point the rule cannot start with a simple identifier any
  9126  //    more, keyword or not. But more importantly, any token sequence
  9127  //    that starts with ROLE cannot be matched by any of these remaining
  9128  //    rules. This means that the prefix is now free to use, without
  9129  //    ambiguity. We do this as follows, to gain a syntax rule for "ROLE
  9130  //    <namelist>". (We will handle a ROLE with no name list below.)
  9131  //
  9132  //    targets ::=
  9133  //        ROLE name_list                        # <- here
  9134  //        complex_table_pattern
  9135  //        table_pattern ',' table_pattern_list
  9136  //        TABLE table_pattern_list
  9137  //        DATABASE name_list
  9138  //
  9139  // 6. Now on to the finishing touches. First we would like to regain the
  9140  //    ability to use "<tablename>" when the table name is a simple
  9141  //    identifier. This is done as follows:
  9142  //
  9143  //    targets ::=
  9144  //        ROLE name_list
  9145  //        name                                  # <- here
  9146  //        complex_table_pattern
  9147  //        table_pattern ',' table_pattern_list
  9148  //        TABLE table_pattern_list
  9149  //        DATABASE name_list
  9150  //
  9151  // 7. Then, we want to recognize "ROLE" without any subsequent name
  9152  //    list. This requires some care: we can not add "ROLE" to the set of
  9153  //    rules above, because "name" would then overlap. To disambiguate,
  9154  //    we must first inline "name" as follows:
  9155  //
  9156  //    targets ::=
  9157  //        ROLE name_list
  9158  //        IDENT                    # <- here, always <table>
  9159  //        col_name_keyword         # <- here, always <table>
  9160  //        unreserved_keyword       # <- here, either ROLE or <table>
  9161  //        complex_table_pattern
  9162  //        table_pattern ',' table_pattern_list
  9163  //        TABLE table_pattern_list
  9164  //        DATABASE name_list
  9165  //
  9166  // 8. And now the rule is sufficiently simple that we can disambiguate
  9167  //    in the action, like this:
  9168  //
  9169  //    targets ::=
  9170  //        ...
  9171  //        unreserved_keyword {
  9172  //             if $1 == "role" { /* handle ROLE */ }
  9173  //             else { /* handle ON <tablename> */ }
  9174  //        }
  9175  //        ...
  9176  //
  9177  //   (but see the comment on the action of this sub-rule below for
  9178  //   more nuance.)
  9179  //
  9180  // Tada!
  9181  // TODO(knz): This should learn how to parse more complex expressions
  9182  // and placeholders.
  9183  grant_targets:
  9184    IDENT
  9185    {
  9186      $$.val = tree.GrantTargetList{Tables: tree.TableAttrs{SequenceOnly: false, TablePatterns: tree.TablePatterns{&tree.UnresolvedName{NumParts:1, Parts: tree.NameParts{$1}}}}}
  9187    }
  9188  | col_name_keyword
  9189    {
  9190      $$.val = tree.GrantTargetList{Tables: tree.TableAttrs{SequenceOnly: false, TablePatterns: tree.TablePatterns{&tree.UnresolvedName{NumParts:1, Parts: tree.NameParts{$1}}}}}
  9191    }
  9192  | unreserved_keyword
  9193    {
  9194      // This sub-rule is meant to support both ROLE and other keywords
  9195      // used as table name without the TABLE prefix. The keyword ROLE
  9196      // here can have two meanings:
  9197      //
  9198      // - for all statements except SHOW GRANTS, it must be interpreted
  9199      //   as a plain table name.
  9200      // - for SHOW GRANTS specifically, it must be handled as an ON ROLE
  9201      //   specifier without a name list (the rule with a name list is separate,
  9202      //   see above).
  9203      //
  9204      // Yet we want to use a single "targets" non-terminal for all
  9205      // statements that use targets, to share the code. This action
  9206      // achieves this as follows:
  9207      //
  9208      // - for all statements (including SHOW GRANTS), it populates the
  9209      //   Tables list in TargetList{} with the given name. This will
  9210      //   include the given keyword as table pattern in all cases,
  9211      //   including when the keyword was ROLE.
  9212      //
  9213      // - if ROLE was specified, it remembers this fact in the ForRoles
  9214      //   field. This distinguishes `ON ROLE` (where "role" is
  9215      //   specified as keyword), which triggers the special case in
  9216      //   SHOW GRANTS, from `ON "role"` (where "role" is specified as
  9217      //   identifier), which is always handled as a table name.
  9218      //
  9219      //   Both `ON ROLE` and `ON "role"` populate the Tables list in the same way,
  9220      //   so that other statements than SHOW GRANTS don't observe any difference.
  9221      //
  9222      // Arguably this code is a bit too clever. Future work should aim
  9223      // to remove the special casing of SHOW GRANTS altogether instead
  9224      // of increasing (or attempting to modify) the grey magic occurring
  9225      // here.
  9226      $$.val = tree.GrantTargetList{
  9227        Tables: tree.TableAttrs{SequenceOnly: false, TablePatterns:tree.TablePatterns{&tree.UnresolvedName{NumParts:1, Parts: tree.NameParts{$1}}}},
  9228        ForRoles: $1 == "role", // backdoor for "SHOW GRANTS ON ROLE" (no name list)
  9229      }
  9230    }
  9231  | complex_table_pattern
  9232    {
  9233      $$.val = tree.GrantTargetList{Tables: tree.TableAttrs{SequenceOnly: false, TablePatterns: tree.TablePatterns{$1.unresolvedName()}}}
  9234    }
  9235  | SEQUENCE table_pattern_list
  9236    {
  9237      $$.val = tree.GrantTargetList{Tables: tree.TableAttrs{SequenceOnly: true, TablePatterns: $2.tablePatterns()}}
  9238    }
  9239  | table_pattern ',' table_pattern_list
  9240    {
  9241      remainderPats := $3.tablePatterns()
  9242      $$.val = tree.GrantTargetList{Tables: tree.TableAttrs{SequenceOnly: false, TablePatterns: append(tree.TablePatterns{$1.unresolvedName()}, remainderPats...)}}
  9243    }
  9244  | TABLE table_pattern_list
  9245    {
  9246      $$.val = tree.GrantTargetList{Tables: tree.TableAttrs{SequenceOnly: false, TablePatterns: $2.tablePatterns()}}
  9247    }
  9248  | DATABASE name_list
  9249    {
  9250      $$.val = tree.GrantTargetList{Databases: $2.nameList()}
  9251    }
  9252  | EXTERNAL CONNECTION name_list
  9253    {
  9254      $$.val = tree.GrantTargetList{ExternalConnections: $3.nameList()}
  9255    }
  9256  | FUNCTION function_with_paramtypes_list
  9257    {
  9258      $$.val = tree.GrantTargetList{Functions: $2.routineObjs()}
  9259    }
  9260  | PROCEDURE function_with_paramtypes_list
  9261    {
  9262      $$.val = tree.GrantTargetList{Procedures: $2.routineObjs()}
  9263    }
  9264  
  9265  // backup_targets is similar to grant_targets but used by backup and restore, and thus
  9266  // supports tenants, but does not support sequences, types, or other SQL nouns
  9267  // that grants support, but rather just things which hold rows that can be backed
  9268  // up.
  9269  backup_targets:
  9270    IDENT
  9271    {
  9272      $$.val = tree.BackupTargetList{Tables: tree.TableAttrs{SequenceOnly: false, TablePatterns: tree.TablePatterns{&tree.UnresolvedName{NumParts:1, Parts: tree.NameParts{$1}}}}}
  9273    }
  9274  | col_name_keyword
  9275    {
  9276      $$.val = tree.BackupTargetList{Tables: tree.TableAttrs{SequenceOnly: false, TablePatterns: tree.TablePatterns{&tree.UnresolvedName{NumParts:1, Parts: tree.NameParts{$1}}}}}
  9277    }
  9278  | unreserved_keyword
  9279    {
  9280        $$.val = tree.BackupTargetList{
  9281        Tables: tree.TableAttrs{SequenceOnly: false, TablePatterns:tree.TablePatterns{&tree.UnresolvedName{NumParts:1, Parts: tree.NameParts{$1}}}},
  9282      }
  9283    }
  9284  | complex_table_pattern
  9285    {
  9286      $$.val = tree.BackupTargetList{Tables: tree.TableAttrs{SequenceOnly: false, TablePatterns: tree.TablePatterns{$1.unresolvedName()}}}
  9287    }
  9288  | table_pattern ',' table_pattern_list
  9289    {
  9290      remainderPats := $3.tablePatterns()
  9291      $$.val = tree.BackupTargetList{Tables: tree.TableAttrs{SequenceOnly: false, TablePatterns: append(tree.TablePatterns{$1.unresolvedName()}, remainderPats...)}}
  9292    }
  9293  | TABLE table_pattern_list
  9294    {
  9295      $$.val = tree.BackupTargetList{Tables: tree.TableAttrs{SequenceOnly: false, TablePatterns: $2.tablePatterns()}}
  9296    }
  9297  // TODO(knz): This should learn how to parse more complex expressions
  9298  // and placeholders.
  9299  | virtual_cluster iconst64
  9300    {
  9301      /* SKIP DOC */
  9302      tenID := uint64($2.int64())
  9303      if tenID == 0 {
  9304        return setErr(sqllex, errors.New("invalid tenant ID"))
  9305      }
  9306      $$.val = tree.BackupTargetList{TenantID: tree.TenantID{Specified: true, ID: tenID}}
  9307    }
  9308  | virtual_cluster IDENT
  9309    {
  9310      /* SKIP DOC */
  9311      // TODO(knz): This rule can go away once the main clause above supports
  9312      // arbitrary expressions.
  9313      if $2 != "_" {
  9314         return setErr(sqllex, errors.New("invalid syntax"))
  9315      }
  9316      $$.val = tree.BackupTargetList{TenantID: tree.TenantID{Specified: true}}
  9317    }
  9318  | DATABASE name_list
  9319    {
  9320      $$.val = tree.BackupTargetList{Databases: $2.nameList()}
  9321    }
  9322  
  9323  // target_roles is the variant of targets which recognizes ON ROLES
  9324  // with a name list. This cannot be included in targets directly
  9325  // because some statements must not recognize this syntax.
  9326  targets_roles:
  9327    ROLE role_spec_list
  9328    {
  9329       $$.val = tree.GrantTargetList{ForRoles: true, Roles: $2.roleSpecList()}
  9330    }
  9331  | SCHEMA schema_name_list
  9332    {
  9333       $$.val = tree.GrantTargetList{Schemas: $2.objectNamePrefixList()}
  9334    }
  9335  | SCHEMA schema_wildcard
  9336     {
  9337       $$.val = tree.GrantTargetList{Schemas: $2.objectNamePrefixList()}
  9338     }
  9339  | TYPE type_name_list
  9340    {
  9341      $$.val = tree.GrantTargetList{Types: $2.unresolvedObjectNames()}
  9342    }
  9343  | grant_targets
  9344  
  9345  
  9346  for_grantee_clause:
  9347    FOR role_spec_list
  9348    {
  9349      $$.val = $2.roleSpecList()
  9350    }
  9351  | /* EMPTY */
  9352    {
  9353      $$.val = tree.RoleSpecList(nil)
  9354    }
  9355  
  9356  // %Help: PAUSE - pause background tasks
  9357  // %Category: Group
  9358  // %Text: PAUSE JOBS, PAUSE SCHEDULES, PAUSE ALL JOBS
  9359  pause_stmt:
  9360    pause_jobs_stmt       // EXTEND WITH HELP: PAUSE JOBS
  9361  | pause_schedules_stmt  // EXTEND WITH HELP: PAUSE SCHEDULES
  9362  | pause_all_jobs_stmt  // EXTEND WITH HELP: PAUSE ALL JOBS
  9363  | PAUSE error           // SHOW HELP: PAUSE
  9364  
  9365  // %Help: RESUME - resume background tasks
  9366  // %Category: Group
  9367  // %Text: RESUME JOBS, RESUME SCHEDULES, RESUME ALL BACKUP JOBS
  9368  resume_stmt:
  9369    resume_jobs_stmt       // EXTEND WITH HELP: RESUME JOBS
  9370  | resume_schedules_stmt  // EXTEND WITH HELP: RESUME SCHEDULES
  9371  | resume_all_jobs_stmt  // EXTEND WITH HELP: RESUME ALL JOBS
  9372  | RESUME error           // SHOW HELP: RESUME
  9373  
  9374  // %Help: RESUME ALL JOBS - resume background jobs
  9375  // %Category: Misc
  9376  // %Text:
  9377  // RESUME ALL {BACKUP|CHANGEFEED|IMPORT|RESTORE} JOBS
  9378  resume_all_jobs_stmt:
  9379    RESUME ALL name JOBS
  9380    {
  9381      $$.val = &tree.ControlJobsOfType{Type: $3, Command: tree.ResumeJob}
  9382    }
  9383  | RESUME ALL error // SHOW HELP: RESUME ALL JOBS
  9384  
  9385  // %Help: PAUSE JOBS - pause selected background jobs
  9386  // %Category: Misc
  9387  // %Text:
  9388  // PAUSE JOBS <selectclause>
  9389  // PAUSE JOB <jobid>
  9390  // %SeeAlso: SHOW JOBS, CANCEL JOBS, RESUME JOBS
  9391  pause_jobs_stmt:
  9392    PAUSE JOB a_expr
  9393    {
  9394      $$.val = &tree.ControlJobs{
  9395        Jobs: &tree.Select{
  9396          Select: &tree.ValuesClause{Rows: []tree.Exprs{tree.Exprs{$3.expr()}}},
  9397        },
  9398        Command: tree.PauseJob,
  9399      }
  9400    }
  9401  | PAUSE JOB a_expr WITH REASON '=' string_or_placeholder
  9402    {
  9403      $$.val = &tree.ControlJobs{
  9404        Jobs: &tree.Select{
  9405          Select: &tree.ValuesClause{Rows: []tree.Exprs{tree.Exprs{$3.expr()}}},
  9406        },
  9407        Command: tree.PauseJob,
  9408        Reason: $7.expr(),
  9409      }
  9410    }
  9411  | PAUSE JOB error // SHOW HELP: PAUSE JOBS
  9412  | PAUSE JOBS select_stmt
  9413    {
  9414      $$.val = &tree.ControlJobs{Jobs: $3.slct(), Command: tree.PauseJob}
  9415    }
  9416  | PAUSE JOBS select_stmt WITH REASON '=' string_or_placeholder
  9417    {
  9418      $$.val = &tree.ControlJobs{Jobs: $3.slct(), Command: tree.PauseJob, Reason: $7.expr()}
  9419    }
  9420  | PAUSE JOBS for_schedules_clause
  9421    {
  9422      $$.val = &tree.ControlJobsForSchedules{Schedules: $3.slct(), Command: tree.PauseJob}
  9423    }
  9424  | PAUSE JOBS error // SHOW HELP: PAUSE JOBS
  9425  
  9426  
  9427  for_schedules_clause:
  9428    FOR SCHEDULES select_stmt
  9429    {
  9430      $$.val = $3.slct()
  9431    }
  9432  | FOR SCHEDULE a_expr
  9433    {
  9434     $$.val = &tree.Select{
  9435       Select: &tree.ValuesClause{Rows: []tree.Exprs{tree.Exprs{$3.expr()}}},
  9436     }
  9437    }
  9438  
  9439  // %Help: PAUSE SCHEDULES - pause scheduled jobs
  9440  // %Category: Misc
  9441  // %Text:
  9442  // PAUSE SCHEDULES <selectclause>
  9443  //   select clause: select statement returning schedule id to pause.
  9444  // PAUSE SCHEDULE <scheduleID>
  9445  // %SeeAlso: RESUME SCHEDULES, SHOW JOBS, CANCEL JOBS
  9446  pause_schedules_stmt:
  9447    PAUSE SCHEDULE a_expr
  9448    {
  9449      $$.val = &tree.ControlSchedules{
  9450        Schedules: &tree.Select{
  9451          Select: &tree.ValuesClause{Rows: []tree.Exprs{tree.Exprs{$3.expr()}}},
  9452        },
  9453        Command: tree.PauseSchedule,
  9454      }
  9455    }
  9456  | PAUSE SCHEDULE error // SHOW HELP: PAUSE SCHEDULES
  9457  | PAUSE SCHEDULES select_stmt
  9458    {
  9459      $$.val = &tree.ControlSchedules{
  9460        Schedules: $3.slct(),
  9461        Command: tree.PauseSchedule,
  9462      }
  9463    }
  9464  | PAUSE SCHEDULES error // SHOW HELP: PAUSE SCHEDULES
  9465  
  9466  // %Help: PAUSE ALL JOBS - pause all background jobs
  9467  // %Category: Misc
  9468  // %Text:
  9469  // PAUSE ALL {BACKUP|CHANGEFEED|IMPORT|RESTORE} JOBS
  9470  pause_all_jobs_stmt:
  9471    PAUSE ALL name JOBS
  9472    {
  9473      $$.val = &tree.ControlJobsOfType{Type: $3, Command: tree.PauseJob}
  9474    }
  9475  | PAUSE ALL error // SHOW HELP: PAUSE ALL JOBS
  9476  
  9477  
  9478  // %Help: CREATE SCHEMA - create a new schema
  9479  // %Category: DDL
  9480  // %Text:
  9481  // CREATE SCHEMA [IF NOT EXISTS] { [<databasename>.]<schemaname> | [[<databasename>.]<schemaname>] AUTHORIZATION <rolename> }
  9482  create_schema_stmt:
  9483    CREATE SCHEMA qualifiable_schema_name
  9484    {
  9485      $$.val = &tree.CreateSchema{
  9486        Schema: $3.objectNamePrefix(),
  9487      }
  9488    }
  9489  | CREATE SCHEMA IF NOT EXISTS qualifiable_schema_name
  9490    {
  9491      $$.val = &tree.CreateSchema{
  9492        Schema: $6.objectNamePrefix(),
  9493        IfNotExists: true,
  9494      }
  9495    }
  9496  | CREATE SCHEMA opt_schema_name AUTHORIZATION role_spec
  9497    {
  9498      $$.val = &tree.CreateSchema{
  9499        Schema: $3.objectNamePrefix(),
  9500        AuthRole: $5.roleSpec(),
  9501      }
  9502    }
  9503  | CREATE SCHEMA IF NOT EXISTS opt_schema_name AUTHORIZATION role_spec
  9504    {
  9505      $$.val = &tree.CreateSchema{
  9506        Schema: $6.objectNamePrefix(),
  9507        IfNotExists: true,
  9508        AuthRole: $8.roleSpec(),
  9509      }
  9510    }
  9511  | CREATE SCHEMA error // SHOW HELP: CREATE SCHEMA
  9512  
  9513  // %Help: ALTER SCHEMA - alter an existing schema
  9514  // %Category: DDL
  9515  // %Text:
  9516  //
  9517  // Commands:
  9518  //   ALTER SCHEMA ... RENAME TO <newschemaname>
  9519  //   ALTER SCHEMA ... OWNER TO {<newowner> | CURRENT_USER | SESSION_USER }
  9520  alter_schema_stmt:
  9521    ALTER SCHEMA qualifiable_schema_name RENAME TO schema_name
  9522    {
  9523      $$.val = &tree.AlterSchema{
  9524        Schema: $3.objectNamePrefix(),
  9525        Cmd: &tree.AlterSchemaRename{
  9526          NewName: tree.Name($6),
  9527        },
  9528      }
  9529    }
  9530  | ALTER SCHEMA qualifiable_schema_name OWNER TO role_spec
  9531    {
  9532      $$.val = &tree.AlterSchema{
  9533        Schema: $3.objectNamePrefix(),
  9534        Cmd: &tree.AlterSchemaOwner{
  9535          Owner: $6.roleSpec(),
  9536        },
  9537      }
  9538    }
  9539  | ALTER SCHEMA error // SHOW HELP: ALTER SCHEMA
  9540  
  9541  // %Help: CREATE TABLE - create a new table
  9542  // %Category: DDL
  9543  // %Text:
  9544  // CREATE [[GLOBAL | LOCAL] {TEMPORARY | TEMP}] TABLE [IF NOT EXISTS] <tablename> ( <elements...> ) [<on_commit>]
  9545  // CREATE [[GLOBAL | LOCAL] {TEMPORARY | TEMP}] TABLE [IF NOT EXISTS] <tablename> [( <colnames...> )] AS <source> [<on commit>]
  9546  //
  9547  // Table elements:
  9548  //    <name> <type> [<qualifiers...>]
  9549  //    [UNIQUE | INVERTED] INDEX [<name>] ( <colname> [ASC | DESC] [, ...] )
  9550  //                            [USING HASH] [{STORING | INCLUDE | COVERING} ( <colnames...> )]
  9551  //    FAMILY [<name>] ( <colnames...> )
  9552  //    [CONSTRAINT <name>] <constraint>
  9553  //
  9554  // Table constraints:
  9555  //    PRIMARY KEY ( <colnames...> ) [USING HASH]
  9556  //    FOREIGN KEY ( <colnames...> ) REFERENCES <tablename> [( <colnames...> )] [ON DELETE {NO ACTION | RESTRICT}] [ON UPDATE {NO ACTION | RESTRICT}]
  9557  //    UNIQUE ( <colnames...> ) [{STORING | INCLUDE | COVERING} ( <colnames...> )]
  9558  //    CHECK ( <expr> )
  9559  //
  9560  // Column qualifiers:
  9561  //   [CONSTRAINT <constraintname>] {NULL | NOT NULL | NOT VISIBLE | UNIQUE | PRIMARY KEY | CHECK (<expr>) | DEFAULT <expr> | ON UPDATE <expr> | GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY [( <opt_sequence_option_list> )]}
  9562  //   FAMILY <familyname>, CREATE [IF NOT EXISTS] FAMILY [<familyname>]
  9563  //   REFERENCES <tablename> [( <colnames...> )] [ON DELETE {NO ACTION | RESTRICT}] [ON UPDATE {NO ACTION | RESTRICT}]
  9564  //   COLLATE <collationname>
  9565  //   AS ( <expr> ) { STORED | VIRTUAL }
  9566  //
  9567  // On commit clause:
  9568  //    ON COMMIT {PRESERVE ROWS | DROP | DELETE ROWS}
  9569  //
  9570  // %SeeAlso: SHOW TABLES, CREATE VIEW, SHOW CREATE,
  9571  // WEBDOCS/create-table.html
  9572  // WEBDOCS/create-table-as.html
  9573  create_table_stmt:
  9574    CREATE opt_persistence_temp_table TABLE table_name '(' opt_table_elem_list ')' opt_create_table_inherits opt_partition_by_table opt_table_with opt_create_table_on_commit opt_locality
  9575    {
  9576      name := $4.unresolvedObjectName().ToTableName()
  9577      $$.val = &tree.CreateTable{
  9578        Table: name,
  9579        IfNotExists: false,
  9580        Defs: $6.tblDefs(),
  9581        AsSource: nil,
  9582        PartitionByTable: $9.partitionByTable(),
  9583        Persistence: $2.persistence(),
  9584        StorageParams: $10.storageParams(),
  9585        OnCommit: $11.createTableOnCommitSetting(),
  9586        Locality: $12.locality(),
  9587      }
  9588    }
  9589  | CREATE opt_persistence_temp_table TABLE IF NOT EXISTS table_name '(' opt_table_elem_list ')' opt_create_table_inherits opt_partition_by_table opt_table_with opt_create_table_on_commit opt_locality
  9590    {
  9591      name := $7.unresolvedObjectName().ToTableName()
  9592      $$.val = &tree.CreateTable{
  9593        Table: name,
  9594        IfNotExists: true,
  9595        Defs: $9.tblDefs(),
  9596        AsSource: nil,
  9597        PartitionByTable: $12.partitionByTable(),
  9598        Persistence: $2.persistence(),
  9599        StorageParams: $13.storageParams(),
  9600        OnCommit: $14.createTableOnCommitSetting(),
  9601        Locality: $15.locality(),
  9602      }
  9603    }
  9604  
  9605  opt_locality:
  9606    locality
  9607    {
  9608      $$.val = $1.locality()
  9609    }
  9610  | /* EMPTY */
  9611    {
  9612      $$.val = (*tree.Locality)(nil)
  9613    }
  9614  
  9615  opt_table_with:
  9616    opt_with_storage_parameter_list
  9617  | WITHOUT OIDS
  9618    {
  9619      /* SKIP DOC */
  9620      /* this is also the default in CockroachDB */
  9621      $$.val = nil
  9622    }
  9623  | WITH OIDS error
  9624    {
  9625      return unimplemented(sqllex, "create table with oids")
  9626    }
  9627  
  9628  opt_create_table_inherits:
  9629    /* EMPTY */
  9630    {
  9631      $$ = ""
  9632    }
  9633  | INHERITS error
  9634    {
  9635      /* SKIP DOC */
  9636      return unimplementedWithIssueDetail(sqllex, 22456, "create table inherits")
  9637    }
  9638  
  9639  opt_with_storage_parameter_list:
  9640    {
  9641      $$.val = nil
  9642    }
  9643  | WITH '(' storage_parameter_list ')'
  9644    {
  9645      $$.val = $3.storageParams()
  9646    }
  9647  
  9648  opt_create_table_on_commit:
  9649    {
  9650      $$.val = tree.CreateTableOnCommitUnset
  9651    }
  9652  | ON COMMIT PRESERVE ROWS
  9653    {
  9654      $$.val = tree.CreateTableOnCommitPreserveRows
  9655    }
  9656  | ON COMMIT DELETE ROWS error
  9657    {
  9658      return unimplementedWithIssueDetail(sqllex, 46556, "delete rows")
  9659    }
  9660  | ON COMMIT DROP error
  9661    {
  9662      return unimplementedWithIssueDetail(sqllex, 46556, "drop")
  9663    }
  9664  
  9665  storage_parameter_key:
  9666    name
  9667  | SCONST
  9668  
  9669  storage_parameter_key_list:
  9670    storage_parameter_key
  9671    {
  9672      $$.val = []tree.Name{tree.Name($1)}
  9673    }
  9674  | storage_parameter_key_list ',' storage_parameter_key
  9675    {
  9676      $$.val = append($1.storageParamKeys(), tree.Name($3))
  9677    }
  9678  
  9679  storage_parameter:
  9680    storage_parameter_key '=' var_value
  9681    {
  9682      $$.val = tree.StorageParam{Key: tree.Name($1), Value: $3.expr()}
  9683    }
  9684  
  9685  storage_parameter_list:
  9686    storage_parameter
  9687    {
  9688      $$.val = []tree.StorageParam{$1.storageParam()}
  9689    }
  9690  |  storage_parameter_list ',' storage_parameter
  9691    {
  9692      $$.val = append($1.storageParams(), $3.storageParam())
  9693    }
  9694  
  9695  create_table_as_stmt:
  9696    CREATE opt_persistence_temp_table TABLE table_name create_as_opt_col_list opt_table_with AS select_stmt opt_create_as_data opt_create_table_on_commit
  9697    {
  9698      name := $4.unresolvedObjectName().ToTableName()
  9699      $$.val = &tree.CreateTable{
  9700        Table: name,
  9701        IfNotExists: false,
  9702        Defs: $5.tblDefs(),
  9703        AsSource: $8.slct(),
  9704        StorageParams: $6.storageParams(),
  9705        OnCommit: $10.createTableOnCommitSetting(),
  9706        Persistence: $2.persistence(),
  9707      }
  9708    }
  9709  | CREATE opt_persistence_temp_table TABLE IF NOT EXISTS table_name create_as_opt_col_list opt_table_with AS select_stmt opt_create_as_data opt_create_table_on_commit
  9710    {
  9711      name := $7.unresolvedObjectName().ToTableName()
  9712      $$.val = &tree.CreateTable{
  9713        Table: name,
  9714        IfNotExists: true,
  9715        Defs: $8.tblDefs(),
  9716        AsSource: $11.slct(),
  9717        StorageParams: $9.storageParams(),
  9718        OnCommit: $13.createTableOnCommitSetting(),
  9719        Persistence: $2.persistence(),
  9720      }
  9721    }
  9722  
  9723  opt_create_as_data:
  9724    /* EMPTY */  { /* no error */ }
  9725  | WITH DATA    { /* SKIP DOC */ /* This is the default */ }
  9726  | WITH NO DATA { return unimplemented(sqllex, "create table as with no data") }
  9727  
  9728  /*
  9729   * Redundancy here is needed to avoid shift/reduce conflicts,
  9730   * since TEMP is not a reserved word.  See also OptTempTableName.
  9731   *
  9732   * NOTE: we accept both GLOBAL and LOCAL options.  They currently do nothing,
  9733   * but future versions might consider GLOBAL to request SQL-spec-compliant
  9734   * temp table behavior.  Since we have no modules the
  9735   * LOCAL keyword is really meaningless; furthermore, some other products
  9736   * implement LOCAL as meaning the same as our default temp table behavior,
  9737   * so we'll probably continue to treat LOCAL as a noise word.
  9738   *
  9739   * NOTE: PG only accepts GLOBAL/LOCAL keywords for temp tables -- not sequences
  9740   * and views. These keywords are no-ops in PG. This behavior is replicated by
  9741   * making the distinction between opt_temp and opt_persistence_temp_table.
  9742   */
  9743   opt_temp:
  9744    TEMPORARY         { $$.val = tree.PersistenceTemporary }
  9745  | TEMP              { $$.val = tree.PersistenceTemporary }
  9746  | /*EMPTY*/         { $$.val = tree.PersistencePermanent }
  9747  
  9748  opt_persistence_temp_table:
  9749    opt_temp
  9750  | LOCAL TEMPORARY   { $$.val = tree.PersistenceTemporary }
  9751  | LOCAL TEMP        { $$.val = tree.PersistenceTemporary }
  9752  | GLOBAL TEMPORARY  { $$.val = tree.PersistenceTemporary }
  9753  | GLOBAL TEMP       { $$.val = tree.PersistenceTemporary }
  9754  | UNLOGGED          { $$.val = tree.PersistenceUnlogged }
  9755  
  9756  opt_table_elem_list:
  9757    table_elem_list
  9758  | /* EMPTY */
  9759    {
  9760      $$.val = tree.TableDefs(nil)
  9761    }
  9762  
  9763  table_elem_list:
  9764    table_elem
  9765    {
  9766      $$.val = tree.TableDefs{$1.tblDef()}
  9767    }
  9768  | table_elem_list ',' table_elem
  9769    {
  9770      $$.val = append($1.tblDefs(), $3.tblDef())
  9771    }
  9772  
  9773  table_elem:
  9774    column_table_def
  9775    {
  9776      $$.val = $1.colTableDef()
  9777    }
  9778  | index_def
  9779  | family_def
  9780  | table_constraint opt_validate_behavior
  9781    {
  9782      def := $1.constraintDef()
  9783      valBehavior := $2.validationBehavior()
  9784      if u, ok := def.(*tree.UniqueConstraintTableDef); ok && valBehavior == tree.ValidationSkip {
  9785        typ := "PRIMARY KEY"
  9786        if !u.PrimaryKey {
  9787          typ = "UNIQUE"
  9788        }
  9789        return purposelyUnimplemented(sqllex, "table constraint", typ + " constraints cannot be marked NOT VALID")
  9790      }
  9791      $$.val = def
  9792    }
  9793  | LIKE table_name like_table_option_list
  9794    {
  9795      $$.val = &tree.LikeTableDef{
  9796        Name: $2.unresolvedObjectName().ToTableName(),
  9797        Options: $3.likeTableOptionList(),
  9798      }
  9799    }
  9800  
  9801  like_table_option_list:
  9802    like_table_option_list INCLUDING like_table_option
  9803    {
  9804      $$.val = append($1.likeTableOptionList(), $3.likeTableOption())
  9805    }
  9806  | like_table_option_list EXCLUDING like_table_option
  9807    {
  9808      opt := $3.likeTableOption()
  9809      opt.Excluded = true
  9810      $$.val = append($1.likeTableOptionList(), opt)
  9811    }
  9812  | /* EMPTY */
  9813    {
  9814      $$.val = []tree.LikeTableOption(nil)
  9815    }
  9816  
  9817  like_table_option:
  9818    COMMENTS			{ return unimplementedWithIssueDetail(sqllex, 47071, "like table in/excluding comments") }
  9819  | CONSTRAINTS		{ $$.val = tree.LikeTableOption{Opt: tree.LikeTableOptConstraints} }
  9820  | DEFAULTS			{ $$.val = tree.LikeTableOption{Opt: tree.LikeTableOptDefaults} }
  9821  | IDENTITY	  	{ return unimplementedWithIssueDetail(sqllex, 47071, "like table in/excluding identity") }
  9822  | GENERATED			{ $$.val = tree.LikeTableOption{Opt: tree.LikeTableOptGenerated} }
  9823  | INDEXES			{ $$.val = tree.LikeTableOption{Opt: tree.LikeTableOptIndexes} }
  9824  | STATISTICS		{ return unimplementedWithIssueDetail(sqllex, 47071, "like table in/excluding statistics") }
  9825  | STORAGE			{ return unimplementedWithIssueDetail(sqllex, 47071, "like table in/excluding storage") }
  9826  | ALL				{ $$.val = tree.LikeTableOption{Opt: tree.LikeTableOptAll} }
  9827  
  9828  
  9829  partition:
  9830    PARTITION partition_name
  9831    {
  9832      $$ = $2
  9833    }
  9834  
  9835  opt_partition:
  9836    partition
  9837  | /* EMPTY */
  9838    {
  9839      $$ = ""
  9840    }
  9841  
  9842  opt_partition_by:
  9843    partition_by
  9844  | /* EMPTY */
  9845    {
  9846      $$.val = (*tree.PartitionBy)(nil)
  9847    }
  9848  
  9849  partition_by_index:
  9850    partition_by
  9851    {
  9852      $$.val = &tree.PartitionByIndex{
  9853        PartitionBy: $1.partitionBy(),
  9854      }
  9855    }
  9856  
  9857  opt_partition_by_index:
  9858    partition_by
  9859    {
  9860      $$.val = &tree.PartitionByIndex{
  9861        PartitionBy: $1.partitionBy(),
  9862      }
  9863    }
  9864  | /* EMPTY */
  9865    {
  9866      $$.val = (*tree.PartitionByIndex)(nil)
  9867    }
  9868  
  9869  partition_by_table:
  9870    partition_by
  9871    {
  9872      $$.val = &tree.PartitionByTable{
  9873        PartitionBy: $1.partitionBy(),
  9874      }
  9875    }
  9876  | PARTITION ALL BY partition_by_inner
  9877    {
  9878      $$.val = &tree.PartitionByTable{
  9879        All: true,
  9880        PartitionBy: $4.partitionBy(),
  9881      }
  9882    }
  9883  
  9884  opt_partition_by_table:
  9885    partition_by_table
  9886  | /* EMPTY */
  9887    {
  9888      $$.val = (*tree.PartitionByTable)(nil)
  9889    }
  9890  
  9891  partition_by:
  9892    PARTITION BY partition_by_inner
  9893    {
  9894      $$.val = $3.partitionBy()
  9895    }
  9896  
  9897  partition_by_inner:
  9898    LIST '(' name_list ')' '(' list_partitions ')'
  9899    {
  9900      $$.val = &tree.PartitionBy{
  9901        Fields: $3.nameList(),
  9902        List: $6.listPartitions(),
  9903      }
  9904    }
  9905  | RANGE '(' name_list ')' '(' range_partitions ')'
  9906    {
  9907      $$.val = &tree.PartitionBy{
  9908        Fields: $3.nameList(),
  9909        Range: $6.rangePartitions(),
  9910      }
  9911    }
  9912  | NOTHING
  9913    {
  9914      $$.val = (*tree.PartitionBy)(nil)
  9915    }
  9916  
  9917  list_partitions:
  9918    list_partition
  9919    {
  9920      $$.val = []tree.ListPartition{$1.listPartition()}
  9921    }
  9922  | list_partitions ',' list_partition
  9923    {
  9924      $$.val = append($1.listPartitions(), $3.listPartition())
  9925    }
  9926  
  9927  list_partition:
  9928    partition VALUES IN '(' expr_list ')' opt_partition_by
  9929    {
  9930      $$.val = tree.ListPartition{
  9931        Name: tree.Name($1),
  9932        Exprs: $5.exprs(),
  9933        Subpartition: $7.partitionBy(),
  9934      }
  9935    }
  9936  
  9937  range_partitions:
  9938    range_partition
  9939    {
  9940      $$.val = []tree.RangePartition{$1.rangePartition()}
  9941    }
  9942  | range_partitions ',' range_partition
  9943    {
  9944      $$.val = append($1.rangePartitions(), $3.rangePartition())
  9945    }
  9946  
  9947  range_partition:
  9948    partition VALUES FROM '(' expr_list ')' TO '(' expr_list ')' opt_partition_by
  9949    {
  9950      $$.val = tree.RangePartition{
  9951        Name: tree.Name($1),
  9952        From: $5.exprs(),
  9953        To: $9.exprs(),
  9954        Subpartition: $11.partitionBy(),
  9955      }
  9956    }
  9957  
  9958  // Treat SERIAL pseudo-types as separate case so that types.T does not have to
  9959  // support them as first-class types (e.g. they should not be supported as CAST
  9960  // target types).
  9961  column_table_def:
  9962    column_name typename col_qual_list
  9963    {
  9964      typ := $2.typeReference()
  9965      tableDef, err := tree.NewColumnTableDef(tree.Name($1), typ, tree.IsReferenceSerialType(typ), $3.colQuals())
  9966      if err != nil {
  9967        return setErr(sqllex, err)
  9968      }
  9969      $$.val = tableDef
  9970    }
  9971  
  9972  col_qual_list:
  9973    col_qual_list col_qualification
  9974    {
  9975      $$.val = append($1.colQuals(), $2.colQual())
  9976    }
  9977  | /* EMPTY */
  9978    {
  9979      $$.val = []tree.NamedColumnQualification(nil)
  9980    }
  9981  
  9982  col_qualification:
  9983    CONSTRAINT constraint_name col_qualification_elem
  9984    {
  9985      $$.val = tree.NamedColumnQualification{Name: tree.Name($2), Qualification: $3.colQualElem()}
  9986    }
  9987  | col_qualification_elem
  9988    {
  9989      $$.val = tree.NamedColumnQualification{Qualification: $1.colQualElem()}
  9990    }
  9991  | COLLATE collation_name
  9992    {
  9993      $$.val = tree.NamedColumnQualification{Qualification: tree.ColumnCollation($2)}
  9994    }
  9995  | FAMILY family_name
  9996    {
  9997      $$.val = tree.NamedColumnQualification{Qualification: &tree.ColumnFamilyConstraint{Family: tree.Name($2)}}
  9998    }
  9999  | CREATE FAMILY family_name
 10000    {
 10001      $$.val = tree.NamedColumnQualification{Qualification: &tree.ColumnFamilyConstraint{Family: tree.Name($3), Create: true}}
 10002    }
 10003  | CREATE FAMILY
 10004    {
 10005      $$.val = tree.NamedColumnQualification{Qualification: &tree.ColumnFamilyConstraint{Create: true}}
 10006    }
 10007  | CREATE IF NOT EXISTS FAMILY family_name
 10008    {
 10009      $$.val = tree.NamedColumnQualification{Qualification: &tree.ColumnFamilyConstraint{Family: tree.Name($6), Create: true, IfNotExists: true}}
 10010    }
 10011  
 10012  // DEFAULT NULL is already the default for Postgres. But define it here and
 10013  // carry it forward into the system to make it explicit.
 10014  // - thomas 1998-09-13
 10015  //
 10016  // WITH NULL and NULL are not SQL-standard syntax elements, so leave them
 10017  // out. Use DEFAULT NULL to explicitly indicate that a column may have that
 10018  // value. WITH NULL leads to shift/reduce conflicts with WITH TIME ZONE anyway.
 10019  // - thomas 1999-01-08
 10020  //
 10021  // DEFAULT expression must be b_expr not a_expr to prevent shift/reduce
 10022  // conflict on NOT (since NOT might start a subsequent NOT NULL constraint, or
 10023  // be part of a_expr NOT LIKE or similar constructs).
 10024  col_qualification_elem:
 10025    NOT NULL
 10026    {
 10027      $$.val = tree.NotNullConstraint{}
 10028    }
 10029  | NULL
 10030    {
 10031      $$.val = tree.NullConstraint{}
 10032    }
 10033  | NOT VISIBLE
 10034    {
 10035      $$.val = tree.HiddenConstraint{}
 10036    }
 10037  | UNIQUE opt_without_index
 10038    {
 10039      $$.val = tree.UniqueConstraint{
 10040        WithoutIndex: $2.bool(),
 10041      }
 10042    }
 10043  | PRIMARY KEY opt_with_storage_parameter_list
 10044    {
 10045      $$.val = tree.PrimaryKeyConstraint{
 10046        StorageParams: $3.storageParams(),
 10047      }
 10048    }
 10049  | PRIMARY KEY USING HASH opt_hash_sharded_bucket_count opt_with_storage_parameter_list
 10050  {
 10051    $$.val = tree.ShardedPrimaryKeyConstraint{
 10052      Sharded: true,
 10053      ShardBuckets: $5.expr(),
 10054      StorageParams: $6.storageParams(),
 10055    }
 10056  }
 10057  | CHECK '(' a_expr ')'
 10058    {
 10059      $$.val = &tree.ColumnCheckConstraint{Expr: $3.expr()}
 10060    }
 10061  | DEFAULT b_expr
 10062    {
 10063      $$.val = &tree.ColumnDefault{Expr: $2.expr()}
 10064    }
 10065  | ON UPDATE b_expr
 10066    {
 10067      $$.val = &tree.ColumnOnUpdate{Expr: $3.expr()}
 10068    }
 10069  | REFERENCES table_name opt_name_parens key_match reference_actions
 10070    {
 10071      name := $2.unresolvedObjectName().ToTableName()
 10072      $$.val = &tree.ColumnFKConstraint{
 10073        Table: name,
 10074        Col: tree.Name($3),
 10075        Actions: $5.referenceActions(),
 10076        Match: $4.compositeKeyMatchMethod(),
 10077      }
 10078    }
 10079  | generated_as '(' a_expr ')' STORED
 10080    {
 10081      $$.val = &tree.ColumnComputedDef{Expr: $3.expr(), Virtual: false}
 10082    }
 10083  | generated_as '(' a_expr ')' VIRTUAL
 10084    {
 10085      $$.val = &tree.ColumnComputedDef{Expr: $3.expr(), Virtual: true}
 10086    }
 10087  | generated_as error
 10088    {
 10089      sqllex.Error("use AS ( <expr> ) STORED or AS ( <expr> ) VIRTUAL")
 10090      return 1
 10091    }
 10092  | generated_always_as IDENTITY '(' opt_sequence_option_list ')'
 10093    {
 10094      $$.val = &tree.GeneratedAlwaysAsIdentity{
 10095         SeqOptions: $4.seqOpts(),
 10096      }
 10097    }
 10098  | generated_by_default_as IDENTITY '(' opt_sequence_option_list ')'
 10099    {
 10100      $$.val = &tree.GeneratedByDefAsIdentity{
 10101          SeqOptions: $4.seqOpts(),
 10102      }
 10103    }
 10104  | generated_always_as IDENTITY
 10105    {
 10106      $$.val = &tree.GeneratedAlwaysAsIdentity{}
 10107    }
 10108  | generated_by_default_as IDENTITY
 10109    {
 10110      $$.val = &tree.GeneratedByDefAsIdentity{}
 10111    }
 10112  
 10113  opt_without_index:
 10114    WITHOUT INDEX
 10115    {
 10116      /* SKIP DOC */
 10117      $$.val = true
 10118    }
 10119  | /* EMPTY */
 10120    {
 10121      $$.val = false
 10122    }
 10123  
 10124  generated_as:
 10125    AS {}
 10126  | generated_always_as
 10127  
 10128  generated_always_as:
 10129    GENERATED_ALWAYS ALWAYS AS {}
 10130  
 10131  generated_by_default_as:
 10132    GENERATED_BY_DEFAULT BY DEFAULT AS {}
 10133  
 10134  index_def:
 10135    INDEX_BEFORE_PAREN '(' index_params ')' opt_hash_sharded opt_storing opt_partition_by_index opt_with_storage_parameter_list opt_where_clause opt_index_visible
 10136    {
 10137      $$.val = &tree.IndexTableDef{
 10138        Name:             "",
 10139        Columns:          $3.idxElems(),
 10140        Sharded:          $5.shardedIndexDef(),
 10141        Storing:          $6.nameList(),
 10142        PartitionByIndex: $7.partitionByIndex(),
 10143        StorageParams:    $8.storageParams(),
 10144        Predicate:        $9.expr(),
 10145        Invisibility:     $10.indexInvisibility(),
 10146      }
 10147    }
 10148  | INDEX_BEFORE_NAME_THEN_PAREN name '(' index_params ')' opt_hash_sharded opt_storing opt_partition_by_index opt_with_storage_parameter_list opt_where_clause opt_index_visible
 10149    {
 10150      $$.val = &tree.IndexTableDef{
 10151        Name:             tree.Name($2),
 10152        Columns:          $4.idxElems(),
 10153        Sharded:          $6.shardedIndexDef(),
 10154        Storing:          $7.nameList(),
 10155        PartitionByIndex: $8.partitionByIndex(),
 10156        StorageParams:    $9.storageParams(),
 10157        Predicate:        $10.expr(),
 10158        Invisibility:     $11.indexInvisibility(),
 10159      }
 10160    }
 10161  | UNIQUE INDEX opt_index_name '(' index_params ')' opt_hash_sharded opt_storing opt_partition_by_index opt_with_storage_parameter_list opt_where_clause opt_index_visible
 10162    {
 10163      $$.val = &tree.UniqueConstraintTableDef{
 10164        IndexTableDef: tree.IndexTableDef {
 10165          Name:             tree.Name($3),
 10166          Columns:          $5.idxElems(),
 10167          Sharded:          $7.shardedIndexDef(),
 10168          Storing:          $8.nameList(),
 10169          PartitionByIndex: $9.partitionByIndex(),
 10170          StorageParams:    $10.storageParams(),
 10171          Predicate:        $11.expr(),
 10172          Invisibility:     $12.indexInvisibility(),
 10173        },
 10174      }
 10175    }
 10176  | INVERTED INDEX_BEFORE_PAREN '(' index_params ')' opt_partition_by_index opt_with_storage_parameter_list opt_where_clause opt_index_visible
 10177    {
 10178      $$.val = &tree.IndexTableDef{
 10179        Name:             "",
 10180        Columns:          $4.idxElems(),
 10181        Inverted:         true,
 10182        PartitionByIndex: $6.partitionByIndex(),
 10183        StorageParams:    $7.storageParams(),
 10184        Predicate:        $8.expr(),
 10185        Invisibility:     $9.indexInvisibility(),
 10186      }
 10187    }
 10188  | INVERTED INDEX_BEFORE_NAME_THEN_PAREN name '(' index_params ')' opt_partition_by_index opt_with_storage_parameter_list opt_where_clause opt_index_visible
 10189    {
 10190      $$.val = &tree.IndexTableDef{
 10191        Name:             tree.Name($3),
 10192        Columns:          $5.idxElems(),
 10193        Inverted:         true,
 10194        PartitionByIndex: $7.partitionByIndex(),
 10195        StorageParams:    $8.storageParams(),
 10196        Predicate:        $9.expr(),
 10197        Invisibility:     $10.indexInvisibility(),
 10198      }
 10199    }
 10200  
 10201  family_def:
 10202    FAMILY opt_family_name '(' name_list ')'
 10203    {
 10204      $$.val = &tree.FamilyTableDef{
 10205        Name: tree.Name($2),
 10206        Columns: $4.nameList(),
 10207      }
 10208    }
 10209  
 10210  // constraint_elem specifies constraint syntax which is not embedded into a
 10211  // column definition. col_qualification_elem specifies the embedded form.
 10212  // - thomas 1997-12-03
 10213  table_constraint:
 10214    CONSTRAINT constraint_name constraint_elem
 10215    {
 10216      $$.val = $3.constraintDef()
 10217      $$.val.(tree.ConstraintTableDef).SetName(tree.Name($2))
 10218    }
 10219  | constraint_elem
 10220    {
 10221      $$.val = $1.constraintDef()
 10222    }
 10223  
 10224  constraint_elem:
 10225    CHECK '(' a_expr ')' opt_deferrable
 10226    {
 10227      $$.val = &tree.CheckConstraintTableDef{
 10228        Expr: $3.expr(),
 10229      }
 10230    }
 10231  | UNIQUE opt_without_index '(' index_params ')'
 10232      opt_storing opt_partition_by_index opt_deferrable opt_where_clause
 10233    {
 10234      $$.val = &tree.UniqueConstraintTableDef{
 10235        WithoutIndex: $2.bool(),
 10236        IndexTableDef: tree.IndexTableDef{
 10237          Columns: $4.idxElems(),
 10238          Storing: $6.nameList(),
 10239          PartitionByIndex: $7.partitionByIndex(),
 10240          Predicate: $9.expr(),
 10241        },
 10242      }
 10243    }
 10244  | PRIMARY KEY '(' index_params ')' opt_hash_sharded opt_with_storage_parameter_list
 10245    {
 10246      $$.val = &tree.UniqueConstraintTableDef{
 10247        IndexTableDef: tree.IndexTableDef{
 10248          Columns: $4.idxElems(),
 10249          Sharded: $6.shardedIndexDef(),
 10250          StorageParams: $7.storageParams(),
 10251        },
 10252        PrimaryKey: true,
 10253      }
 10254    }
 10255  | FOREIGN KEY '(' name_list ')' REFERENCES table_name
 10256      opt_column_list key_match reference_actions opt_deferrable
 10257    {
 10258      name := $7.unresolvedObjectName().ToTableName()
 10259      $$.val = &tree.ForeignKeyConstraintTableDef{
 10260        Table: name,
 10261        FromCols: $4.nameList(),
 10262        ToCols: $8.nameList(),
 10263        Match: $9.compositeKeyMatchMethod(),
 10264        Actions: $10.referenceActions(),
 10265      }
 10266    }
 10267  | EXCLUDE USING error
 10268    {
 10269      return unimplementedWithIssueDetail(sqllex, 46657, "add constraint exclude using")
 10270    }
 10271  
 10272  
 10273  create_as_opt_col_list:
 10274    '(' create_as_table_defs ')'
 10275    {
 10276      $$.val = $2.val
 10277    }
 10278  | /* EMPTY */
 10279    {
 10280      $$.val = tree.TableDefs(nil)
 10281    }
 10282  
 10283  create_as_table_defs:
 10284    column_name create_as_col_qual_list
 10285    {
 10286      tableDef, err := tree.NewColumnTableDef(tree.Name($1), nil, false, $2.colQuals())
 10287      if err != nil {
 10288        return setErr(sqllex, err)
 10289      }
 10290  
 10291      var colToTableDef tree.TableDef = tableDef
 10292      $$.val = tree.TableDefs{colToTableDef}
 10293    }
 10294  | create_as_table_defs ',' column_name create_as_col_qual_list
 10295    {
 10296      tableDef, err := tree.NewColumnTableDef(tree.Name($3), nil, false, $4.colQuals())
 10297      if err != nil {
 10298        return setErr(sqllex, err)
 10299      }
 10300  
 10301      var colToTableDef tree.TableDef = tableDef
 10302  
 10303      $$.val = append($1.tblDefs(), colToTableDef)
 10304    }
 10305  | create_as_table_defs ',' family_def
 10306    {
 10307      $$.val = append($1.tblDefs(), $3.tblDef())
 10308    }
 10309  | create_as_table_defs ',' create_as_constraint_def
 10310  {
 10311    var constraintToTableDef tree.TableDef = $3.constraintDef()
 10312    $$.val = append($1.tblDefs(), constraintToTableDef)
 10313  }
 10314  
 10315  create_as_constraint_def:
 10316    create_as_constraint_elem
 10317    {
 10318      $$.val = $1.constraintDef()
 10319    }
 10320  
 10321  create_as_constraint_elem:
 10322    PRIMARY KEY '(' create_as_params ')' opt_with_storage_parameter_list
 10323    {
 10324      $$.val = &tree.UniqueConstraintTableDef{
 10325        IndexTableDef: tree.IndexTableDef{
 10326          Columns: $4.idxElems(),
 10327          StorageParams: $6.storageParams(),
 10328        },
 10329        PrimaryKey:    true,
 10330      }
 10331    }
 10332  
 10333  create_as_params:
 10334    create_as_param
 10335    {
 10336      $$.val = tree.IndexElemList{$1.idxElem()}
 10337    }
 10338  | create_as_params ',' create_as_param
 10339    {
 10340      $$.val = append($1.idxElems(), $3.idxElem())
 10341    }
 10342  
 10343  create_as_param:
 10344    column_name
 10345    {
 10346      $$.val = tree.IndexElem{Column: tree.Name($1)}
 10347    }
 10348  
 10349  create_as_col_qual_list:
 10350    create_as_col_qual_list create_as_col_qualification
 10351    {
 10352      $$.val = append($1.colQuals(), $2.colQual())
 10353    }
 10354  | /* EMPTY */
 10355    {
 10356      $$.val = []tree.NamedColumnQualification(nil)
 10357    }
 10358  
 10359  create_as_col_qualification:
 10360    create_as_col_qualification_elem
 10361    {
 10362      $$.val = tree.NamedColumnQualification{Qualification: $1.colQualElem()}
 10363    }
 10364  | FAMILY family_name
 10365    {
 10366      $$.val = tree.NamedColumnQualification{Qualification: &tree.ColumnFamilyConstraint{Family: tree.Name($2)}}
 10367    }
 10368  
 10369  create_as_col_qualification_elem:
 10370    PRIMARY KEY opt_with_storage_parameter_list
 10371    {
 10372      $$.val = tree.PrimaryKeyConstraint{
 10373        StorageParams: $3.storageParams(),
 10374      }
 10375    }
 10376  
 10377  opt_deferrable:
 10378    /* EMPTY */ { /* no error */ }
 10379  | DEFERRABLE { return unimplementedWithIssueDetail(sqllex, 31632, "deferrable") }
 10380  | DEFERRABLE INITIALLY DEFERRED { return unimplementedWithIssueDetail(sqllex, 31632, "def initially deferred") }
 10381  | DEFERRABLE INITIALLY IMMEDIATE { return unimplementedWithIssueDetail(sqllex, 31632, "def initially immediate") }
 10382  | INITIALLY DEFERRED { return unimplementedWithIssueDetail(sqllex, 31632, "initially deferred") }
 10383  | INITIALLY IMMEDIATE { return unimplementedWithIssueDetail(sqllex, 31632, "initially immediate") }
 10384  
 10385  storing:
 10386    COVERING
 10387  | STORING
 10388  | INCLUDE
 10389  
 10390  // TODO(pmattis): It would be nice to support a syntax like STORING
 10391  // ALL or STORING (*). The syntax addition is straightforward, but we
 10392  // need to be careful with the rest of the implementation. In
 10393  // particular, columns stored at indexes are currently encoded in such
 10394  // a way that adding a new column would require rewriting the existing
 10395  // index values. We will need to change the storage format so that it
 10396  // is a list of <columnID, value> pairs which will allow both adding
 10397  // and dropping columns without rewriting indexes that are storing the
 10398  // adjusted column.
 10399  opt_storing:
 10400    storing '(' name_list ')'
 10401    {
 10402      $$.val = $3.nameList()
 10403    }
 10404  | /* EMPTY */
 10405    {
 10406      $$.val = tree.NameList(nil)
 10407    }
 10408  
 10409  opt_hash_sharded:
 10410    USING HASH opt_hash_sharded_bucket_count
 10411    {
 10412      $$.val = &tree.ShardedIndexDef{
 10413        ShardBuckets: $3.expr(),
 10414      }
 10415    }
 10416    | /* EMPTY */
 10417    {
 10418      $$.val = (*tree.ShardedIndexDef)(nil)
 10419    }
 10420  
 10421  opt_hash_sharded_bucket_count:
 10422    WITH_LA BUCKET_COUNT '=' a_expr
 10423    {
 10424      $$.val = $4.expr()
 10425    }
 10426    |
 10427    {
 10428      $$.val = tree.DefaultVal{}
 10429    }
 10430  
 10431  opt_column_list:
 10432    '(' name_list ')'
 10433    {
 10434      $$.val = $2.nameList()
 10435    }
 10436  | /* EMPTY */
 10437    {
 10438      $$.val = tree.NameList(nil)
 10439    }
 10440  
 10441  // https://www.postgresql.org/docs/10/sql-createtable.html
 10442  //
 10443  // "A value inserted into the referencing column(s) is matched against
 10444  // the values of the referenced table and referenced columns using the
 10445  // given match type. There are three match types: MATCH FULL, MATCH
 10446  // PARTIAL, and MATCH SIMPLE (which is the default). MATCH FULL will
 10447  // not allow one column of a multicolumn foreign key to be null unless
 10448  // all foreign key columns are null; if they are all null, the row is
 10449  // not required to have a match in the referenced table. MATCH SIMPLE
 10450  // allows any of the foreign key columns to be null; if any of them
 10451  // are null, the row is not required to have a match in the referenced
 10452  // table. MATCH PARTIAL is not yet implemented. (Of course, NOT NULL
 10453  // constraints can be applied to the referencing column(s) to prevent
 10454  // these cases from arising.)"
 10455  key_match:
 10456    MATCH SIMPLE
 10457    {
 10458      $$.val = tree.MatchSimple
 10459    }
 10460  | MATCH FULL
 10461    {
 10462      $$.val = tree.MatchFull
 10463    }
 10464  | MATCH PARTIAL
 10465    {
 10466      return unimplementedWithIssueDetail(sqllex, 20305, "match partial")
 10467    }
 10468  | /* EMPTY */
 10469    {
 10470      $$.val = tree.MatchSimple
 10471    }
 10472  
 10473  // We combine the update and delete actions into one value temporarily for
 10474  // simplicity of parsing, and then break them down again in the calling
 10475  // production.
 10476  reference_actions:
 10477    reference_on_update
 10478    {
 10479       $$.val = tree.ReferenceActions{Update: $1.referenceAction()}
 10480    }
 10481  | reference_on_delete
 10482    {
 10483       $$.val = tree.ReferenceActions{Delete: $1.referenceAction()}
 10484    }
 10485  | reference_on_update reference_on_delete
 10486    {
 10487      $$.val = tree.ReferenceActions{Update: $1.referenceAction(), Delete: $2.referenceAction()}
 10488    }
 10489  | reference_on_delete reference_on_update
 10490    {
 10491      $$.val = tree.ReferenceActions{Delete: $1.referenceAction(), Update: $2.referenceAction()}
 10492    }
 10493  | /* EMPTY */
 10494    {
 10495      $$.val = tree.ReferenceActions{}
 10496    }
 10497  
 10498  reference_on_update:
 10499    ON_LA UPDATE reference_action
 10500    {
 10501      $$.val = $3.referenceAction()
 10502    }
 10503  
 10504  reference_on_delete:
 10505    ON_LA DELETE reference_action
 10506    {
 10507      $$.val = $3.referenceAction()
 10508    }
 10509  
 10510  reference_action:
 10511  // NO ACTION is currently the default behavior. It is functionally the same as
 10512  // RESTRICT.
 10513    NO ACTION
 10514    {
 10515      $$.val = tree.NoAction
 10516    }
 10517  | RESTRICT
 10518    {
 10519      $$.val = tree.Restrict
 10520    }
 10521  | CASCADE
 10522    {
 10523      $$.val = tree.Cascade
 10524    }
 10525  | SET NULL
 10526    {
 10527      $$.val = tree.SetNull
 10528    }
 10529  | SET DEFAULT
 10530    {
 10531      $$.val = tree.SetDefault
 10532    }
 10533  
 10534  // %Help: CREATE SEQUENCE - create a new sequence
 10535  // %Category: DDL
 10536  // %Text:
 10537  // CREATE [TEMPORARY | TEMP] SEQUENCE <seqname>
 10538  //   [AS <typename>]
 10539  //   [INCREMENT <increment>]
 10540  //   [MINVALUE <minvalue> | NO MINVALUE]
 10541  //   [MAXVALUE <maxvalue> | NO MAXVALUE]
 10542  //   [START [WITH] <start>]
 10543  //   [CACHE <cache>]
 10544  //   [NO CYCLE]
 10545  //   [VIRTUAL]
 10546  //
 10547  // %SeeAlso: CREATE TABLE
 10548  create_sequence_stmt:
 10549    CREATE opt_temp SEQUENCE sequence_name opt_sequence_option_list
 10550    {
 10551      name := $4.unresolvedObjectName().ToTableName()
 10552      $$.val = &tree.CreateSequence {
 10553        Name: name,
 10554        Persistence: $2.persistence(),
 10555        Options: $5.seqOpts(),
 10556      }
 10557    }
 10558  | CREATE opt_temp SEQUENCE IF NOT EXISTS sequence_name opt_sequence_option_list
 10559    {
 10560      name := $7.unresolvedObjectName().ToTableName()
 10561      $$.val = &tree.CreateSequence {
 10562        Name: name, Options: $8.seqOpts(),
 10563        Persistence: $2.persistence(),
 10564        IfNotExists: true,
 10565      }
 10566    }
 10567  | CREATE opt_temp SEQUENCE error // SHOW HELP: CREATE SEQUENCE
 10568  
 10569  opt_sequence_option_list:
 10570    sequence_option_list
 10571  | /* EMPTY */          { $$.val = []tree.SequenceOption(nil) }
 10572  
 10573  sequence_option_list:
 10574    sequence_option_elem                       { $$.val = []tree.SequenceOption{$1.seqOpt()} }
 10575  | sequence_option_list sequence_option_elem  { $$.val = append($1.seqOpts(), $2.seqOpt()) }
 10576  
 10577  sequence_option_elem:
 10578    AS typename                  {
 10579                                    // Valid option values must be integer types (ex. int2, bigint)
 10580                                    parsedType := $2.colType()
 10581                                    if parsedType == nil {
 10582                                        sqllex.(*lexer).lastError = pgerror.Newf(pgcode.UndefinedObject, "type %q does not exist", $2.val)
 10583                                        sqllex.(*lexer).populateErrorDetails()
 10584                                        return 1
 10585                                    }
 10586                                    if parsedType.Family() != types.IntFamily {
 10587                                        sqllex.Error(fmt.Sprintf("invalid integer type: %s", parsedType.SQLString()))
 10588                                        return 1
 10589                                    }
 10590                                    $$.val = tree.SequenceOption{Name: tree.SeqOptAs, AsIntegerType: parsedType}
 10591                                  }
 10592  | CYCLE                        { /* SKIP DOC */
 10593                                   $$.val = tree.SequenceOption{Name: tree.SeqOptCycle} }
 10594  | NO CYCLE                     { $$.val = tree.SequenceOption{Name: tree.SeqOptNoCycle} }
 10595  | OWNED BY NONE                { $$.val = tree.SequenceOption{Name: tree.SeqOptOwnedBy, ColumnItemVal: nil} }
 10596  | OWNED BY column_path         { varName, err := $3.unresolvedName().NormalizeVarName()
 10597                                       if err != nil {
 10598                                         return setErr(sqllex, err)
 10599                                       }
 10600                                       columnItem, ok := varName.(*tree.ColumnItem)
 10601                                       if !ok {
 10602                                         sqllex.Error(fmt.Sprintf("invalid column name: %q", tree.ErrString($3.unresolvedName())))
 10603                                               return 1
 10604                                       }
 10605                                   $$.val = tree.SequenceOption{Name: tree.SeqOptOwnedBy, ColumnItemVal: columnItem} }
 10606  | CACHE signed_iconst64        { x := $2.int64()
 10607                                   $$.val = tree.SequenceOption{Name: tree.SeqOptCache, IntVal: &x} }
 10608  | INCREMENT signed_iconst64    { x := $2.int64()
 10609                                   $$.val = tree.SequenceOption{Name: tree.SeqOptIncrement, IntVal: &x} }
 10610  | INCREMENT BY signed_iconst64 { x := $3.int64()
 10611                                   $$.val = tree.SequenceOption{Name: tree.SeqOptIncrement, IntVal: &x, OptionalWord: true} }
 10612  | MINVALUE signed_iconst64     { x := $2.int64()
 10613                                   $$.val = tree.SequenceOption{Name: tree.SeqOptMinValue, IntVal: &x} }
 10614  | NO MINVALUE                  { $$.val = tree.SequenceOption{Name: tree.SeqOptMinValue} }
 10615  | MAXVALUE signed_iconst64     { x := $2.int64()
 10616                                   $$.val = tree.SequenceOption{Name: tree.SeqOptMaxValue, IntVal: &x} }
 10617  | NO MAXVALUE                  { $$.val = tree.SequenceOption{Name: tree.SeqOptMaxValue} }
 10618  | START signed_iconst64        { x := $2.int64()
 10619                                   $$.val = tree.SequenceOption{Name: tree.SeqOptStart, IntVal: &x} }
 10620  | START WITH signed_iconst64   { x := $3.int64()
 10621                                   $$.val = tree.SequenceOption{Name: tree.SeqOptStart, IntVal: &x, OptionalWord: true} }
 10622  | RESTART                      { $$.val = tree.SequenceOption{Name: tree.SeqOptRestart} }
 10623  | RESTART signed_iconst64      { x := $2.int64()
 10624                                   $$.val = tree.SequenceOption{Name: tree.SeqOptRestart, IntVal: &x} }
 10625  | RESTART WITH signed_iconst64 { x := $3.int64()
 10626                                   $$.val = tree.SequenceOption{Name: tree.SeqOptRestart, IntVal: &x, OptionalWord: true} }
 10627  
 10628  | VIRTUAL                      { $$.val = tree.SequenceOption{Name: tree.SeqOptVirtual} }
 10629  
 10630  // %Help: TRUNCATE - empty one or more tables
 10631  // %Category: DML
 10632  // %Text: TRUNCATE [TABLE] <tablename> [, ...] [CASCADE | RESTRICT]
 10633  // %SeeAlso: WEBDOCS/truncate.html
 10634  truncate_stmt:
 10635    TRUNCATE opt_table relation_expr_list opt_drop_behavior
 10636    {
 10637      $$.val = &tree.Truncate{Tables: $3.tableNames(), DropBehavior: $4.dropBehavior()}
 10638    }
 10639  | TRUNCATE error // SHOW HELP: TRUNCATE
 10640  
 10641  password_clause:
 10642    ENCRYPTED PASSWORD sconst_or_placeholder
 10643    {
 10644      /* SKIP DOC */
 10645      // This is a legacy postgres syntax.
 10646      $$.val = tree.KVOption{Key: tree.Name($2), Value: $3.expr()}
 10647    }
 10648  | PASSWORD sconst_or_placeholder
 10649    {
 10650      $$.val = tree.KVOption{Key: tree.Name($1), Value: $2.expr()}
 10651    }
 10652  | PASSWORD NULL
 10653    {
 10654      $$.val = tree.KVOption{Key: tree.Name($1), Value: tree.DNull}
 10655    }
 10656  
 10657  // %Help: CREATE ROLE - define a new role
 10658  // %Category: Priv
 10659  // %Text: CREATE ROLE [IF NOT EXISTS] <name> [ [WITH] <OPTIONS...> ]
 10660  // %SeeAlso: ALTER ROLE, DROP ROLE, SHOW ROLES
 10661  create_role_stmt:
 10662    CREATE role_or_group_or_user role_spec opt_role_options
 10663    {
 10664      $$.val = &tree.CreateRole{Name: $3.roleSpec(), KVOptions: $4.kvOptions(), IsRole: $2.bool()}
 10665    }
 10666  | CREATE role_or_group_or_user IF NOT EXISTS role_spec opt_role_options
 10667    {
 10668      $$.val = &tree.CreateRole{Name: $6.roleSpec(), IfNotExists: true, KVOptions: $7.kvOptions(), IsRole: $2.bool()}
 10669    }
 10670  | CREATE role_or_group_or_user error // SHOW HELP: CREATE ROLE
 10671  
 10672  // %Help: ALTER ROLE - alter a role
 10673  // %Category: Priv
 10674  // %Text:
 10675  // ALTER ROLE <name> [WITH] <options...>
 10676  // ALTER ROLE { name | ALL } [ IN DATABASE database_name ] SET var { TO | = } { value | DEFAULT }
 10677  // ALTER ROLE { name | ALL } [ IN DATABASE database_name ] RESET { var | ALL }
 10678  // %SeeAlso: CREATE ROLE, DROP ROLE, SHOW ROLES
 10679  alter_role_stmt:
 10680    ALTER role_or_group_or_user role_spec opt_role_options
 10681  {
 10682    $$.val = &tree.AlterRole{Name: $3.roleSpec(), KVOptions: $4.kvOptions(), IsRole: $2.bool()}
 10683  }
 10684  | ALTER role_or_group_or_user IF EXISTS role_spec opt_role_options
 10685  {
 10686    $$.val = &tree.AlterRole{Name: $5.roleSpec(), IfExists: true, KVOptions: $6.kvOptions(), IsRole: $2.bool()}
 10687  }
 10688  | ALTER role_or_group_or_user role_spec opt_in_database set_or_reset_clause
 10689    {
 10690      $$.val = &tree.AlterRoleSet{RoleName: $3.roleSpec(), DatabaseName: tree.Name($4), IsRole: $2.bool(), SetOrReset: $5.setVar()}
 10691    }
 10692  | ALTER role_or_group_or_user IF EXISTS role_spec opt_in_database set_or_reset_clause
 10693    {
 10694      $$.val = &tree.AlterRoleSet{RoleName: $5.roleSpec(), IfExists: true, DatabaseName: tree.Name($6), IsRole: $2.bool(), SetOrReset: $7.setVar()}
 10695    }
 10696  | ALTER ROLE_ALL ALL opt_in_database set_or_reset_clause
 10697    {
 10698      $$.val = &tree.AlterRoleSet{AllRoles: true, DatabaseName: tree.Name($4), IsRole: true, SetOrReset: $5.setVar()}
 10699    }
 10700  | ALTER USER_ALL ALL opt_in_database set_or_reset_clause
 10701    {
 10702      $$.val = &tree.AlterRoleSet{AllRoles: true, DatabaseName: tree.Name($4), IsRole: false, SetOrReset: $5.setVar()}
 10703    }
 10704  | ALTER role_or_group_or_user error // SHOW HELP: ALTER ROLE
 10705  
 10706  opt_in_database:
 10707    IN DATABASE database_name
 10708    {
 10709      $$ = $3
 10710    }
 10711  | /* EMPTY */
 10712    {
 10713      $$ = ""
 10714    }
 10715  
 10716  // This rule is used when SET is used as a clause in another statement,
 10717  // like ALTER ROLE ... SET.
 10718  set_or_reset_clause:
 10719    SET set_rest
 10720    {
 10721      $$.val = $2.setVar()
 10722    }
 10723  | SET_TRACING set_rest
 10724    {
 10725      /* SKIP DOC */
 10726      // We need to recognize the "set tracing" specially here since we do a
 10727      // syntax lookahead and use a different token.
 10728      $$.val = $2.setVar()
 10729    }
 10730  | RESET_ALL ALL
 10731    {
 10732      $$.val = &tree.SetVar{ResetAll: true}
 10733    }
 10734  | RESET session_var
 10735    {
 10736      $$.val = &tree.SetVar{Name: $2, Values:tree.Exprs{tree.DefaultVal{}}}
 10737    }
 10738  
 10739  // "CREATE GROUP is now an alias for CREATE ROLE"
 10740  // https://www.postgresql.org/docs/10/static/sql-creategroup.html
 10741  role_or_group_or_user:
 10742    ROLE
 10743    {
 10744      $$.val = true
 10745    }
 10746  | GROUP
 10747    {
 10748      /* SKIP DOC */
 10749      $$.val = true
 10750    }
 10751  | USER
 10752    {
 10753      $$.val = false
 10754    }
 10755  
 10756  // %Help: CREATE VIEW - create a new view
 10757  // %Category: DDL
 10758  // %Text:
 10759  // CREATE [TEMPORARY | TEMP] VIEW [IF NOT EXISTS] <viewname> [( <colnames...> )] AS <source>
 10760  // CREATE [TEMPORARY | TEMP] MATERIALIZED VIEW [IF NOT EXISTS] <viewname> [( <colnames...> )] AS <source> [WITH [NO] DATA]
 10761  // %SeeAlso: CREATE TABLE, SHOW CREATE, WEBDOCS/create-view.html
 10762  create_view_stmt:
 10763    CREATE opt_temp opt_view_recursive VIEW view_name opt_column_list AS select_stmt
 10764    {
 10765      name := $5.unresolvedObjectName().ToTableName()
 10766      $$.val = &tree.CreateView{
 10767        Name: name,
 10768        ColumnNames: $6.nameList(),
 10769        AsSource: $8.slct(),
 10770        Persistence: $2.persistence(),
 10771        IfNotExists: false,
 10772        Replace: false,
 10773      }
 10774    }
 10775  // We cannot use a rule like opt_or_replace here as that would cause a conflict
 10776  // with the opt_temp rule.
 10777  | CREATE OR REPLACE opt_temp opt_view_recursive VIEW view_name opt_column_list AS select_stmt
 10778    {
 10779      name := $7.unresolvedObjectName().ToTableName()
 10780      $$.val = &tree.CreateView{
 10781        Name: name,
 10782        ColumnNames: $8.nameList(),
 10783        AsSource: $10.slct(),
 10784        Persistence: $4.persistence(),
 10785        IfNotExists: false,
 10786        Replace: true,
 10787      }
 10788    }
 10789  | CREATE opt_temp opt_view_recursive VIEW IF NOT EXISTS view_name opt_column_list AS select_stmt
 10790    {
 10791      name := $8.unresolvedObjectName().ToTableName()
 10792      $$.val = &tree.CreateView{
 10793        Name: name,
 10794        ColumnNames: $9.nameList(),
 10795        AsSource: $11.slct(),
 10796        Persistence: $2.persistence(),
 10797        IfNotExists: true,
 10798        Replace: false,
 10799      }
 10800    }
 10801  | CREATE MATERIALIZED VIEW view_name opt_column_list AS select_stmt opt_with_data
 10802    {
 10803      name := $4.unresolvedObjectName().ToTableName()
 10804      $$.val = &tree.CreateView{
 10805        Name: name,
 10806        ColumnNames: $5.nameList(),
 10807        AsSource: $7.slct(),
 10808        Materialized: true,
 10809        WithData: $8.bool(),
 10810      }
 10811    }
 10812  | CREATE MATERIALIZED VIEW IF NOT EXISTS view_name opt_column_list AS select_stmt opt_with_data
 10813    {
 10814      name := $7.unresolvedObjectName().ToTableName()
 10815      $$.val = &tree.CreateView{
 10816        Name: name,
 10817        ColumnNames: $8.nameList(),
 10818        AsSource: $10.slct(),
 10819        Materialized: true,
 10820        IfNotExists: true,
 10821        WithData: $11.bool(),
 10822      }
 10823    }
 10824  | CREATE opt_temp opt_view_recursive VIEW error // SHOW HELP: CREATE VIEW
 10825  
 10826  opt_with_data:
 10827    WITH NO DATA error
 10828    {
 10829      $$.val = false
 10830    }
 10831  | WITH DATA
 10832    {
 10833      $$.val = true
 10834    }
 10835  | /* EMPTY */
 10836    {
 10837      $$.val = true
 10838    }
 10839  
 10840  role_option:
 10841    CREATEROLE
 10842    {
 10843      $$.val = tree.KVOption{Key: tree.Name($1), Value: nil}
 10844    }
 10845  | NOCREATEROLE
 10846    {
 10847      $$.val = tree.KVOption{Key: tree.Name($1), Value: nil}
 10848    }
 10849  | LOGIN
 10850    {
 10851      $$.val = tree.KVOption{Key: tree.Name($1), Value: nil}
 10852    }
 10853  | NOLOGIN
 10854    {
 10855      $$.val = tree.KVOption{Key: tree.Name($1), Value: nil}
 10856    }
 10857  | CONTROLJOB
 10858    {
 10859      $$.val = tree.KVOption{Key: tree.Name($1), Value: nil}
 10860    }
 10861  | NOCONTROLJOB
 10862    {
 10863     $$.val = tree.KVOption{Key: tree.Name($1), Value: nil}
 10864    }
 10865  | CONTROLCHANGEFEED
 10866    {
 10867      $$.val = tree.KVOption{Key: tree.Name($1), Value: nil}
 10868    }
 10869  | NOCONTROLCHANGEFEED
 10870    {
 10871      $$.val = tree.KVOption{Key: tree.Name($1), Value: nil}
 10872    }
 10873  | CREATEDB
 10874    {
 10875      $$.val = tree.KVOption{Key: tree.Name($1), Value: nil}
 10876    }
 10877  | NOCREATEDB
 10878    {
 10879      $$.val = tree.KVOption{Key: tree.Name($1), Value: nil}
 10880    }
 10881  | CREATELOGIN
 10882    {
 10883      $$.val = tree.KVOption{Key: tree.Name($1), Value: nil}
 10884    }
 10885  | NOCREATELOGIN
 10886    {
 10887      $$.val = tree.KVOption{Key: tree.Name($1), Value: nil}
 10888    }
 10889  | VIEWACTIVITY
 10890    {
 10891      $$.val = tree.KVOption{Key: tree.Name($1), Value: nil}
 10892    }
 10893  | NOVIEWACTIVITY
 10894    {
 10895      $$.val = tree.KVOption{Key: tree.Name($1), Value: nil}
 10896    }
 10897  | VIEWACTIVITYREDACTED
 10898    {
 10899      $$.val = tree.KVOption{Key: tree.Name($1), Value: nil}
 10900    }
 10901  | NOVIEWACTIVITYREDACTED
 10902    {
 10903      $$.val = tree.KVOption{Key: tree.Name($1), Value: nil}
 10904    }
 10905  | CANCELQUERY
 10906    {
 10907      $$.val = tree.KVOption{Key: tree.Name($1), Value: nil}
 10908    }
 10909  | NOCANCELQUERY
 10910    {
 10911      $$.val = tree.KVOption{Key: tree.Name($1), Value: nil}
 10912    }
 10913  | MODIFYCLUSTERSETTING
 10914    {
 10915      $$.val = tree.KVOption{Key: tree.Name($1), Value: nil}
 10916    }
 10917  | NOMODIFYCLUSTERSETTING
 10918    {
 10919      $$.val = tree.KVOption{Key: tree.Name($1), Value: nil}
 10920    }
 10921  | SQLLOGIN
 10922    {
 10923      $$.val = tree.KVOption{Key: tree.Name($1), Value: nil}
 10924    }
 10925  | NOSQLLOGIN
 10926    {
 10927      $$.val = tree.KVOption{Key: tree.Name($1), Value: nil}
 10928    }
 10929  | VIEWCLUSTERSETTING
 10930    {
 10931      $$.val = tree.KVOption{Key: tree.Name($1), Value: nil}
 10932    }
 10933  | NOVIEWCLUSTERSETTING
 10934    {
 10935      $$.val = tree.KVOption{Key: tree.Name($1), Value: nil}
 10936    }
 10937  | password_clause
 10938  | valid_until_clause
 10939  | REPLICATION
 10940    {
 10941      $$.val = tree.KVOption{Key: tree.Name($1), Value: nil}
 10942    }
 10943  | NOREPLICATION
 10944    {
 10945      $$.val = tree.KVOption{Key: tree.Name($1), Value: nil}
 10946    }
 10947  
 10948  role_options:
 10949    role_option
 10950    {
 10951      $$.val = []tree.KVOption{$1.kvOption()}
 10952    }
 10953  | role_options role_option
 10954    {
 10955      $$.val = append($1.kvOptions(), $2.kvOption())
 10956    }
 10957  
 10958  opt_role_options:
 10959    opt_with role_options
 10960    {
 10961      $$.val = $2.kvOptions()
 10962    }
 10963  | /* EMPTY */
 10964    {
 10965      $$.val = nil
 10966    }
 10967  
 10968  valid_until_clause:
 10969    VALID UNTIL string_or_placeholder
 10970    {
 10971      $$.val = tree.KVOption{Key: tree.Name("valid until"), Value: $3.expr()}
 10972    }
 10973  | VALID UNTIL NULL
 10974    {
 10975      $$.val = tree.KVOption{Key: tree.Name("valid until"), Value: tree.DNull}
 10976    }
 10977  
 10978  opt_view_recursive:
 10979    /* EMPTY */ { /* no error */ }
 10980  | RECURSIVE { return unimplemented(sqllex, "create recursive view") }
 10981  
 10982  
 10983  // %Help: CREATE TYPE - create a type
 10984  // %Category: DDL
 10985  // %Text: CREATE TYPE [IF NOT EXISTS] <type_name> AS ENUM (...)
 10986  create_type_stmt:
 10987    // Enum types.
 10988    CREATE TYPE type_name AS ENUM '(' opt_enum_val_list ')'
 10989    {
 10990      $$.val = &tree.CreateType{
 10991        TypeName: $3.unresolvedObjectName(),
 10992        Variety: tree.Enum,
 10993        EnumLabels: $7.enumValueList(),
 10994      }
 10995    }
 10996  | CREATE TYPE IF NOT EXISTS type_name AS ENUM '(' opt_enum_val_list ')'
 10997    {
 10998      $$.val = &tree.CreateType{
 10999        TypeName: $6.unresolvedObjectName(),
 11000        Variety: tree.Enum,
 11001        EnumLabels: $10.enumValueList(),
 11002        IfNotExists: true,
 11003      }
 11004    }
 11005  | CREATE TYPE error // SHOW HELP: CREATE TYPE
 11006    // Record/Composite types.
 11007  | CREATE TYPE type_name AS '(' opt_composite_type_list ')'
 11008    {
 11009      $$.val = &tree.CreateType{
 11010        TypeName: $3.unresolvedObjectName(),
 11011        Variety: tree.Composite,
 11012        CompositeTypeList: $6.compositeTypeList(),
 11013      }
 11014    }
 11015  | CREATE TYPE IF NOT EXISTS type_name AS '(' opt_composite_type_list ')'
 11016    {
 11017      $$.val = &tree.CreateType{
 11018        TypeName: $6.unresolvedObjectName(),
 11019        Variety: tree.Composite,
 11020        IfNotExists: true,
 11021        CompositeTypeList: $9.compositeTypeList(),
 11022      }
 11023    }
 11024    // Range types.
 11025  | CREATE TYPE type_name AS RANGE error    { return unimplementedWithIssue(sqllex, 27791) }
 11026    // Base (primitive) types.
 11027  | CREATE TYPE type_name '(' error         { return unimplementedWithIssueDetail(sqllex, 27793, "base") }
 11028    // Shell types, gateway to define base types using the previous syntax.
 11029  | CREATE TYPE type_name                   { return unimplementedWithIssueDetail(sqllex, 27793, "shell") }
 11030    // Domain types.
 11031  | CREATE DOMAIN type_name error           { return unimplementedWithIssueDetail(sqllex, 27796, "create") }
 11032  
 11033  opt_enum_val_list:
 11034    enum_val_list
 11035    {
 11036      $$.val = $1.enumValueList()
 11037    }
 11038  | /* EMPTY */
 11039    {
 11040      $$.val = tree.EnumValueList(nil)
 11041    }
 11042  
 11043  enum_val_list:
 11044    SCONST
 11045    {
 11046      $$.val = tree.EnumValueList{tree.EnumValue($1)}
 11047    }
 11048  | enum_val_list ',' SCONST
 11049    {
 11050      $$.val = append($1.enumValueList(), tree.EnumValue($3))
 11051    }
 11052  
 11053  opt_composite_type_list:
 11054    composite_type_list
 11055    {
 11056      $$.val = $1.compositeTypeList()
 11057    }
 11058  | /* EMPTY */
 11059    {
 11060      $$.val = []tree.CompositeTypeElem{}
 11061    }
 11062  
 11063  composite_type_list:
 11064    name simple_typename
 11065    {
 11066      $$.val = []tree.CompositeTypeElem{
 11067          tree.CompositeTypeElem{
 11068              Label: tree.Name($1),
 11069              Type: $2.typeReference(),
 11070          },
 11071      }
 11072    }
 11073  | composite_type_list ',' name simple_typename
 11074    {
 11075      $$.val = append($1.compositeTypeList(),
 11076          tree.CompositeTypeElem{
 11077              Label: tree.Name($3),
 11078              Type: $4.typeReference(),
 11079          },
 11080      )
 11081    }
 11082  
 11083  // %Help: CREATE INDEX - create a new index
 11084  // %Category: DDL
 11085  // %Text:
 11086  // CREATE [UNIQUE | INVERTED] INDEX [CONCURRENTLY] [IF NOT EXISTS] [<idxname>]
 11087  //        ON <tablename> ( <colname> [ASC | DESC] [, ...] )
 11088  //        [USING HASH] [STORING ( <colnames...> )]
 11089  //        [PARTITION BY <partition params>]
 11090  //        [WITH <storage_parameter_list] [WHERE <where_conds...>]
 11091  //
 11092  // %SeeAlso: CREATE TABLE, SHOW INDEXES, SHOW CREATE,
 11093  // WEBDOCS/create-index.html
 11094  create_index_stmt:
 11095    CREATE opt_unique INDEX opt_concurrently opt_index_name ON table_name opt_index_access_method '(' index_params ')' opt_hash_sharded opt_storing opt_partition_by_index opt_with_storage_parameter_list opt_where_clause opt_index_visible
 11096    {
 11097      table := $7.unresolvedObjectName().ToTableName()
 11098      $$.val = &tree.CreateIndex{
 11099        Name:             tree.Name($5),
 11100        Table:            table,
 11101        Unique:           $2.bool(),
 11102        Columns:          $10.idxElems(),
 11103        Sharded:          $12.shardedIndexDef(),
 11104        Storing:          $13.nameList(),
 11105        PartitionByIndex: $14.partitionByIndex(),
 11106        StorageParams:    $15.storageParams(),
 11107        Predicate:        $16.expr(),
 11108        Inverted:         $8.bool(),
 11109        Concurrently:     $4.bool(),
 11110        Invisibility:     $17.indexInvisibility(),
 11111      }
 11112    }
 11113  | CREATE opt_unique INDEX opt_concurrently IF NOT EXISTS index_name ON table_name opt_index_access_method '(' index_params ')' opt_hash_sharded opt_storing opt_partition_by_index opt_with_storage_parameter_list opt_where_clause opt_index_visible
 11114    {
 11115      table := $10.unresolvedObjectName().ToTableName()
 11116      $$.val = &tree.CreateIndex{
 11117        Name:             tree.Name($8),
 11118        Table:            table,
 11119        Unique:           $2.bool(),
 11120        IfNotExists:      true,
 11121        Columns:          $13.idxElems(),
 11122        Sharded:          $15.shardedIndexDef(),
 11123        Storing:          $16.nameList(),
 11124        PartitionByIndex: $17.partitionByIndex(),
 11125        Inverted:         $11.bool(),
 11126        StorageParams:    $18.storageParams(),
 11127        Predicate:        $19.expr(),
 11128        Concurrently:     $4.bool(),
 11129        Invisibility:     $20.indexInvisibility(),
 11130      }
 11131    }
 11132  | CREATE opt_unique INVERTED INDEX opt_concurrently opt_index_name ON table_name '(' index_params ')' opt_storing opt_partition_by_index opt_with_storage_parameter_list opt_where_clause opt_index_visible
 11133    {
 11134      table := $8.unresolvedObjectName().ToTableName()
 11135      $$.val = &tree.CreateIndex{
 11136        Name:             tree.Name($6),
 11137        Table:            table,
 11138        Unique:           $2.bool(),
 11139        Inverted:         true,
 11140        Columns:          $10.idxElems(),
 11141        Storing:          $12.nameList(),
 11142        PartitionByIndex: $13.partitionByIndex(),
 11143        StorageParams:    $14.storageParams(),
 11144        Predicate:        $15.expr(),
 11145        Concurrently:     $5.bool(),
 11146        Invisibility:     $16.indexInvisibility(),
 11147      }
 11148    }
 11149  | CREATE opt_unique INVERTED INDEX opt_concurrently IF NOT EXISTS index_name ON table_name '(' index_params ')' opt_storing opt_partition_by_index opt_with_storage_parameter_list opt_where_clause opt_index_visible
 11150    {
 11151      table := $11.unresolvedObjectName().ToTableName()
 11152      $$.val = &tree.CreateIndex{
 11153        Name:             tree.Name($9),
 11154        Table:            table,
 11155        Unique:           $2.bool(),
 11156        Inverted:         true,
 11157        IfNotExists:      true,
 11158        Columns:          $13.idxElems(),
 11159        Storing:          $15.nameList(),
 11160        PartitionByIndex: $16.partitionByIndex(),
 11161        StorageParams:    $17.storageParams(),
 11162        Predicate:        $18.expr(),
 11163        Concurrently:     $5.bool(),
 11164        Invisibility:     $19.indexInvisibility(),
 11165      }
 11166    }
 11167  | CREATE opt_unique INDEX error // SHOW HELP: CREATE INDEX
 11168  
 11169  opt_index_access_method:
 11170    USING name
 11171    {
 11172      /* FORCE DOC */
 11173      switch $2 {
 11174        case "gin", "gist":
 11175          $$.val = true
 11176        case "btree":
 11177          $$.val = false
 11178        case "hash", "spgist", "brin":
 11179          return unimplemented(sqllex, "index using " + $2)
 11180        default:
 11181          sqllex.Error("unrecognized access method: " + $2)
 11182          return 1
 11183      }
 11184    }
 11185  | /* EMPTY */
 11186    {
 11187      $$.val = false
 11188    }
 11189  
 11190  opt_concurrently:
 11191    CONCURRENTLY
 11192    {
 11193      $$.val = true
 11194    }
 11195  | /* EMPTY */
 11196    {
 11197      $$.val = false
 11198    }
 11199  
 11200  opt_unique:
 11201    UNIQUE
 11202    {
 11203      $$.val = true
 11204    }
 11205  | /* EMPTY */
 11206    {
 11207      $$.val = false
 11208    }
 11209  
 11210  index_params:
 11211    index_elem
 11212    {
 11213      $$.val = tree.IndexElemList{$1.idxElem()}
 11214    }
 11215  | index_params ',' index_elem
 11216    {
 11217      $$.val = append($1.idxElems(), $3.idxElem())
 11218    }
 11219  
 11220  // Index attributes can be either simple column references, or arbitrary
 11221  // expressions in parens. For backwards-compatibility reasons, we allow an
 11222  // expression that is just a function call to be written without parens.
 11223  index_elem:
 11224    func_expr_windowless index_elem_options
 11225    {
 11226      e := $2.idxElem()
 11227      e.Expr = $1.expr()
 11228      $$.val = e
 11229    }
 11230  | '(' a_expr ')' index_elem_options
 11231    {
 11232      e := $4.idxElem()
 11233      e.Expr = $2.expr()
 11234      $$.val = e
 11235    }
 11236  | name index_elem_options
 11237    {
 11238      e := $2.idxElem()
 11239      e.Column = tree.Name($1)
 11240      $$.val = e
 11241    }
 11242  
 11243  index_elem_options:
 11244    opt_class opt_asc_desc opt_nulls_order
 11245    {
 11246      /* FORCE DOC */
 11247      opClass := $1
 11248      dir := $2.dir()
 11249      nullsOrder := $3.nullsOrder()
 11250      // We currently only support the opposite of Postgres defaults.
 11251      if nullsOrder != tree.DefaultNullsOrder {
 11252        if dir == tree.Descending && nullsOrder == tree.NullsFirst {
 11253          return unimplementedWithIssue(sqllex, 6224)
 11254        }
 11255        if dir != tree.Descending && nullsOrder == tree.NullsLast {
 11256          return unimplementedWithIssue(sqllex, 6224)
 11257        }
 11258      }
 11259      $$.val = tree.IndexElem{Direction: dir, NullsOrder: nullsOrder, OpClass: tree.Name(opClass)}
 11260    }
 11261  
 11262  opt_class:
 11263    name { $$ = $1 }
 11264  | /* EMPTY */ { $$ = "" }
 11265  
 11266  opt_collate:
 11267    COLLATE collation_name { $$ = $2 }
 11268  | /* EMPTY */ { $$ = "" }
 11269  
 11270  opt_asc_desc:
 11271    ASC
 11272    {
 11273      $$.val = tree.Ascending
 11274    }
 11275  | DESC
 11276    {
 11277      $$.val = tree.Descending
 11278    }
 11279  | /* EMPTY */
 11280    {
 11281      $$.val = tree.DefaultDirection
 11282    }
 11283  
 11284  opt_index_visible:
 11285    NOT VISIBLE
 11286    {
 11287      $$.val = tree.IndexInvisibility{Value: 1.0}
 11288    }
 11289  | INVISIBLE
 11290    {
 11291      $$.val = tree.IndexInvisibility{Value: 1.0}
 11292    }
 11293  | VISIBLE
 11294    {
 11295      $$.val = tree.IndexInvisibility{Value: 0.0}
 11296    }
 11297  | VISIBILITY FCONST
 11298    {
 11299      visibilityConst, _ := constant.Float64Val($2.numVal().AsConstantValue())
 11300        if visibilityConst < 0.0 || visibilityConst > 1.0 {
 11301          sqllex.Error("index visibility must be between 0 and 1")
 11302          return 1
 11303        }
 11304      invisibilityConst := 1.0 - visibilityConst
 11305      $$.val = tree.IndexInvisibility{Value: invisibilityConst, FloatProvided: true}
 11306    }
 11307  | /* EMPTY */
 11308    {
 11309      $$.val = tree.IndexInvisibility{Value: 0.0}
 11310    }
 11311  
 11312  alter_database_to_schema_stmt:
 11313    ALTER DATABASE database_name CONVERT TO SCHEMA WITH PARENT database_name
 11314    {
 11315      $$.val = &tree.ReparentDatabase{Name: tree.Name($3), Parent: tree.Name($9)}
 11316    }
 11317  
 11318  alter_rename_database_stmt:
 11319    ALTER DATABASE database_name RENAME TO database_name
 11320    {
 11321      $$.val = &tree.RenameDatabase{Name: tree.Name($3), NewName: tree.Name($6)}
 11322    }
 11323  
 11324  alter_rename_table_stmt:
 11325    ALTER TABLE relation_expr RENAME TO table_name
 11326    {
 11327      name := $3.unresolvedObjectName()
 11328      newName := $6.unresolvedObjectName()
 11329      $$.val = &tree.RenameTable{Name: name, NewName: newName, IfExists: false, IsView: false}
 11330    }
 11331  | ALTER TABLE IF EXISTS relation_expr RENAME TO table_name
 11332    {
 11333      name := $5.unresolvedObjectName()
 11334      newName := $8.unresolvedObjectName()
 11335      $$.val = &tree.RenameTable{Name: name, NewName: newName, IfExists: true, IsView: false}
 11336    }
 11337  
 11338  alter_table_set_schema_stmt:
 11339    ALTER TABLE relation_expr SET SCHEMA schema_name
 11340     {
 11341       $$.val = &tree.AlterTableSetSchema{
 11342         Name: $3.unresolvedObjectName(), Schema: tree.Name($6), IfExists: false,
 11343       }
 11344     }
 11345  | ALTER TABLE IF EXISTS relation_expr SET SCHEMA schema_name
 11346    {
 11347      $$.val = &tree.AlterTableSetSchema{
 11348        Name: $5.unresolvedObjectName(), Schema: tree.Name($8), IfExists: true,
 11349      }
 11350    }
 11351  
 11352  alter_table_locality_stmt:
 11353    ALTER TABLE relation_expr SET locality
 11354    {
 11355      $$.val = &tree.AlterTableLocality{
 11356        Name: $3.unresolvedObjectName(),
 11357        Locality: $5.locality(),
 11358        IfExists: false,
 11359      }
 11360    }
 11361  | ALTER TABLE IF EXISTS relation_expr SET locality
 11362    {
 11363      $$.val = &tree.AlterTableLocality{
 11364        Name: $5.unresolvedObjectName(),
 11365        Locality: $7.locality(),
 11366        IfExists: true,
 11367      }
 11368    }
 11369  
 11370  locality:
 11371    LOCALITY GLOBAL
 11372    {
 11373      $$.val = &tree.Locality{
 11374        LocalityLevel: tree.LocalityLevelGlobal,
 11375      }
 11376    }
 11377  | LOCALITY REGIONAL BY TABLE IN region_name
 11378    {
 11379      $$.val = &tree.Locality{
 11380        TableRegion: tree.Name($6),
 11381        LocalityLevel: tree.LocalityLevelTable,
 11382      }
 11383    }
 11384  | LOCALITY REGIONAL BY TABLE IN PRIMARY REGION
 11385    {
 11386      $$.val = &tree.Locality{
 11387        LocalityLevel: tree.LocalityLevelTable,
 11388      }
 11389    }
 11390  | LOCALITY REGIONAL BY TABLE
 11391    {
 11392      $$.val = &tree.Locality{
 11393        LocalityLevel: tree.LocalityLevelTable,
 11394      }
 11395    }
 11396  | LOCALITY REGIONAL IN region_name
 11397    {
 11398      $$.val = &tree.Locality{
 11399        TableRegion: tree.Name($4),
 11400        LocalityLevel: tree.LocalityLevelTable,
 11401      }
 11402    }
 11403  | LOCALITY REGIONAL IN PRIMARY REGION
 11404    {
 11405      $$.val = &tree.Locality{
 11406        LocalityLevel: tree.LocalityLevelTable,
 11407      }
 11408    }
 11409  | LOCALITY REGIONAL
 11410    {
 11411      $$.val = &tree.Locality{
 11412        LocalityLevel: tree.LocalityLevelTable,
 11413      }
 11414    }
 11415  | LOCALITY REGIONAL BY ROW
 11416    {
 11417      $$.val = &tree.Locality{
 11418        LocalityLevel: tree.LocalityLevelRow,
 11419      }
 11420    }
 11421  | LOCALITY REGIONAL BY ROW AS name
 11422    {
 11423      $$.val = &tree.Locality{
 11424        LocalityLevel: tree.LocalityLevelRow,
 11425        RegionalByRowColumn: tree.Name($6),
 11426      }
 11427    }
 11428  
 11429  alter_table_owner_stmt:
 11430    ALTER TABLE relation_expr OWNER TO role_spec
 11431    {
 11432      $$.val = &tree.AlterTableOwner{
 11433        Name: $3.unresolvedObjectName(),
 11434        Owner: $6.roleSpec(),
 11435        IfExists: false,
 11436      }
 11437    }
 11438  | ALTER TABLE IF EXISTS relation_expr OWNER TO role_spec
 11439    {
 11440      $$.val = &tree.AlterTableOwner{
 11441        Name: $5.unresolvedObjectName(),
 11442        Owner: $8.roleSpec(),
 11443        IfExists: true,
 11444      }
 11445    }
 11446  
 11447  alter_view_set_schema_stmt:
 11448  	ALTER VIEW relation_expr SET SCHEMA schema_name
 11449  	 {
 11450  		 $$.val = &tree.AlterTableSetSchema{
 11451  			 Name: $3.unresolvedObjectName(), Schema: tree.Name($6), IfExists: false, IsView: true,
 11452  		 }
 11453  	 }
 11454  | ALTER MATERIALIZED VIEW relation_expr SET SCHEMA schema_name
 11455  	 {
 11456  		 $$.val = &tree.AlterTableSetSchema{
 11457  			 Name: $4.unresolvedObjectName(),
 11458  			 Schema: tree.Name($7),
 11459  			 IfExists: false,
 11460  			 IsView: true,
 11461  			 IsMaterialized: true,
 11462  		 }
 11463  	 }
 11464  | ALTER VIEW IF EXISTS relation_expr SET SCHEMA schema_name
 11465  	{
 11466  		$$.val = &tree.AlterTableSetSchema{
 11467  			Name: $5.unresolvedObjectName(), Schema: tree.Name($8), IfExists: true, IsView: true,
 11468  		}
 11469  	}
 11470  | ALTER MATERIALIZED VIEW IF EXISTS relation_expr SET SCHEMA schema_name
 11471  	{
 11472  		$$.val = &tree.AlterTableSetSchema{
 11473  			Name: $6.unresolvedObjectName(),
 11474  			Schema: tree.Name($9),
 11475  			IfExists: true,
 11476  			IsView: true,
 11477  			IsMaterialized: true,
 11478  		}
 11479  	}
 11480  
 11481  alter_view_owner_stmt:
 11482  	ALTER VIEW relation_expr OWNER TO role_spec
 11483    {
 11484      $$.val = &tree.AlterTableOwner{
 11485        Name: $3.unresolvedObjectName(),
 11486        Owner: $6.roleSpec(),
 11487        IfExists: false,
 11488        IsView: true,
 11489      }
 11490    }
 11491  | ALTER MATERIALIZED VIEW relation_expr OWNER TO role_spec
 11492    {
 11493      $$.val = &tree.AlterTableOwner{
 11494        Name: $4.unresolvedObjectName(),
 11495        Owner: $7.roleSpec(),
 11496        IfExists: false,
 11497        IsView: true,
 11498        IsMaterialized: true,
 11499      }
 11500    }
 11501  | ALTER VIEW IF EXISTS relation_expr OWNER TO role_spec
 11502    {
 11503      $$.val = &tree.AlterTableOwner{
 11504        Name: $5.unresolvedObjectName(),
 11505        Owner: $8.roleSpec(),
 11506        IfExists: true,
 11507        IsView: true,
 11508      }
 11509    }
 11510  | ALTER MATERIALIZED VIEW IF EXISTS relation_expr OWNER TO role_spec
 11511    {
 11512      $$.val = &tree.AlterTableOwner{
 11513        Name: $6.unresolvedObjectName(),
 11514        Owner: $9.roleSpec(),
 11515        IfExists: true,
 11516        IsView: true,
 11517        IsMaterialized: true,
 11518      }
 11519    }
 11520  
 11521  alter_sequence_set_schema_stmt:
 11522  	ALTER SEQUENCE relation_expr SET SCHEMA schema_name
 11523  	 {
 11524  		 $$.val = &tree.AlterTableSetSchema{
 11525  			 Name: $3.unresolvedObjectName(), Schema: tree.Name($6), IfExists: false, IsSequence: true,
 11526  		 }
 11527  	 }
 11528  | ALTER SEQUENCE IF EXISTS relation_expr SET SCHEMA schema_name
 11529  	{
 11530  		$$.val = &tree.AlterTableSetSchema{
 11531  			Name: $5.unresolvedObjectName(), Schema: tree.Name($8), IfExists: true, IsSequence: true,
 11532  		}
 11533  	}
 11534  
 11535  alter_sequence_owner_stmt:
 11536  	ALTER SEQUENCE relation_expr OWNER TO role_spec
 11537  	{
 11538  		$$.val = &tree.AlterTableOwner{
 11539  			Name: $3.unresolvedObjectName(),
 11540  			Owner: $6.roleSpec(),
 11541  			IfExists: false,
 11542  			IsSequence: true,
 11543  		}
 11544  	}
 11545  | ALTER SEQUENCE IF EXISTS relation_expr OWNER TO role_spec
 11546  	{
 11547  		$$.val = &tree.AlterTableOwner{
 11548  			Name: $5.unresolvedObjectName(),
 11549  			Owner: $8.roleSpec(),
 11550  			IfExists: true,
 11551  			IsSequence: true,
 11552  		}
 11553  	}
 11554  
 11555  alter_rename_view_stmt:
 11556    ALTER VIEW relation_expr RENAME TO view_name
 11557    {
 11558      name := $3.unresolvedObjectName()
 11559      newName := $6.unresolvedObjectName()
 11560      $$.val = &tree.RenameTable{Name: name, NewName: newName, IfExists: false, IsView: true}
 11561    }
 11562  | ALTER MATERIALIZED VIEW relation_expr RENAME TO view_name
 11563    {
 11564      name := $4.unresolvedObjectName()
 11565      newName := $7.unresolvedObjectName()
 11566      $$.val = &tree.RenameTable{
 11567        Name: name,
 11568        NewName: newName,
 11569        IfExists: false,
 11570        IsView: true,
 11571        IsMaterialized: true,
 11572      }
 11573    }
 11574  | ALTER VIEW IF EXISTS relation_expr RENAME TO view_name
 11575    {
 11576      name := $5.unresolvedObjectName()
 11577      newName := $8.unresolvedObjectName()
 11578      $$.val = &tree.RenameTable{Name: name, NewName: newName, IfExists: true, IsView: true}
 11579    }
 11580  | ALTER MATERIALIZED VIEW IF EXISTS relation_expr RENAME TO view_name
 11581    {
 11582      name := $6.unresolvedObjectName()
 11583      newName := $9.unresolvedObjectName()
 11584      $$.val = &tree.RenameTable{
 11585        Name: name,
 11586        NewName: newName,
 11587        IfExists: true,
 11588        IsView: true,
 11589        IsMaterialized: true,
 11590      }
 11591    }
 11592  
 11593  alter_rename_sequence_stmt:
 11594    ALTER SEQUENCE relation_expr RENAME TO sequence_name
 11595    {
 11596      name := $3.unresolvedObjectName()
 11597      newName := $6.unresolvedObjectName()
 11598      $$.val = &tree.RenameTable{Name: name, NewName: newName, IfExists: false, IsSequence: true}
 11599    }
 11600  | ALTER SEQUENCE IF EXISTS relation_expr RENAME TO sequence_name
 11601    {
 11602      name := $5.unresolvedObjectName()
 11603      newName := $8.unresolvedObjectName()
 11604      $$.val = &tree.RenameTable{Name: name, NewName: newName, IfExists: true, IsSequence: true}
 11605    }
 11606  
 11607  alter_rename_index_stmt:
 11608    ALTER INDEX table_index_name RENAME TO index_name
 11609    {
 11610      $$.val = &tree.RenameIndex{Index: $3.newTableIndexName(), NewName: tree.UnrestrictedName($6), IfExists: false}
 11611    }
 11612  | ALTER INDEX IF EXISTS table_index_name RENAME TO index_name
 11613    {
 11614      $$.val = &tree.RenameIndex{Index: $5.newTableIndexName(), NewName: tree.UnrestrictedName($8), IfExists: true}
 11615    }
 11616  
 11617  // %Help: ALTER DEFAULT PRIVILEGES - alter default privileges on an object
 11618  // %Category: DDL
 11619  // %Text:
 11620  //
 11621  // Commands:
 11622  //   ALTER DEFAULT PRIVILEGES [ FOR { ROLE | USER } target_roles... ] [ IN SCHEMA schema_name...] abbreviated_grant_or_revoke
 11623  alter_default_privileges_stmt:
 11624   ALTER DEFAULT PRIVILEGES opt_for_roles opt_in_schemas abbreviated_grant_stmt
 11625   {
 11626     $$.val = &tree.AlterDefaultPrivileges{
 11627       Roles: $4.roleSpecList(),
 11628       Schemas: $5.objectNamePrefixList(),
 11629       Grant: $6.abbreviatedGrant(),
 11630       IsGrant: true,
 11631     }
 11632   }
 11633  | ALTER DEFAULT PRIVILEGES opt_for_roles opt_in_schemas abbreviated_revoke_stmt
 11634   {
 11635     $$.val = &tree.AlterDefaultPrivileges{
 11636       Roles: $4.roleSpecList(),
 11637       Schemas: $5.objectNamePrefixList(),
 11638       Revoke: $6.abbreviatedRevoke(),
 11639       IsGrant: false,
 11640     }
 11641   }
 11642  | ALTER DEFAULT PRIVILEGES FOR ALL ROLES opt_in_schemas abbreviated_grant_stmt
 11643   {
 11644     $$.val = &tree.AlterDefaultPrivileges{
 11645       ForAllRoles: true,
 11646       Schemas: $7.objectNamePrefixList(),
 11647       Grant: $8.abbreviatedGrant(),
 11648       IsGrant: true,
 11649    }
 11650   }
 11651  | ALTER DEFAULT PRIVILEGES FOR ALL ROLES opt_in_schemas abbreviated_revoke_stmt
 11652   {
 11653     $$.val = &tree.AlterDefaultPrivileges{
 11654       ForAllRoles: true,
 11655       Schemas: $7.objectNamePrefixList(),
 11656       Revoke: $8.abbreviatedRevoke(),
 11657       IsGrant: false,
 11658    }
 11659   }
 11660  | ALTER DEFAULT PRIVILEGES error // SHOW HELP: ALTER DEFAULT PRIVILEGES
 11661  
 11662  abbreviated_grant_stmt:
 11663    GRANT privileges ON target_object_type TO role_spec_list opt_with_grant_option
 11664    {
 11665      $$.val = tree.AbbreviatedGrant{
 11666        Privileges: $2.privilegeList(),
 11667        Target: $4.targetObjectType(),
 11668        Grantees: $6.roleSpecList(),
 11669        WithGrantOption: $7.bool(),
 11670      }
 11671    }
 11672  
 11673  opt_with_grant_option:
 11674   WITH GRANT OPTION
 11675    {
 11676      $$.val = true
 11677    }
 11678  | /* EMPTY */
 11679    {
 11680      $$.val = false
 11681    }
 11682  
 11683  abbreviated_revoke_stmt:
 11684    REVOKE privileges ON target_object_type FROM role_spec_list opt_drop_behavior
 11685    {
 11686      $$.val = tree.AbbreviatedRevoke{
 11687        Privileges: $2.privilegeList(),
 11688        Target: $4.targetObjectType(),
 11689        Grantees: $6.roleSpecList(),
 11690      }
 11691    }
 11692  | REVOKE GRANT OPTION FOR privileges ON target_object_type FROM role_spec_list opt_drop_behavior
 11693    {
 11694      $$.val = tree.AbbreviatedRevoke{
 11695        Privileges: $5.privilegeList(),
 11696        Target: $7.targetObjectType(),
 11697        Grantees: $9.roleSpecList(),
 11698        GrantOptionFor: true,
 11699      }
 11700    }
 11701  
 11702  target_object_type:
 11703    TABLES
 11704    {
 11705      $$.val = privilege.Tables
 11706    }
 11707  | SEQUENCES
 11708    {
 11709      $$.val = privilege.Sequences
 11710    }
 11711  | TYPES
 11712    {
 11713      $$.val = privilege.Types
 11714    }
 11715  | SCHEMAS
 11716    {
 11717      $$.val = privilege.Schemas
 11718    }
 11719  | FUNCTIONS
 11720    {
 11721      $$.val = privilege.Routines
 11722    }
 11723  | ROUTINES error
 11724    {
 11725      return unimplemented(sqllex, "ALTER DEFAULT PRIVILEGES ... ON ROUTINES ...")
 11726    }
 11727  
 11728  opt_for_roles:
 11729   FOR role_or_group_or_user role_spec_list
 11730   {
 11731     $$.val = $3.roleSpecList()
 11732   }
 11733  | /* EMPTY */ {
 11734     $$.val = tree.RoleSpecList(nil)
 11735  }
 11736  
 11737  opt_in_schema:
 11738   IN SCHEMA schema_name
 11739   {
 11740     $$ = $3
 11741   }
 11742  | /* EMPTY */
 11743   {
 11744     $$ = ""
 11745   }
 11746  
 11747  
 11748  opt_in_schemas:
 11749   IN SCHEMA schema_name_list
 11750   {
 11751     $$.val = $3.objectNamePrefixList()
 11752   }
 11753  | /* EMPTY */
 11754   {
 11755     $$.val = tree.ObjectNamePrefixList{}
 11756   }
 11757  
 11758  opt_column:
 11759    COLUMN {}
 11760  | /* EMPTY */ {}
 11761  
 11762  opt_set_data:
 11763    SET DATA {}
 11764  | /* EMPTY */ {}
 11765  
 11766  // %Help: RELEASE - complete a sub-transaction
 11767  // %Category: Txn
 11768  // %Text: RELEASE [SAVEPOINT] <savepoint name>
 11769  // %SeeAlso: SAVEPOINT, WEBDOCS/savepoint.html
 11770  release_stmt:
 11771    RELEASE savepoint_name
 11772    {
 11773      $$.val = &tree.ReleaseSavepoint{Savepoint: tree.Name($2)}
 11774    }
 11775  | RELEASE error // SHOW HELP: RELEASE
 11776  
 11777  // %Help: RESUME JOBS - resume selected background jobs
 11778  // %Category: Misc
 11779  // %Text:
 11780  // RESUME JOBS <selectclause>
 11781  // RESUME JOB <jobid>
 11782  // %SeeAlso: SHOW JOBS, CANCEL JOBS, PAUSE JOBS
 11783  resume_jobs_stmt:
 11784    RESUME JOB a_expr
 11785    {
 11786      $$.val = &tree.ControlJobs{
 11787        Jobs: &tree.Select{
 11788          Select: &tree.ValuesClause{Rows: []tree.Exprs{tree.Exprs{$3.expr()}}},
 11789        },
 11790        Command: tree.ResumeJob,
 11791      }
 11792    }
 11793  | RESUME JOB error // SHOW HELP: RESUME JOBS
 11794  | RESUME JOBS select_stmt
 11795    {
 11796      $$.val = &tree.ControlJobs{Jobs: $3.slct(), Command: tree.ResumeJob}
 11797    }
 11798  | RESUME JOBS for_schedules_clause
 11799    {
 11800      $$.val = &tree.ControlJobsForSchedules{Schedules: $3.slct(), Command: tree.ResumeJob}
 11801    }
 11802  | RESUME JOBS error // SHOW HELP: RESUME JOBS
 11803  
 11804  // %Help: RESUME SCHEDULES - resume executing scheduled jobs
 11805  // %Category: Misc
 11806  // %Text:
 11807  // RESUME SCHEDULES <selectclause>
 11808  //  selectclause: select statement returning schedule IDs to resume.
 11809  //
 11810  // RESUME SCHEDULE <scheduleID>
 11811  //
 11812  // %SeeAlso: PAUSE SCHEDULES, SHOW JOBS, RESUME JOBS
 11813  resume_schedules_stmt:
 11814    RESUME SCHEDULE a_expr
 11815    {
 11816      $$.val = &tree.ControlSchedules{
 11817        Schedules: &tree.Select{
 11818          Select: &tree.ValuesClause{Rows: []tree.Exprs{tree.Exprs{$3.expr()}}},
 11819        },
 11820        Command: tree.ResumeSchedule,
 11821      }
 11822    }
 11823  | RESUME SCHEDULE error // SHOW HELP: RESUME SCHEDULES
 11824  | RESUME SCHEDULES select_stmt
 11825    {
 11826      $$.val = &tree.ControlSchedules{
 11827        Schedules: $3.slct(),
 11828        Command: tree.ResumeSchedule,
 11829      }
 11830    }
 11831  | RESUME SCHEDULES error // SHOW HELP: RESUME SCHEDULES
 11832  
 11833  // %Help: DROP SCHEDULES - destroy specified schedules
 11834  // %Category: Misc
 11835  // %Text:
 11836  // DROP SCHEDULES <selectclause>
 11837  //  selectclause: select statement returning schedule IDs to resume.
 11838  //
 11839  // DROP SCHEDULE <scheduleID>
 11840  //
 11841  // %SeeAlso: PAUSE SCHEDULES, SHOW JOBS, CANCEL JOBS
 11842  drop_schedule_stmt:
 11843    DROP SCHEDULE a_expr
 11844    {
 11845      $$.val = &tree.ControlSchedules{
 11846        Schedules: &tree.Select{
 11847          Select: &tree.ValuesClause{Rows: []tree.Exprs{tree.Exprs{$3.expr()}}},
 11848        },
 11849        Command: tree.DropSchedule,
 11850      }
 11851    }
 11852  | DROP SCHEDULE error // SHOW HELP: DROP SCHEDULES
 11853  | DROP SCHEDULES select_stmt
 11854    {
 11855      $$.val = &tree.ControlSchedules{
 11856        Schedules: $3.slct(),
 11857        Command: tree.DropSchedule,
 11858      }
 11859    }
 11860  | DROP SCHEDULES error // SHOW HELP: DROP SCHEDULES
 11861  
 11862  // %Help: SAVEPOINT - start a sub-transaction
 11863  // %Category: Txn
 11864  // %Text: SAVEPOINT <savepoint name>
 11865  // %SeeAlso: RELEASE, WEBDOCS/savepoint.html
 11866  savepoint_stmt:
 11867    SAVEPOINT name
 11868    {
 11869      $$.val = &tree.Savepoint{Name: tree.Name($2)}
 11870    }
 11871  | SAVEPOINT error // SHOW HELP: SAVEPOINT
 11872  
 11873  // BEGIN / START / COMMIT / END / ROLLBACK / ...
 11874  transaction_stmt:
 11875    begin_stmt    // EXTEND WITH HELP: BEGIN
 11876  | commit_stmt   // EXTEND WITH HELP: COMMIT
 11877  | rollback_stmt // EXTEND WITH HELP: ROLLBACK
 11878  | abort_stmt    /* SKIP DOC */
 11879  
 11880  // %Help: BEGIN - start a transaction
 11881  // %Category: Txn
 11882  // %Text:
 11883  // BEGIN [TRANSACTION] [ <txnparameter> [[,] ...] ]
 11884  // START TRANSACTION [ <txnparameter> [[,] ...] ]
 11885  //
 11886  // Transaction parameters:
 11887  //    ISOLATION LEVEL { READ COMMITTED | SERIALIZABLE }
 11888  //    PRIORITY { LOW | NORMAL | HIGH }
 11889  //
 11890  // %SeeAlso: COMMIT, ROLLBACK, WEBDOCS/begin-transaction.html
 11891  begin_stmt:
 11892    START TRANSACTION begin_transaction
 11893    {
 11894      s := $3.beginTransaction()
 11895      s.FormatWithStart = true
 11896      $$.val = s
 11897    }
 11898  | START error // SHOW HELP: BEGIN
 11899  
 11900  // %Help: COMMIT - commit the current transaction
 11901  // %Category: Txn
 11902  // %Text:
 11903  // COMMIT [TRANSACTION]
 11904  // END [TRANSACTION]
 11905  // %SeeAlso: BEGIN, ROLLBACK, WEBDOCS/commit-transaction.html
 11906  commit_stmt:
 11907    COMMIT opt_transaction
 11908    {
 11909      $$.val = &tree.CommitTransaction{}
 11910    }
 11911  | COMMIT error // SHOW HELP: COMMIT
 11912  
 11913  abort_stmt:
 11914    ABORT opt_abort_mod
 11915    {
 11916      $$.val = &tree.RollbackTransaction{}
 11917    }
 11918  
 11919  opt_abort_mod:
 11920    TRANSACTION {}
 11921  | WORK        {}
 11922  | /* EMPTY */ {}
 11923  
 11924  // %Help: ROLLBACK - abort the current (sub-)transaction
 11925  // %Category: Txn
 11926  // %Text:
 11927  // ROLLBACK [TRANSACTION]
 11928  // ROLLBACK [TRANSACTION] TO [SAVEPOINT] <savepoint name>
 11929  // %SeeAlso: BEGIN, COMMIT, SAVEPOINT, WEBDOCS/rollback-transaction.html
 11930  rollback_stmt:
 11931    ROLLBACK opt_transaction
 11932    {
 11933       $$.val = &tree.RollbackTransaction{}
 11934    }
 11935  | ROLLBACK opt_transaction TO savepoint_name
 11936    {
 11937       $$.val = &tree.RollbackToSavepoint{Savepoint: tree.Name($4)}
 11938    }
 11939  | ROLLBACK error // SHOW HELP: ROLLBACK
 11940  
 11941  // "legacy" here doesn't mean we're deprecating the syntax. We inherit this
 11942  // concept from postgres. The idea is to avoid conflicts in "CREATE FUNCTION"'s
 11943  // "BEGIN ATOMIC...END" function body context.
 11944  legacy_transaction_stmt:
 11945    legacy_begin_stmt // EXTEND WITH HELP: BEGIN
 11946  | legacy_end_stmt // EXTEND WITH HELP: COMMIT
 11947  
 11948  legacy_begin_stmt:
 11949    BEGIN opt_transaction begin_transaction
 11950    {
 11951      $$.val = $3.stmt()
 11952    }
 11953  | BEGIN error // SHOW HELP: BEGIN
 11954  
 11955  legacy_end_stmt:
 11956    END opt_transaction
 11957    {
 11958      $$.val = &tree.CommitTransaction{}
 11959    }
 11960  | END error // SHOW HELP: COMMIT
 11961  
 11962  
 11963  opt_transaction:
 11964    TRANSACTION {}
 11965  | /* EMPTY */ {}
 11966  
 11967  savepoint_name:
 11968    SAVEPOINT name
 11969    {
 11970      $$ = $2
 11971    }
 11972  | name
 11973    {
 11974      $$ = $1
 11975    }
 11976  
 11977  begin_transaction:
 11978    transaction_mode_list
 11979    {
 11980      $$.val = &tree.BeginTransaction{Modes: $1.transactionModes()}
 11981    }
 11982  | /* EMPTY */
 11983    {
 11984      $$.val = &tree.BeginTransaction{}
 11985    }
 11986  
 11987  transaction_mode_list:
 11988    transaction_mode
 11989    {
 11990      $$.val = $1.transactionModes()
 11991    }
 11992  | transaction_mode_list opt_comma transaction_mode
 11993    {
 11994      a := $1.transactionModes()
 11995      b := $3.transactionModes()
 11996      err := a.Merge(b)
 11997      if err != nil { return setErr(sqllex, err) }
 11998      $$.val = a
 11999    }
 12000  
 12001  // The transaction mode list after BEGIN should use comma-separated
 12002  // modes as per the SQL standard, but PostgreSQL historically allowed
 12003  // them to be listed without commas too.
 12004  opt_comma:
 12005    ','
 12006    { }
 12007  | /* EMPTY */
 12008    { }
 12009  
 12010  transaction_mode:
 12011    transaction_iso_level
 12012    {
 12013      /* SKIP DOC */
 12014      $$.val = tree.TransactionModes{Isolation: $1.isoLevel()}
 12015    }
 12016  | transaction_user_priority
 12017    {
 12018      $$.val = tree.TransactionModes{UserPriority: $1.userPriority()}
 12019    }
 12020  | transaction_read_mode
 12021    {
 12022      $$.val = tree.TransactionModes{ReadWriteMode: $1.readWriteMode()}
 12023    }
 12024  | as_of_clause
 12025    {
 12026      $$.val = tree.TransactionModes{AsOf: $1.asOfClause()}
 12027    }
 12028  | transaction_deferrable_mode
 12029    {
 12030      $$.val = tree.TransactionModes{Deferrable: $1.deferrableMode()}
 12031    }
 12032  
 12033  transaction_user_priority:
 12034    PRIORITY user_priority
 12035    {
 12036      $$.val = $2.userPriority()
 12037    }
 12038  
 12039  transaction_iso_level:
 12040    ISOLATION LEVEL iso_level
 12041    {
 12042      $$.val = $3.isoLevel()
 12043    }
 12044  
 12045  transaction_read_mode:
 12046    READ ONLY
 12047    {
 12048      $$.val = tree.ReadOnly
 12049    }
 12050  | READ WRITE
 12051    {
 12052      $$.val = tree.ReadWrite
 12053    }
 12054  
 12055  transaction_deferrable_mode:
 12056    DEFERRABLE
 12057    {
 12058      $$.val = tree.Deferrable
 12059    }
 12060  | NOT DEFERRABLE
 12061    {
 12062      $$.val = tree.NotDeferrable
 12063    }
 12064  
 12065  // %Help: CREATE DATABASE - create a new database
 12066  // %Category: DDL
 12067  // %Text: CREATE DATABASE [IF NOT EXISTS] <name>
 12068  // %SeeAlso: WEBDOCS/create-database.html
 12069  create_database_stmt:
 12070    CREATE DATABASE database_name opt_with opt_template_clause opt_encoding_clause opt_lc_collate_clause opt_lc_ctype_clause opt_connection_limit opt_primary_region_clause opt_regions_list opt_survival_goal_clause opt_placement_clause opt_owner_clause opt_super_region_clause opt_secondary_region_clause
 12071    {
 12072      $$.val = &tree.CreateDatabase{
 12073        Name: tree.Name($3),
 12074        Template: $5,
 12075        Encoding: $6,
 12076        Collate: $7,
 12077        CType: $8,
 12078        ConnectionLimit: $9.int32(),
 12079        PrimaryRegion: tree.Name($10),
 12080        Regions: $11.nameList(),
 12081        SurvivalGoal: $12.survivalGoal(),
 12082        Placement: $13.dataPlacement(),
 12083        Owner: $14.roleSpec(),
 12084        SuperRegion: $15.superRegion(),
 12085        SecondaryRegion: tree.Name($16),
 12086      }
 12087    }
 12088  | CREATE DATABASE IF NOT EXISTS database_name opt_with opt_template_clause opt_encoding_clause opt_lc_collate_clause opt_lc_ctype_clause opt_connection_limit opt_primary_region_clause opt_regions_list opt_survival_goal_clause opt_placement_clause opt_owner_clause opt_super_region_clause opt_secondary_region_clause
 12089    {
 12090      $$.val = &tree.CreateDatabase{
 12091        IfNotExists: true,
 12092        Name: tree.Name($6),
 12093        Template: $8,
 12094        Encoding: $9,
 12095        Collate: $10,
 12096        CType: $11,
 12097        ConnectionLimit: $12.int32(),
 12098        PrimaryRegion: tree.Name($13),
 12099        Regions: $14.nameList(),
 12100        SurvivalGoal: $15.survivalGoal(),
 12101        Placement: $16.dataPlacement(),
 12102        Owner: $17.roleSpec(),
 12103        SuperRegion: $18.superRegion(),
 12104        SecondaryRegion: tree.Name($19),
 12105      }
 12106    }
 12107  | CREATE DATABASE error // SHOW HELP: CREATE DATABASE
 12108  
 12109  opt_primary_region_clause:
 12110    primary_region_clause
 12111  | /* EMPTY */
 12112    {
 12113      $$ = ""
 12114    }
 12115  
 12116  primary_region_clause:
 12117    PRIMARY REGION opt_equal region_name {
 12118      $$ = $4
 12119    }
 12120  
 12121  opt_secondary_region_clause:
 12122    secondary_region_clause
 12123  | /* EMPTY */
 12124    {
 12125      $$ = ""
 12126    }
 12127  
 12128  secondary_region_clause:
 12129    SECONDARY REGION opt_equal region_name {
 12130      $$ = $4
 12131    }
 12132  
 12133  opt_super_region_clause:
 12134    super_region_clause
 12135  | /* EMPTY */
 12136  {
 12137    $$.val = tree.SuperRegion{}
 12138  }
 12139  
 12140  super_region_clause:
 12141  SUPER REGION region_name VALUES region_name_list
 12142  {
 12143    $$.val = tree.SuperRegion{Name: tree.Name($3), Regions: $5.nameList()}
 12144  }
 12145  
 12146  opt_placement_clause:
 12147    placement_clause
 12148  | /* EMPTY */
 12149    {
 12150      $$.val = tree.DataPlacementUnspecified
 12151    }
 12152  
 12153  placement_clause:
 12154    PLACEMENT RESTRICTED
 12155    {
 12156      $$.val = tree.DataPlacementRestricted
 12157    }
 12158  | PLACEMENT DEFAULT
 12159    {
 12160      $$.val = tree.DataPlacementDefault
 12161    }
 12162  
 12163  opt_regions_list:
 12164    region_or_regions opt_equal region_name_list
 12165    {
 12166      $$.val = $3.nameList()
 12167    }
 12168  | /* EMPTY */
 12169    {
 12170      $$.val = tree.NameList(nil)
 12171    }
 12172  
 12173  region_or_regions:
 12174    REGION
 12175    {
 12176      /* SKIP DOC */
 12177    }
 12178  | REGIONS
 12179  
 12180  survival_goal_clause:
 12181    SURVIVE opt_equal REGION FAILURE
 12182    {
 12183      $$.val = tree.SurvivalGoalRegionFailure
 12184    }
 12185  | SURVIVE opt_equal ZONE FAILURE
 12186    {
 12187      $$.val = tree.SurvivalGoalZoneFailure
 12188    }
 12189  | SURVIVE opt_equal AVAILABILITY ZONE FAILURE
 12190    {
 12191      /* SKIP DOC */
 12192      $$.val = tree.SurvivalGoalZoneFailure
 12193    }
 12194  
 12195  
 12196  opt_survival_goal_clause:
 12197    survival_goal_clause
 12198  | /* EMPTY */
 12199    {
 12200      $$.val = tree.SurvivalGoalDefault
 12201    }
 12202  
 12203  opt_template_clause:
 12204    TEMPLATE opt_equal non_reserved_word_or_sconst
 12205    {
 12206      $$ = $3
 12207    }
 12208  | /* EMPTY */
 12209    {
 12210      $$ = ""
 12211    }
 12212  
 12213  opt_encoding_clause:
 12214    ENCODING opt_equal non_reserved_word_or_sconst
 12215    {
 12216      $$ = $3
 12217    }
 12218  | /* EMPTY */
 12219    {
 12220      $$ = ""
 12221    }
 12222  
 12223  opt_lc_collate_clause:
 12224    LC_COLLATE opt_equal non_reserved_word_or_sconst
 12225    {
 12226      $$ = $3
 12227    }
 12228  | /* EMPTY */
 12229    {
 12230      $$ = ""
 12231    }
 12232  
 12233  opt_lc_ctype_clause:
 12234    LC_CTYPE opt_equal non_reserved_word_or_sconst
 12235    {
 12236      $$ = $3
 12237    }
 12238  | /* EMPTY */
 12239    {
 12240      $$ = ""
 12241    }
 12242  
 12243  opt_connection_limit:
 12244    CONNECTION LIMIT opt_equal signed_iconst
 12245    {
 12246      ret, err := $4.numVal().AsInt32()
 12247      if err != nil {
 12248        return setErr(sqllex, err)
 12249      }
 12250      $$.val = ret
 12251    }
 12252  | /* EMPTY */
 12253    {
 12254      $$.val = int32(-1)
 12255    }
 12256  
 12257  opt_owner_clause:
 12258    OWNER opt_equal role_spec
 12259    {
 12260      $$ = $3
 12261    }
 12262  | /* EMPTY */
 12263     {
 12264  		 $$.val = tree.RoleSpec{
 12265  		   RoleSpecType: tree.CurrentUser,
 12266  		 }
 12267     }
 12268  
 12269  opt_equal:
 12270    '=' {}
 12271  | /* EMPTY */ {}
 12272  
 12273  // %Help: INSERT - create new rows in a table
 12274  // %Category: DML
 12275  // %Text:
 12276  // INSERT INTO <tablename> [[AS] <name>] [( <colnames...> )]
 12277  //        <selectclause>
 12278  //        [ON CONFLICT {
 12279  //          [( <colnames...> )] [WHERE <arbiter_predicate>] DO NOTHING |
 12280  //          ( <colnames...> ) [WHERE <index_predicate>] DO UPDATE SET ... [WHERE <expr>]
 12281  //        }
 12282  //        [RETURNING <exprs...>]
 12283  // %SeeAlso: UPSERT, UPDATE, DELETE, WEBDOCS/insert.html
 12284  insert_stmt:
 12285    opt_with_clause INSERT INTO insert_target insert_rest returning_clause
 12286    {
 12287      $$.val = $5.stmt()
 12288      $$.val.(*tree.Insert).With = $1.with()
 12289      $$.val.(*tree.Insert).Table = $4.tblExpr()
 12290      $$.val.(*tree.Insert).Returning = $6.retClause()
 12291    }
 12292  | opt_with_clause INSERT INTO insert_target insert_rest on_conflict returning_clause
 12293    {
 12294      $$.val = $5.stmt()
 12295      $$.val.(*tree.Insert).With = $1.with()
 12296      $$.val.(*tree.Insert).Table = $4.tblExpr()
 12297      $$.val.(*tree.Insert).OnConflict = $6.onConflict()
 12298      $$.val.(*tree.Insert).Returning = $7.retClause()
 12299    }
 12300  | opt_with_clause INSERT error // SHOW HELP: INSERT
 12301  
 12302  // %Help: UPSERT - create or replace rows in a table
 12303  // %Category: DML
 12304  // %Text:
 12305  // UPSERT INTO <tablename> [AS <name>] [( <colnames...> )]
 12306  //        <selectclause>
 12307  //        [RETURNING <exprs...>]
 12308  // %SeeAlso: INSERT, UPDATE, DELETE, WEBDOCS/upsert.html
 12309  upsert_stmt:
 12310    opt_with_clause UPSERT INTO insert_target insert_rest returning_clause
 12311    {
 12312      $$.val = $5.stmt()
 12313      $$.val.(*tree.Insert).With = $1.with()
 12314      $$.val.(*tree.Insert).Table = $4.tblExpr()
 12315      $$.val.(*tree.Insert).OnConflict = &tree.OnConflict{}
 12316      $$.val.(*tree.Insert).Returning = $6.retClause()
 12317    }
 12318  | opt_with_clause UPSERT error // SHOW HELP: UPSERT
 12319  
 12320  insert_target:
 12321    table_name
 12322    {
 12323      name := $1.unresolvedObjectName().ToTableName()
 12324      $$.val = &name
 12325    }
 12326  // Can't easily make AS optional here, because VALUES in insert_rest would have
 12327  // a shift/reduce conflict with VALUES as an optional alias. We could easily
 12328  // allow unreserved_keywords as optional aliases, but that'd be an odd
 12329  // divergence from other places. So just require AS for now.
 12330  | table_name AS table_alias_name
 12331    {
 12332      name := $1.unresolvedObjectName().ToTableName()
 12333      $$.val = &tree.AliasedTableExpr{Expr: &name, As: tree.AliasClause{Alias: tree.Name($3)}}
 12334    }
 12335  | numeric_table_ref
 12336    {
 12337      $$.val = $1.tblExpr()
 12338    }
 12339  
 12340  insert_rest:
 12341    select_stmt
 12342    {
 12343      $$.val = &tree.Insert{Rows: $1.slct()}
 12344    }
 12345  | '(' insert_column_list ')' select_stmt
 12346    {
 12347      $$.val = &tree.Insert{Columns: $2.nameList(), Rows: $4.slct()}
 12348    }
 12349  | DEFAULT VALUES
 12350    {
 12351      $$.val = &tree.Insert{Rows: &tree.Select{}}
 12352    }
 12353  
 12354  insert_column_list:
 12355    insert_column_item
 12356    {
 12357      $$.val = tree.NameList{tree.Name($1)}
 12358    }
 12359  | insert_column_list ',' insert_column_item
 12360    {
 12361      $$.val = append($1.nameList(), tree.Name($3))
 12362    }
 12363  
 12364  // insert_column_item represents the target of an INSERT/UPSERT or one
 12365  // of the LHS operands in an UPDATE SET statement.
 12366  //
 12367  //    INSERT INTO foo (x, y) VALUES ...
 12368  //                     ^^^^ here
 12369  //
 12370  //    UPDATE foo SET x = 1+2, (y, z) = (4, 5)
 12371  //                   ^^ here   ^^^^ here
 12372  //
 12373  // Currently CockroachDB only supports simple column names in this
 12374  // position. The rule below can be extended to support a sequence of
 12375  // field subscript or array indexing operators to designate a part of
 12376  // a field, when partial updates are to be supported. This likely will
 12377  // be needed together with support for composite types (#27792).
 12378  insert_column_item:
 12379    column_name
 12380  | column_name '.' error { return unimplementedWithIssue(sqllex, 27792) }
 12381  
 12382  on_conflict:
 12383    ON CONFLICT DO NOTHING
 12384    {
 12385      $$.val = &tree.OnConflict{
 12386        Columns: tree.NameList(nil),
 12387        DoNothing: true,
 12388      }
 12389    }
 12390  | ON CONFLICT '(' name_list ')' opt_where_clause DO NOTHING
 12391    {
 12392      $$.val = &tree.OnConflict{
 12393        Columns: $4.nameList(),
 12394        ArbiterPredicate: $6.expr(),
 12395        DoNothing: true,
 12396      }
 12397    }
 12398  | ON CONFLICT '(' name_list ')' opt_where_clause DO UPDATE SET set_clause_list opt_where_clause
 12399    {
 12400      $$.val = &tree.OnConflict{
 12401        Columns: $4.nameList(),
 12402        ArbiterPredicate: $6.expr(),
 12403        Exprs: $10.updateExprs(),
 12404        Where: tree.NewWhere(tree.AstWhere, $11.expr()),
 12405      }
 12406    }
 12407  | ON CONFLICT ON CONSTRAINT constraint_name DO NOTHING
 12408    {
 12409      $$.val = &tree.OnConflict{
 12410        Constraint: tree.Name($5),
 12411        DoNothing: true,
 12412      }
 12413    }
 12414  | ON CONFLICT ON CONSTRAINT constraint_name DO UPDATE SET set_clause_list opt_where_clause
 12415    {
 12416      $$.val = &tree.OnConflict{
 12417        Constraint: tree.Name($5),
 12418        Exprs: $9.updateExprs(),
 12419        Where: tree.NewWhere(tree.AstWhere, $10.expr()),
 12420      }
 12421    }
 12422  
 12423  returning_clause:
 12424    RETURNING target_list
 12425    {
 12426      ret := tree.ReturningExprs($2.selExprs())
 12427      $$.val = &ret
 12428    }
 12429  | RETURNING NOTHING_AFTER_RETURNING
 12430    {
 12431      $$.val = tree.ReturningNothingClause
 12432    }
 12433  | /* EMPTY */
 12434    {
 12435      $$.val = tree.AbsentReturningClause
 12436    }
 12437  
 12438  // %Help: UPDATE - update rows of a table
 12439  // %Category: DML
 12440  // %Text:
 12441  // UPDATE <tablename> [[AS] <name>]
 12442  //        SET ...
 12443  //        [FROM <source>]
 12444  //        [WHERE <expr>]
 12445  //        [ORDER BY <exprs...>]
 12446  //        [LIMIT <expr>]
 12447  //        [RETURNING <exprs...>]
 12448  // %SeeAlso: INSERT, UPSERT, DELETE, WEBDOCS/update.html
 12449  update_stmt:
 12450    opt_with_clause UPDATE table_expr_opt_alias_idx
 12451      SET set_clause_list opt_from_list opt_where_clause opt_sort_clause opt_limit_clause returning_clause
 12452    {
 12453      $$.val = &tree.Update{
 12454        With: $1.with(),
 12455        Table: $3.tblExpr(),
 12456        Exprs: $5.updateExprs(),
 12457        From: $6.tblExprs(),
 12458        Where: tree.NewWhere(tree.AstWhere, $7.expr()),
 12459        OrderBy: $8.orderBy(),
 12460        Limit: $9.limit(),
 12461        Returning: $10.retClause(),
 12462      }
 12463    }
 12464  | opt_with_clause UPDATE error // SHOW HELP: UPDATE
 12465  
 12466  opt_from_list:
 12467    FROM from_list {
 12468      $$.val = $2.tblExprs()
 12469    }
 12470  | /* EMPTY */ {
 12471      $$.val = tree.TableExprs{}
 12472  }
 12473  
 12474  set_clause_list:
 12475    set_clause
 12476    {
 12477      $$.val = tree.UpdateExprs{$1.updateExpr()}
 12478    }
 12479  | set_clause_list ',' set_clause
 12480    {
 12481      $$.val = append($1.updateExprs(), $3.updateExpr())
 12482    }
 12483  
 12484  // TODO(knz): The LHS in these can be extended to support
 12485  // a path to a field member when compound types are supported.
 12486  // Keep it simple for now.
 12487  set_clause:
 12488    single_set_clause
 12489  | multiple_set_clause
 12490  
 12491  single_set_clause:
 12492    column_name '=' a_expr
 12493    {
 12494      $$.val = &tree.UpdateExpr{Names: tree.NameList{tree.Name($1)}, Expr: $3.expr()}
 12495    }
 12496  | column_name '.' error { return unimplementedWithIssue(sqllex, 27792) }
 12497  
 12498  multiple_set_clause:
 12499    '(' insert_column_list ')' '=' in_expr
 12500    {
 12501      $$.val = &tree.UpdateExpr{Tuple: true, Names: $2.nameList(), Expr: $5.expr()}
 12502    }
 12503  
 12504  // %Help: REASSIGN OWNED BY - change ownership of all objects
 12505  // %Category: Priv
 12506  // %Text: REASSIGN OWNED BY {<name> | CURRENT_USER | SESSION_USER}[,...]
 12507  // TO {<name> | CURRENT_USER | SESSION_USER}
 12508  // %SeeAlso: DROP OWNED BY
 12509  reassign_owned_by_stmt:
 12510    REASSIGN OWNED BY role_spec_list TO role_spec
 12511    {
 12512      $$.val = &tree.ReassignOwnedBy{
 12513        OldRoles: $4.roleSpecList(),
 12514        NewRole: $6.roleSpec(),
 12515      }
 12516    }
 12517  | REASSIGN OWNED BY error // SHOW HELP: REASSIGN OWNED BY
 12518  
 12519  // %Help: DROP OWNED BY - remove database objects owned by role(s).
 12520  // %Category: Priv
 12521  // %Text: DROP OWNED BY {<name> | CURRENT_USER | SESSION_USER}[,...]
 12522  // [RESTRICT | CASCADE]
 12523  // %SeeAlso: REASSIGN OWNED BY
 12524  drop_owned_by_stmt:
 12525    DROP OWNED BY role_spec_list opt_drop_behavior
 12526    {
 12527      $$.val = &tree.DropOwnedBy{
 12528        Roles: $4.roleSpecList(),
 12529        DropBehavior: $5.dropBehavior(),
 12530      }
 12531    }
 12532  | DROP OWNED BY error // SHOW HELP: DROP OWNED BY
 12533  
 12534  // A complete SELECT statement looks like this.
 12535  //
 12536  // The rule returns either a single select_stmt node or a tree of them,
 12537  // representing a set-operation tree.
 12538  //
 12539  // There is an ambiguity when a sub-SELECT is within an a_expr and there are
 12540  // excess parentheses: do the parentheses belong to the sub-SELECT or to the
 12541  // surrounding a_expr?  We don't really care, but bison wants to know. To
 12542  // resolve the ambiguity, we are careful to define the grammar so that the
 12543  // decision is staved off as long as possible: as long as we can keep absorbing
 12544  // parentheses into the sub-SELECT, we will do so, and only when it's no longer
 12545  // possible to do that will we decide that parens belong to the expression. For
 12546  // example, in "SELECT (((SELECT 2)) + 3)" the extra parentheses are treated as
 12547  // part of the sub-select. The necessity of doing it that way is shown by
 12548  // "SELECT (((SELECT 2)) UNION SELECT 2)". Had we parsed "((SELECT 2))" as an
 12549  // a_expr, it'd be too late to go back to the SELECT viewpoint when we see the
 12550  // UNION.
 12551  //
 12552  // This approach is implemented by defining a nonterminal select_with_parens,
 12553  // which represents a SELECT with at least one outer layer of parentheses, and
 12554  // being careful to use select_with_parens, never '(' select_stmt ')', in the
 12555  // expression grammar. We will then have shift-reduce conflicts which we can
 12556  // resolve in favor of always treating '(' <select> ')' as a
 12557  // select_with_parens. To resolve the conflicts, the productions that conflict
 12558  // with the select_with_parens productions are manually given precedences lower
 12559  // than the precedence of ')', thereby ensuring that we shift ')' (and then
 12560  // reduce to select_with_parens) rather than trying to reduce the inner
 12561  // <select> nonterminal to something else. We use UMINUS precedence for this,
 12562  // which is a fairly arbitrary choice.
 12563  //
 12564  // To be able to define select_with_parens itself without ambiguity, we need a
 12565  // nonterminal select_no_parens that represents a SELECT structure with no
 12566  // outermost parentheses. This is a little bit tedious, but it works.
 12567  //
 12568  // In non-expression contexts, we use select_stmt which can represent a SELECT
 12569  // with or without outer parentheses.
 12570  select_stmt:
 12571    select_no_parens %prec UMINUS
 12572  | select_with_parens %prec UMINUS
 12573    {
 12574      $$.val = &tree.Select{Select: $1.selectStmt()}
 12575    }
 12576  
 12577  select_with_parens:
 12578    '(' select_no_parens ')'
 12579    {
 12580      $$.val = &tree.ParenSelect{Select: $2.slct()}
 12581    }
 12582  | '(' select_with_parens ')'
 12583    {
 12584      $$.val = &tree.ParenSelect{Select: &tree.Select{Select: $2.selectStmt()}}
 12585    }
 12586  
 12587  // This rule parses the equivalent of the standard's <query expression>. The
 12588  // duplicative productions are annoying, but hard to get rid of without
 12589  // creating shift/reduce conflicts.
 12590  //
 12591  //      The locking clause (FOR UPDATE etc) may be before or after
 12592  //      LIMIT/OFFSET. In <=7.2.X, LIMIT/OFFSET had to be after FOR UPDATE We
 12593  //      now support both orderings, but prefer LIMIT/OFFSET before the locking
 12594  //      clause.
 12595  //      - 2002-08-28 bjm
 12596  select_no_parens:
 12597    simple_select
 12598    {
 12599      $$.val = &tree.Select{Select: $1.selectStmt()}
 12600    }
 12601  | select_clause sort_clause
 12602    {
 12603      $$.val = &tree.Select{Select: $1.selectStmt(), OrderBy: $2.orderBy()}
 12604    }
 12605  | select_clause opt_sort_clause for_locking_clause opt_select_limit
 12606    {
 12607      $$.val = &tree.Select{Select: $1.selectStmt(), OrderBy: $2.orderBy(), Limit: $4.limit(), Locking: $3.lockingClause()}
 12608    }
 12609  | select_clause opt_sort_clause select_limit opt_for_locking_clause
 12610    {
 12611      $$.val = &tree.Select{Select: $1.selectStmt(), OrderBy: $2.orderBy(), Limit: $3.limit(), Locking: $4.lockingClause()}
 12612    }
 12613  | with_clause select_clause
 12614    {
 12615      $$.val = &tree.Select{With: $1.with(), Select: $2.selectStmt()}
 12616    }
 12617  | with_clause select_clause sort_clause
 12618    {
 12619      $$.val = &tree.Select{With: $1.with(), Select: $2.selectStmt(), OrderBy: $3.orderBy()}
 12620    }
 12621  | with_clause select_clause opt_sort_clause for_locking_clause opt_select_limit
 12622    {
 12623      $$.val = &tree.Select{With: $1.with(), Select: $2.selectStmt(), OrderBy: $3.orderBy(), Limit: $5.limit(), Locking: $4.lockingClause()}
 12624    }
 12625  | with_clause select_clause opt_sort_clause select_limit opt_for_locking_clause
 12626    {
 12627      $$.val = &tree.Select{With: $1.with(), Select: $2.selectStmt(), OrderBy: $3.orderBy(), Limit: $4.limit(), Locking: $5.lockingClause()}
 12628    }
 12629  
 12630  for_locking_clause:
 12631    for_locking_items { $$.val = $1.lockingClause() }
 12632  | FOR READ ONLY     { $$.val = (tree.LockingClause)(nil) }
 12633  
 12634  opt_for_locking_clause:
 12635    for_locking_clause { $$.val = $1.lockingClause() }
 12636  | /* EMPTY */        { $$.val = (tree.LockingClause)(nil) }
 12637  
 12638  for_locking_items:
 12639    for_locking_item
 12640    {
 12641      $$.val = tree.LockingClause{$1.lockingItem()}
 12642    }
 12643  | for_locking_items for_locking_item
 12644    {
 12645      $$.val = append($1.lockingClause(), $2.lockingItem())
 12646    }
 12647  
 12648  for_locking_item:
 12649    for_locking_strength opt_locked_rels opt_nowait_or_skip
 12650    {
 12651      $$.val = &tree.LockingItem{
 12652        Strength:   $1.lockingStrength(),
 12653        Targets:    $2.tableNames(),
 12654        WaitPolicy: $3.lockingWaitPolicy(),
 12655      }
 12656    }
 12657  
 12658  for_locking_strength:
 12659    FOR UPDATE        { $$.val = tree.ForUpdate }
 12660  | FOR NO KEY UPDATE { $$.val = tree.ForNoKeyUpdate }
 12661  | FOR SHARE         { $$.val = tree.ForShare }
 12662  | FOR KEY SHARE     { $$.val = tree.ForKeyShare }
 12663  
 12664  opt_locked_rels:
 12665    /* EMPTY */        { $$.val = tree.TableNames{} }
 12666  | OF table_name_list { $$.val = $2.tableNames() }
 12667  
 12668  opt_nowait_or_skip:
 12669    /* EMPTY */ { $$.val = tree.LockWaitBlock }
 12670  | SKIP LOCKED { $$.val = tree.LockWaitSkipLocked }
 12671  | NOWAIT      { $$.val = tree.LockWaitError }
 12672  
 12673  select_clause:
 12674  // We only provide help if an open parenthesis is provided, because
 12675  // otherwise the rule is ambiguous with the top-level statement list.
 12676    '(' error // SHOW HELP: <SELECTCLAUSE>
 12677  | simple_select
 12678  | select_with_parens
 12679  
 12680  // This rule parses SELECT statements that can appear within set operations,
 12681  // including UNION, INTERSECT and EXCEPT. '(' and ')' can be used to specify
 12682  // the ordering of the set operations. Without '(' and ')' we want the
 12683  // operations to be ordered per the precedence specs at the head of this file.
 12684  //
 12685  // As with select_no_parens, simple_select cannot have outer parentheses, but
 12686  // can have parenthesized subclauses.
 12687  //
 12688  // Note that sort clauses cannot be included at this level --- SQL requires
 12689  //       SELECT foo UNION SELECT bar ORDER BY baz
 12690  // to be parsed as
 12691  //       (SELECT foo UNION SELECT bar) ORDER BY baz
 12692  // not
 12693  //       SELECT foo UNION (SELECT bar ORDER BY baz)
 12694  //
 12695  // Likewise for WITH, FOR UPDATE and LIMIT. Therefore, those clauses are
 12696  // described as part of the select_no_parens production, not simple_select.
 12697  // This does not limit functionality, because you can reintroduce these clauses
 12698  // inside parentheses.
 12699  //
 12700  // NOTE: only the leftmost component select_stmt should have INTO. However,
 12701  // this is not checked by the grammar; parse analysis must check it.
 12702  //
 12703  // %Help: <SELECTCLAUSE> - access tabular data
 12704  // %Category: DML
 12705  // %Text:
 12706  // Select clause:
 12707  //   TABLE <tablename>
 12708  //   VALUES ( <exprs...> ) [ , ... ]
 12709  //   SELECT ... [ { INTERSECT | UNION | EXCEPT } [ ALL | DISTINCT ] <selectclause> ]
 12710  simple_select:
 12711    simple_select_clause // EXTEND WITH HELP: SELECT
 12712  | values_clause        // EXTEND WITH HELP: VALUES
 12713  | table_clause         // EXTEND WITH HELP: TABLE
 12714  | set_operation
 12715  
 12716  // %Help: SELECT - retrieve rows from a data source and compute a result
 12717  // %Category: DML
 12718  // %Text:
 12719  // SELECT [DISTINCT [ ON ( <expr> [ , ... ] ) ] ]
 12720  //        { <expr> [[AS] <name>] | [ [<dbname>.] <tablename>. ] * } [, ...]
 12721  //        [ FROM <source> ]
 12722  //        [ WHERE <expr> ]
 12723  //        [ GROUP BY <expr> [ , ... ] ]
 12724  //        [ HAVING <expr> ]
 12725  //        [ WINDOW <name> AS ( <definition> ) ]
 12726  //        [ { UNION | INTERSECT | EXCEPT } [ ALL | DISTINCT ] <selectclause> ]
 12727  //        [ ORDER BY <expr> [ ASC | DESC ] [, ...] ]
 12728  //        [ LIMIT { <expr> | ALL } ]
 12729  //        [ OFFSET <expr> [ ROW | ROWS ] ]
 12730  // %SeeAlso: WEBDOCS/select-clause.html
 12731  simple_select_clause:
 12732    SELECT opt_all_clause target_list
 12733      from_clause opt_where_clause
 12734      group_clause having_clause window_clause
 12735    {
 12736      $$.val = &tree.SelectClause{
 12737        Exprs:   $3.selExprs(),
 12738        From:    $4.from(),
 12739        Where:   tree.NewWhere(tree.AstWhere, $5.expr()),
 12740        GroupBy: $6.groupBy(),
 12741        Having:  tree.NewWhere(tree.AstHaving, $7.expr()),
 12742        Window:  $8.window(),
 12743      }
 12744    }
 12745  | SELECT distinct_clause target_list
 12746      from_clause opt_where_clause
 12747      group_clause having_clause window_clause
 12748    {
 12749      $$.val = &tree.SelectClause{
 12750        Distinct: $2.bool(),
 12751        Exprs:    $3.selExprs(),
 12752        From:     $4.from(),
 12753        Where:    tree.NewWhere(tree.AstWhere, $5.expr()),
 12754        GroupBy:  $6.groupBy(),
 12755        Having:   tree.NewWhere(tree.AstHaving, $7.expr()),
 12756        Window:   $8.window(),
 12757      }
 12758    }
 12759  | SELECT distinct_on_clause target_list
 12760      from_clause opt_where_clause
 12761      group_clause having_clause window_clause
 12762    {
 12763      $$.val = &tree.SelectClause{
 12764        Distinct:   true,
 12765        DistinctOn: $2.distinctOn(),
 12766        Exprs:      $3.selExprs(),
 12767        From:       $4.from(),
 12768        Where:      tree.NewWhere(tree.AstWhere, $5.expr()),
 12769        GroupBy:    $6.groupBy(),
 12770        Having:     tree.NewWhere(tree.AstHaving, $7.expr()),
 12771        Window:     $8.window(),
 12772      }
 12773    }
 12774  | SELECT error // SHOW HELP: SELECT
 12775  
 12776  set_operation:
 12777    select_clause UNION all_or_distinct select_clause
 12778    {
 12779      $$.val = &tree.UnionClause{
 12780        Type:  tree.UnionOp,
 12781        Left:  &tree.Select{Select: $1.selectStmt()},
 12782        Right: &tree.Select{Select: $4.selectStmt()},
 12783        All:   $3.bool(),
 12784      }
 12785    }
 12786  | select_clause INTERSECT all_or_distinct select_clause
 12787    {
 12788      $$.val = &tree.UnionClause{
 12789        Type:  tree.IntersectOp,
 12790        Left:  &tree.Select{Select: $1.selectStmt()},
 12791        Right: &tree.Select{Select: $4.selectStmt()},
 12792        All:   $3.bool(),
 12793      }
 12794    }
 12795  | select_clause EXCEPT all_or_distinct select_clause
 12796    {
 12797      $$.val = &tree.UnionClause{
 12798        Type:  tree.ExceptOp,
 12799        Left:  &tree.Select{Select: $1.selectStmt()},
 12800        Right: &tree.Select{Select: $4.selectStmt()},
 12801        All:   $3.bool(),
 12802      }
 12803    }
 12804  
 12805  // %Help: TABLE - select an entire table
 12806  // %Category: DML
 12807  // %Text: TABLE <tablename>
 12808  // %SeeAlso: SELECT, VALUES, WEBDOCS/table-expressions.html
 12809  table_clause:
 12810    TABLE table_ref
 12811    {
 12812      $$.val = &tree.SelectClause{
 12813        Exprs:       tree.SelectExprs{tree.StarSelectExpr()},
 12814        From:        tree.From{Tables: tree.TableExprs{$2.tblExpr()}},
 12815        TableSelect: true,
 12816      }
 12817    }
 12818  | TABLE error // SHOW HELP: TABLE
 12819  
 12820  // SQL standard WITH clause looks like:
 12821  //
 12822  // WITH [ RECURSIVE ] <query name> [ (<column> [, ...]) ]
 12823  //        AS [ [ NOT ] MATERIALIZED ] (query) [ SEARCH or CYCLE clause ]
 12824  //
 12825  // We don't currently support the SEARCH or CYCLE clause.
 12826  //
 12827  // Recognizing WITH_LA here allows a CTE to be named TIME or ORDINALITY.
 12828  with_clause:
 12829    WITH cte_list
 12830    {
 12831      $$.val = &tree.With{CTEList: $2.ctes()}
 12832    }
 12833  | WITH_LA cte_list
 12834    {
 12835      /* SKIP DOC */
 12836      $$.val = &tree.With{CTEList: $2.ctes()}
 12837    }
 12838  | WITH RECURSIVE cte_list
 12839    {
 12840      $$.val = &tree.With{Recursive: true, CTEList: $3.ctes()}
 12841    }
 12842  
 12843  cte_list:
 12844    common_table_expr
 12845    {
 12846      $$.val = []*tree.CTE{$1.cte()}
 12847    }
 12848  | cte_list ',' common_table_expr
 12849    {
 12850      $$.val = append($1.ctes(), $3.cte())
 12851    }
 12852  
 12853  materialize_clause:
 12854    MATERIALIZED
 12855    {
 12856      $$.val = tree.CTEMaterializeAlways
 12857    }
 12858  | NOT MATERIALIZED
 12859    {
 12860      $$.val = tree.CTEMaterializeNever
 12861    }
 12862  | /* EMPTY */ {
 12863      $$.val = tree.CTEMaterializeDefault
 12864  }
 12865  
 12866  common_table_expr:
 12867    table_alias_name opt_col_def_list_no_types AS materialize_clause '(' preparable_stmt ')'
 12868      {
 12869        $$.val = &tree.CTE{
 12870          Name: tree.AliasClause{Alias: tree.Name($1), Cols: $2.colDefList() },
 12871          Mtr: $4.cteMaterializeClause(),
 12872          Stmt: $6.stmt(),
 12873        }
 12874      }
 12875  
 12876  opt_with:
 12877    WITH {}
 12878  | /* EMPTY */ {}
 12879  
 12880  opt_with_clause:
 12881    with_clause
 12882    {
 12883      $$.val = $1.with()
 12884    }
 12885  | /* EMPTY */
 12886    {
 12887      $$.val = nil
 12888    }
 12889  
 12890  opt_table:
 12891    TABLE {}
 12892  | /* EMPTY */ {}
 12893  
 12894  all_or_distinct:
 12895    ALL
 12896    {
 12897      $$.val = true
 12898    }
 12899  | DISTINCT
 12900    {
 12901      $$.val = false
 12902    }
 12903  | /* EMPTY */
 12904    {
 12905      $$.val = false
 12906    }
 12907  
 12908  distinct_clause:
 12909    DISTINCT
 12910    {
 12911      $$.val = true
 12912    }
 12913  
 12914  distinct_on_clause:
 12915    DISTINCT ON '(' expr_list ')'
 12916    {
 12917      $$.val = tree.DistinctOn($4.exprs())
 12918    }
 12919  
 12920  opt_all_clause:
 12921    ALL {}
 12922  | /* EMPTY */ {}
 12923  
 12924  opt_privileges_clause:
 12925    PRIVILEGES {}
 12926  | /* EMPTY */ {}
 12927  
 12928  opt_sort_clause:
 12929    sort_clause
 12930    {
 12931      $$.val = $1.orderBy()
 12932    }
 12933  | /* EMPTY */
 12934    {
 12935      $$.val = tree.OrderBy(nil)
 12936    }
 12937  
 12938  opt_sort_clause_no_index:
 12939    sort_clause_no_index
 12940    {
 12941      $$.val = $1.orderBy()
 12942    }
 12943  | /* EMPTY */
 12944    {
 12945      $$.val = tree.OrderBy(nil)
 12946    }
 12947  
 12948  sort_clause:
 12949    ORDER BY sortby_list
 12950    {
 12951      $$.val = tree.OrderBy($3.orders())
 12952    }
 12953  
 12954  sort_clause_no_index:
 12955    ORDER BY sortby_no_index_list
 12956    {
 12957      $$.val = tree.OrderBy($3.orders())
 12958    }
 12959  
 12960  single_sort_clause:
 12961    ORDER BY sortby
 12962    {
 12963      $$.val = tree.OrderBy([]*tree.Order{$3.order()})
 12964    }
 12965  | ORDER BY sortby_index
 12966    {
 12967      return unimplementedWithIssueDetail(sqllex, 109847, "order by index")
 12968    }
 12969  | ORDER BY sortby ',' sortby_list
 12970    {
 12971      sqllex.Error("multiple ORDER BY clauses are not supported in this function")
 12972      return 1
 12973    }
 12974  | ORDER BY sortby_index ',' sortby_list
 12975    {
 12976      sqllex.Error("multiple ORDER BY clauses are not supported in this function")
 12977      return 1
 12978    }
 12979  
 12980  sortby_list:
 12981    sortby
 12982    {
 12983      $$.val = []*tree.Order{$1.order()}
 12984    }
 12985  | sortby_index
 12986    {
 12987      $$.val = []*tree.Order{$1.order()}
 12988    }
 12989  | sortby_list ',' sortby
 12990    {
 12991      $$.val = append($1.orders(), $3.order())
 12992    }
 12993  | sortby_list ',' sortby_index
 12994    {
 12995      $$.val = append($1.orders(), $3.order())
 12996    }
 12997  
 12998  sortby_no_index_list:
 12999    sortby
 13000    {
 13001      $$.val = []*tree.Order{$1.order()}
 13002    }
 13003  | sortby_no_index_list ',' sortby
 13004    {
 13005      $$.val = append($1.orders(), $3.order())
 13006    }
 13007  | sortby_no_index_list ',' sortby_index
 13008    {
 13009      $$.val = append($1.orders(), $3.order())
 13010    }
 13011  
 13012  sortby_index:
 13013    PRIMARY KEY table_name opt_asc_desc
 13014    {
 13015      name := $3.unresolvedObjectName().ToTableName()
 13016      $$.val = &tree.Order{OrderType: tree.OrderByIndex, Direction: $4.dir(), Table: name}
 13017    }
 13018  | INDEX_AFTER_ORDER_BY_BEFORE_AT table_name '@' index_name opt_asc_desc
 13019    {
 13020      name := $2.unresolvedObjectName().ToTableName()
 13021      $$.val = &tree.Order{
 13022        OrderType: tree.OrderByIndex,
 13023        Direction: $5.dir(),
 13024        Table:     name,
 13025        Index:     tree.UnrestrictedName($4),
 13026      }
 13027    }
 13028  
 13029  sortby:
 13030    a_expr opt_asc_desc opt_nulls_order
 13031    {
 13032      /* FORCE DOC */
 13033      dir := $2.dir()
 13034      nullsOrder := $3.nullsOrder()
 13035      $$.val = &tree.Order{
 13036        OrderType:  tree.OrderByColumn,
 13037        Expr:       $1.expr(),
 13038        Direction:  dir,
 13039        NullsOrder: nullsOrder,
 13040      }
 13041    }
 13042  
 13043  opt_nulls_order:
 13044    NULLS_LA FIRST
 13045    {
 13046      $$.val = tree.NullsFirst
 13047    }
 13048  | NULLS_LA LAST
 13049    {
 13050      $$.val = tree.NullsLast
 13051    }
 13052  | /* EMPTY */
 13053    {
 13054      $$.val = tree.DefaultNullsOrder
 13055    }
 13056  
 13057  select_limit:
 13058    limit_clause offset_clause
 13059    {
 13060      if $1.limit() == nil {
 13061        $$.val = $2.limit()
 13062      } else {
 13063        $$.val = $1.limit()
 13064        $$.val.(*tree.Limit).Offset = $2.limit().Offset
 13065      }
 13066    }
 13067  | offset_clause limit_clause
 13068    {
 13069      $$.val = $1.limit()
 13070      if $2.limit() != nil {
 13071        $$.val.(*tree.Limit).Count = $2.limit().Count
 13072        $$.val.(*tree.Limit).LimitAll = $2.limit().LimitAll
 13073      }
 13074    }
 13075  | limit_clause
 13076  | offset_clause
 13077  
 13078  opt_select_limit:
 13079    select_limit { $$.val = $1.limit() }
 13080  | /* EMPTY */  { $$.val = (*tree.Limit)(nil) }
 13081  
 13082  opt_limit_clause:
 13083    limit_clause
 13084  | /* EMPTY */ { $$.val = (*tree.Limit)(nil) }
 13085  
 13086  limit_clause:
 13087    LIMIT ALL
 13088    {
 13089      $$.val = &tree.Limit{LimitAll: true}
 13090    }
 13091  | LIMIT a_expr
 13092    {
 13093      if $2.expr() == nil {
 13094        $$.val = (*tree.Limit)(nil)
 13095      } else {
 13096        $$.val = &tree.Limit{Count: $2.expr()}
 13097      }
 13098    }
 13099  // SQL:2008 syntax
 13100  // To avoid shift/reduce conflicts, handle the optional value with
 13101  // a separate production rather than an opt_ expression. The fact
 13102  // that ONLY is fully reserved means that this way, we defer any
 13103  // decision about what rule reduces ROW or ROWS to the point where
 13104  // we can see the ONLY token in the lookahead slot.
 13105  | FETCH first_or_next select_fetch_first_value row_or_rows ONLY
 13106    {
 13107      $$.val = &tree.Limit{Count: $3.expr()}
 13108    }
 13109  | FETCH first_or_next row_or_rows ONLY
 13110  	{
 13111      $$.val = &tree.Limit{
 13112        Count: tree.NewNumVal(constant.MakeInt64(1), "" /* origString */, false /* negative */),
 13113      }
 13114    }
 13115  
 13116  offset_clause:
 13117    OFFSET a_expr
 13118    {
 13119      $$.val = &tree.Limit{Offset: $2.expr()}
 13120    }
 13121    // SQL:2008 syntax
 13122    // The trailing ROW/ROWS in this case prevent the full expression
 13123    // syntax. c_expr is the best we can do.
 13124  | OFFSET select_fetch_first_value row_or_rows
 13125    {
 13126      $$.val = &tree.Limit{Offset: $2.expr()}
 13127    }
 13128  
 13129  // Allowing full expressions without parentheses causes various parsing
 13130  // problems with the trailing ROW/ROWS key words. SQL spec only calls for
 13131  // <simple value specification>, which is either a literal or a parameter (but
 13132  // an <SQL parameter reference> could be an identifier, bringing up conflicts
 13133  // with ROW/ROWS). We solve this by leveraging the presence of ONLY (see above)
 13134  // to determine whether the expression is missing rather than trying to make it
 13135  // optional in this rule.
 13136  //
 13137  // c_expr covers almost all the spec-required cases (and more), but it doesn't
 13138  // cover signed numeric literals, which are allowed by the spec. So we include
 13139  // those here explicitly.
 13140  select_fetch_first_value:
 13141    c_expr
 13142  | only_signed_iconst
 13143  | only_signed_fconst
 13144  
 13145  // noise words
 13146  row_or_rows:
 13147    ROW {}
 13148  | ROWS {}
 13149  
 13150  first_or_next:
 13151    FIRST {}
 13152  | NEXT {}
 13153  
 13154  // This syntax for group_clause tries to follow the spec quite closely.
 13155  // However, the spec allows only column references, not expressions,
 13156  // which introduces an ambiguity between implicit row constructors
 13157  // (a,b) and lists of column references.
 13158  //
 13159  // We handle this by using the a_expr production for what the spec calls
 13160  // <ordinary grouping set>, which in the spec represents either one column
 13161  // reference or a parenthesized list of column references. Then, we check the
 13162  // top node of the a_expr to see if it's an RowExpr, and if so, just grab and
 13163  // use the list, discarding the node. (this is done in parse analysis, not here)
 13164  //
 13165  // Each item in the group_clause list is either an expression tree or a
 13166  // GroupingSet node of some type.
 13167  group_clause:
 13168    GROUP BY group_by_list
 13169    {
 13170      $$.val = tree.GroupBy($3.exprs())
 13171    }
 13172  | /* EMPTY */
 13173    {
 13174      $$.val = tree.GroupBy(nil)
 13175    }
 13176  
 13177  group_by_list:
 13178    group_by_item { $$.val = tree.Exprs{$1.expr()} }
 13179  | group_by_list ',' group_by_item { $$.val = append($1.exprs(), $3.expr()) }
 13180  
 13181  // Note the '(' is required as CUBE and ROLLUP rely on setting precedence
 13182  // of CUBE and ROLLUP below that of '(', so that they shift in these rules
 13183  // rather than reducing the conflicting unreserved_keyword rule.
 13184  group_by_item:
 13185    a_expr { $$.val = $1.expr() }
 13186  | ROLLUP '(' error { return unimplementedWithIssueDetail(sqllex, 46280, "rollup") }
 13187  | CUBE '(' error { return unimplementedWithIssueDetail(sqllex, 46280, "cube") }
 13188  | GROUPING SETS error { return unimplementedWithIssueDetail(sqllex, 46280, "grouping sets") }
 13189  
 13190  having_clause:
 13191    HAVING a_expr
 13192    {
 13193      $$.val = $2.expr()
 13194    }
 13195  | /* EMPTY */
 13196    {
 13197      $$.val = tree.Expr(nil)
 13198    }
 13199  
 13200  // Given "VALUES (a, b)" in a table expression context, we have to
 13201  // decide without looking any further ahead whether VALUES is the
 13202  // values clause or a set-generating function. Since VALUES is allowed
 13203  // as a function name both interpretations are feasible. We resolve
 13204  // the shift/reduce conflict by giving the first values_clause
 13205  // production a higher precedence than the VALUES token has, causing
 13206  // the parser to prefer to reduce, in effect assuming that the VALUES
 13207  // is not a function name.
 13208  //
 13209  // %Help: VALUES - select a given set of values
 13210  // %Category: DML
 13211  // %Text: VALUES ( <exprs...> ) [, ...]
 13212  // %SeeAlso: SELECT, TABLE, WEBDOCS/table-expressions.html
 13213  values_clause:
 13214    VALUES '(' expr_list ')' %prec UMINUS
 13215    {
 13216      $$.val = &tree.ValuesClause{Rows: []tree.Exprs{$3.exprs()}}
 13217    }
 13218  | VALUES error // SHOW HELP: VALUES
 13219  | values_clause ',' '(' expr_list ')'
 13220    {
 13221      valNode := $1.selectStmt().(*tree.ValuesClause)
 13222      valNode.Rows = append(valNode.Rows, $4.exprs())
 13223      $$.val = valNode
 13224    }
 13225  
 13226  // clauses common to all optimizable statements:
 13227  //  from_clause   - allow list of both JOIN expressions and table names
 13228  //  where_clause  - qualifications for joins or restrictions
 13229  
 13230  from_clause:
 13231    FROM from_list opt_as_of_clause
 13232    {
 13233      $$.val = tree.From{Tables: $2.tblExprs(), AsOf: $3.asOfClause()}
 13234    }
 13235  | FROM error // SHOW HELP: <SOURCE>
 13236  | /* EMPTY */
 13237    {
 13238      $$.val = tree.From{}
 13239    }
 13240  
 13241  from_list:
 13242    table_ref
 13243    {
 13244      $$.val = tree.TableExprs{$1.tblExpr()}
 13245    }
 13246  | from_list ',' table_ref
 13247    {
 13248      $$.val = append($1.tblExprs(), $3.tblExpr())
 13249    }
 13250  
 13251  index_flags_param:
 13252    FORCE_INDEX '=' index_name
 13253    {
 13254       $$.val = &tree.IndexFlags{Index: tree.UnrestrictedName($3)}
 13255    }
 13256  | FORCE_INDEX '=' '[' iconst64 ']'
 13257    {
 13258      /* SKIP DOC */
 13259      $$.val = &tree.IndexFlags{IndexID: tree.IndexID($4.int64())}
 13260    }
 13261  | ASC
 13262    {
 13263      /* SKIP DOC */
 13264      $$.val = &tree.IndexFlags{Direction: tree.Ascending}
 13265    }
 13266  | DESC
 13267    {
 13268      /* SKIP DOC */
 13269      $$.val = &tree.IndexFlags{Direction: tree.Descending}
 13270    }
 13271  |
 13272    NO_INDEX_JOIN
 13273    {
 13274      $$.val = &tree.IndexFlags{NoIndexJoin: true}
 13275    }
 13276  |
 13277    NO_ZIGZAG_JOIN
 13278    {
 13279      $$.val = &tree.IndexFlags{NoZigzagJoin: true}
 13280    }
 13281  |
 13282    NO_FULL_SCAN
 13283    {
 13284      $$.val = &tree.IndexFlags{NoFullScan: true}
 13285    }
 13286  |
 13287    IGNORE_FOREIGN_KEYS
 13288    {
 13289      /* SKIP DOC */
 13290      $$.val = &tree.IndexFlags{IgnoreForeignKeys: true}
 13291    }
 13292  |
 13293    FORCE_ZIGZAG
 13294    {
 13295       $$.val = &tree.IndexFlags{ForceZigzag: true}
 13296    }
 13297  |
 13298    FORCE_ZIGZAG '=' index_name
 13299    {
 13300       $$.val = &tree.IndexFlags{ZigzagIndexes: []tree.UnrestrictedName{tree.UnrestrictedName($3)}}
 13301    }
 13302  |
 13303    FORCE_ZIGZAG '=' '[' iconst64 ']'
 13304    {
 13305      /* SKIP DOC */
 13306       $$.val = &tree.IndexFlags{ZigzagIndexIDs: []tree.IndexID{tree.IndexID($4.int64())}}
 13307    }
 13308  | FAMILY '=' '[' iconst64 ']'
 13309    {
 13310      /* SKIP DOC */
 13311      id := tree.FamilyID(uint32($4.int64()))
 13312       $$.val = &tree.IndexFlags{FamilyID: &id}
 13313    }
 13314  
 13315  index_flags_param_list:
 13316    index_flags_param
 13317    {
 13318      $$.val = $1.indexFlags()
 13319    }
 13320  |
 13321    index_flags_param_list ',' index_flags_param
 13322    {
 13323      a := $1.indexFlags()
 13324      b := $3.indexFlags()
 13325      if err := a.CombineWith(b); err != nil {
 13326        return setErr(sqllex, err)
 13327      }
 13328      $$.val = a
 13329    }
 13330  
 13331  opt_index_flags:
 13332    '@' index_name
 13333    {
 13334      $$.val = &tree.IndexFlags{Index: tree.UnrestrictedName($2)}
 13335    }
 13336  | '@' '[' iconst64 ']'
 13337    {
 13338      $$.val = &tree.IndexFlags{IndexID: tree.IndexID($3.int64())}
 13339    }
 13340  | '@' '{' index_flags_param_list '}'
 13341    {
 13342      flags := $3.indexFlags()
 13343      if err := flags.Check(); err != nil {
 13344        return setErr(sqllex, err)
 13345      }
 13346      $$.val = flags
 13347    }
 13348  | /* EMPTY */
 13349    {
 13350      $$.val = (*tree.IndexFlags)(nil)
 13351    }
 13352  
 13353  // %Help: <SOURCE> - define a data source for SELECT
 13354  // %Category: DML
 13355  // %Text:
 13356  // Data sources:
 13357  //   <tablename> [ @ { <idxname> | <indexflags> } ]
 13358  //   <tablefunc> ( <exprs...> )
 13359  //   ( { <selectclause> | <source> } )
 13360  //   <source> [AS] <alias> [( <colnames...> )]
 13361  //   <source> [ <jointype> ] JOIN <source> ON <expr>
 13362  //   <source> [ <jointype> ] JOIN <source> USING ( <colnames...> )
 13363  //   <source> NATURAL [ <jointype> ] JOIN <source>
 13364  //   <source> CROSS JOIN <source>
 13365  //   <source> WITH ORDINALITY
 13366  //   '[' EXPLAIN ... ']'
 13367  //   '[' SHOW ... ']'
 13368  //
 13369  // Index flags:
 13370  //   '{' FORCE_INDEX = <idxname> [, ...] '}'
 13371  //   '{' NO_INDEX_JOIN [, ...] '}'
 13372  //   '{' NO_ZIGZAG_JOIN [, ...] '}'
 13373  //   '{' NO_FULL_SCAN [, ...] '}'
 13374  //   '{' IGNORE_FOREIGN_KEYS [, ...] '}'
 13375  //   '{' FORCE_ZIGZAG = <idxname> [, ...]  '}'
 13376  //
 13377  // Join types:
 13378  //   { INNER | { LEFT | RIGHT | FULL } [OUTER] } [ { HASH | MERGE | LOOKUP | INVERTED } ]
 13379  //
 13380  // %SeeAlso: WEBDOCS/table-expressions.html
 13381  table_ref:
 13382    numeric_table_ref opt_index_flags opt_ordinality opt_alias_clause
 13383    {
 13384      /* SKIP DOC */
 13385      $$.val = &tree.AliasedTableExpr{
 13386          Expr:       $1.tblExpr(),
 13387          IndexFlags: $2.indexFlags(),
 13388          Ordinality: $3.bool(),
 13389          As:         $4.aliasClause(),
 13390      }
 13391    }
 13392  | relation_expr opt_index_flags opt_ordinality opt_alias_clause
 13393    {
 13394      name := $1.unresolvedObjectName().ToTableName()
 13395      $$.val = &tree.AliasedTableExpr{
 13396        Expr:       &name,
 13397        IndexFlags: $2.indexFlags(),
 13398        Ordinality: $3.bool(),
 13399        As:         $4.aliasClause(),
 13400      }
 13401    }
 13402  | select_with_parens opt_ordinality opt_alias_clause
 13403    {
 13404      $$.val = &tree.AliasedTableExpr{
 13405        Expr:       &tree.Subquery{Select: $1.selectStmt()},
 13406        Ordinality: $2.bool(),
 13407        As:         $3.aliasClause(),
 13408      }
 13409    }
 13410  | LATERAL select_with_parens opt_ordinality opt_alias_clause
 13411    {
 13412      $$.val = &tree.AliasedTableExpr{
 13413        Expr:       &tree.Subquery{Select: $2.selectStmt()},
 13414        Ordinality: $3.bool(),
 13415        Lateral:    true,
 13416        As:         $4.aliasClause(),
 13417      }
 13418    }
 13419  | joined_table
 13420    {
 13421      $$.val = $1.tblExpr()
 13422    }
 13423  | '(' joined_table ')' opt_ordinality alias_clause
 13424    {
 13425      $$.val = &tree.AliasedTableExpr{Expr: &tree.ParenTableExpr{Expr: $2.tblExpr()}, Ordinality: $4.bool(), As: $5.aliasClause()}
 13426    }
 13427  | func_table opt_ordinality opt_func_alias_clause
 13428    {
 13429      f := $1.tblExpr()
 13430      $$.val = &tree.AliasedTableExpr{
 13431        Expr: f,
 13432        Ordinality: $2.bool(),
 13433        // Technically, LATERAL is always implied on an SRF, but including it
 13434        // here makes re-printing the AST slightly tricky.
 13435        As: $3.aliasClause(),
 13436      }
 13437    }
 13438  | LATERAL func_table opt_ordinality opt_alias_clause
 13439    {
 13440      f := $2.tblExpr()
 13441      $$.val = &tree.AliasedTableExpr{
 13442        Expr: f,
 13443        Ordinality: $3.bool(),
 13444        Lateral: true,
 13445        As: $4.aliasClause(),
 13446      }
 13447    }
 13448  // The following syntax is a CockroachDB extension:
 13449  //     SELECT ... FROM [ EXPLAIN .... ] WHERE ...
 13450  //     SELECT ... FROM [ SHOW .... ] WHERE ...
 13451  //     SELECT ... FROM [ INSERT ... RETURNING ... ] WHERE ...
 13452  // A statement within square brackets can be used as a table expression (data source).
 13453  // We use square brackets for two reasons:
 13454  // - the grammar would be terribly ambiguous if we used simple
 13455  //   parentheses or no parentheses at all.
 13456  // - it carries visual semantic information, by marking the table
 13457  //   expression as radically different from the other things.
 13458  //   If a user does not know this and encounters this syntax, they
 13459  //   will know from the unusual choice that something rather different
 13460  //   is going on and may be pushed by the unusual syntax to
 13461  //   investigate further in the docs.
 13462  | '[' row_source_extension_stmt ']' opt_ordinality opt_alias_clause
 13463    {
 13464      $$.val = &tree.AliasedTableExpr{Expr: &tree.StatementSource{ Statement: $2.stmt() }, Ordinality: $4.bool(), As: $5.aliasClause() }
 13465    }
 13466  
 13467  numeric_table_ref:
 13468    '[' iconst64 opt_tableref_col_list alias_clause ']'
 13469    {
 13470      /* SKIP DOC */
 13471      $$.val = &tree.TableRef{
 13472        TableID: $2.int64(),
 13473        Columns: $3.tableRefCols(),
 13474        As:      $4.aliasClause(),
 13475      }
 13476    }
 13477  
 13478  func_table:
 13479    func_expr_windowless
 13480    {
 13481      $$.val = &tree.RowsFromExpr{Items: tree.Exprs{$1.expr()}}
 13482    }
 13483  | ROWS FROM '(' rowsfrom_list ')'
 13484    {
 13485      $$.val = &tree.RowsFromExpr{Items: $4.exprs()}
 13486    }
 13487  
 13488  rowsfrom_list:
 13489    rowsfrom_item
 13490    { $$.val = tree.Exprs{$1.expr()} }
 13491  | rowsfrom_list ',' rowsfrom_item
 13492    { $$.val = append($1.exprs(), $3.expr()) }
 13493  
 13494  rowsfrom_item:
 13495    func_expr_windowless opt_func_alias_clause
 13496    {
 13497      $$.val = $1.expr()
 13498    }
 13499  
 13500  opt_col_def_list_no_types:
 13501    '(' col_def_list_no_types ')'
 13502    {
 13503      $$.val = $2.colDefList()
 13504    }
 13505  | /* EMPTY */
 13506    {
 13507      $$.val = tree.ColumnDefList(nil)
 13508    }
 13509  
 13510  col_def_list_no_types:
 13511    name
 13512    {
 13513      $$.val = tree.ColumnDefList{tree.ColumnDef{Name: tree.Name($1)}}
 13514    }
 13515  | col_def_list_no_types ',' name
 13516    {
 13517      $$.val = append($1.colDefList(), tree.ColumnDef{Name: tree.Name($3)})
 13518    }
 13519  
 13520  
 13521  opt_col_def_list:
 13522    /* EMPTY */
 13523    {
 13524      $$.val = tree.ColumnDefList(nil)
 13525    }
 13526  | '(' col_def_list ')'
 13527    {
 13528      $$.val = $2.colDefList()
 13529    }
 13530  
 13531  col_def_list:
 13532    col_def
 13533    {
 13534      $$.val = tree.ColumnDefList{$1.colDef()}
 13535    }
 13536  | col_def_list ',' col_def
 13537    {
 13538      $$.val = append($1.colDefList(), $3.colDef())
 13539    }
 13540  
 13541  col_def:
 13542    name
 13543    {
 13544      $$.val = tree.ColumnDef{Name: tree.Name($1)}
 13545    }
 13546  | name typename
 13547    {
 13548      $$.val = tree.ColumnDef{Name: tree.Name($1), Type: $2.typeReference()}
 13549    }
 13550  
 13551  opt_tableref_col_list:
 13552    /* EMPTY */               { $$.val = nil }
 13553  | '(' ')'                   { $$.val = []tree.ColumnID{} }
 13554  | '(' tableref_col_list ')' { $$.val = $2.tableRefCols() }
 13555  
 13556  tableref_col_list:
 13557    iconst64
 13558    {
 13559      $$.val = []tree.ColumnID{tree.ColumnID($1.int64())}
 13560    }
 13561  | tableref_col_list ',' iconst64
 13562    {
 13563      $$.val = append($1.tableRefCols(), tree.ColumnID($3.int64()))
 13564    }
 13565  
 13566  opt_ordinality:
 13567    WITH_LA ORDINALITY
 13568    {
 13569      $$.val = true
 13570    }
 13571  | /* EMPTY */
 13572    {
 13573      $$.val = false
 13574    }
 13575  
 13576  // It may seem silly to separate joined_table from table_ref, but there is
 13577  // method in SQL's madness: if you don't do it this way you get reduce- reduce
 13578  // conflicts, because it's not clear to the parser generator whether to expect
 13579  // alias_clause after ')' or not. For the same reason we must treat 'JOIN' and
 13580  // 'join_type JOIN' separately, rather than allowing join_type to expand to
 13581  // empty; if we try it, the parser generator can't figure out when to reduce an
 13582  // empty join_type right after table_ref.
 13583  //
 13584  // Note that a CROSS JOIN is the same as an unqualified INNER JOIN, and an
 13585  // INNER JOIN/ON has the same shape but a qualification expression to limit
 13586  // membership. A NATURAL JOIN implicitly matches column names between tables
 13587  // and the shape is determined by which columns are in common. We'll collect
 13588  // columns during the later transformations.
 13589  
 13590  joined_table:
 13591    '(' joined_table ')'
 13592    {
 13593      $$.val = &tree.ParenTableExpr{Expr: $2.tblExpr()}
 13594    }
 13595  | table_ref CROSS opt_join_hint JOIN table_ref
 13596    {
 13597      $$.val = &tree.JoinTableExpr{JoinType: tree.AstCross, Left: $1.tblExpr(), Right: $5.tblExpr(), Hint: $3}
 13598    }
 13599  | table_ref join_type opt_join_hint JOIN table_ref join_qual
 13600    {
 13601      $$.val = &tree.JoinTableExpr{JoinType: $2, Left: $1.tblExpr(), Right: $5.tblExpr(), Cond: $6.joinCond(), Hint: $3}
 13602    }
 13603  | table_ref JOIN table_ref join_qual
 13604    {
 13605      $$.val = &tree.JoinTableExpr{Left: $1.tblExpr(), Right: $3.tblExpr(), Cond: $4.joinCond()}
 13606    }
 13607  | table_ref NATURAL join_type opt_join_hint JOIN table_ref
 13608    {
 13609      $$.val = &tree.JoinTableExpr{JoinType: $3, Left: $1.tblExpr(), Right: $6.tblExpr(), Cond: tree.NaturalJoinCond{}, Hint: $4}
 13610    }
 13611  | table_ref NATURAL JOIN table_ref
 13612    {
 13613      $$.val = &tree.JoinTableExpr{Left: $1.tblExpr(), Right: $4.tblExpr(), Cond: tree.NaturalJoinCond{}}
 13614    }
 13615  
 13616  alias_clause:
 13617    AS table_alias_name opt_col_def_list_no_types
 13618    {
 13619      $$.val = tree.AliasClause{Alias: tree.Name($2), Cols: $3.colDefList()}
 13620    }
 13621  | table_alias_name opt_col_def_list_no_types
 13622    {
 13623      $$.val = tree.AliasClause{Alias: tree.Name($1), Cols: $2.colDefList()}
 13624    }
 13625  
 13626  opt_alias_clause:
 13627    alias_clause
 13628  | /* EMPTY */
 13629    {
 13630      $$.val = tree.AliasClause{}
 13631    }
 13632  
 13633  func_alias_clause:
 13634    AS table_alias_name opt_col_def_list
 13635    {
 13636      $$.val = tree.AliasClause{Alias: tree.Name($2), Cols: $3.colDefList()}
 13637    }
 13638  | table_alias_name opt_col_def_list
 13639    {
 13640      $$.val = tree.AliasClause{Alias: tree.Name($1), Cols: $2.colDefList()}
 13641    }
 13642  
 13643  opt_func_alias_clause:
 13644    func_alias_clause
 13645  | /* EMPTY */
 13646    {
 13647      $$.val = tree.AliasClause{}
 13648    }
 13649  
 13650  as_of_clause:
 13651    AS_LA OF SYSTEM TIME a_expr
 13652    {
 13653      $$.val = tree.AsOfClause{Expr: $5.expr()}
 13654    }
 13655  
 13656  opt_as_of_clause:
 13657    as_of_clause
 13658  | /* EMPTY */
 13659    {
 13660      $$.val = tree.AsOfClause{}
 13661    }
 13662  
 13663  join_type:
 13664    FULL join_outer
 13665    {
 13666      $$ = tree.AstFull
 13667    }
 13668  | LEFT join_outer
 13669    {
 13670      $$ = tree.AstLeft
 13671    }
 13672  | RIGHT join_outer
 13673    {
 13674      $$ = tree.AstRight
 13675    }
 13676  | INNER
 13677    {
 13678      $$ = tree.AstInner
 13679    }
 13680  
 13681  // OUTER is just noise...
 13682  join_outer:
 13683    OUTER {}
 13684  | /* EMPTY */ {}
 13685  
 13686  // Join hint specifies that the join in the query should use a
 13687  // specific method.
 13688  
 13689  // The semantics are as follows:
 13690  //  - HASH forces a hash join; in other words, it disables merge and lookup
 13691  //    join. A hash join is always possible; even if there are no equality
 13692  //    columns - we consider cartesian join a degenerate case of the hash join
 13693  //    (one bucket).
 13694  //  - MERGE forces a merge join, even if it requires resorting both sides of
 13695  //    the join.
 13696  //  - LOOKUP forces a lookup join into the right side; the right side must be
 13697  //    a table with a suitable index. `LOOKUP` can only be used with INNER and
 13698  //    LEFT joins (though this is not enforced by the syntax).
 13699  //  - INVERTED forces an inverted join into the right side; the right side must
 13700  //    be a table with a suitable inverted index. `INVERTED` can only be used
 13701  //    with INNER and LEFT joins (though this is not enforced by the syntax).
 13702  //  - If it is not possible to use the algorithm in the hint, an error is
 13703  //    returned.
 13704  //  - When a join hint is specified, the two tables will not be reordered
 13705  //    by the optimizer.
 13706  opt_join_hint:
 13707    HASH
 13708    {
 13709      $$ = tree.AstHash
 13710    }
 13711  | MERGE
 13712    {
 13713      $$ = tree.AstMerge
 13714    }
 13715  | LOOKUP
 13716    {
 13717      $$ = tree.AstLookup
 13718    }
 13719  | INVERTED
 13720    {
 13721      $$ = tree.AstInverted
 13722    }
 13723  | /* EMPTY */
 13724    {
 13725      $$ = ""
 13726    }
 13727  
 13728  // JOIN qualification clauses
 13729  // Possibilities are:
 13730  //      USING ( column list ) allows only unqualified column names,
 13731  //          which must match between tables.
 13732  //      ON expr allows more general qualifications.
 13733  //
 13734  // We return USING as a List node, while an ON-expr will not be a List.
 13735  join_qual:
 13736    USING '(' name_list ')'
 13737    {
 13738      $$.val = &tree.UsingJoinCond{Cols: $3.nameList()}
 13739    }
 13740  | ON a_expr
 13741    {
 13742      $$.val = &tree.OnJoinCond{Expr: $2.expr()}
 13743    }
 13744  
 13745  relation_expr:
 13746    table_name              { $$.val = $1.unresolvedObjectName() }
 13747  | table_name '*'          { $$.val = $1.unresolvedObjectName() }
 13748  | ONLY table_name         { $$.val = $2.unresolvedObjectName() }
 13749  | ONLY '(' table_name ')' { $$.val = $3.unresolvedObjectName() }
 13750  
 13751  relation_expr_list:
 13752    relation_expr
 13753    {
 13754      name := $1.unresolvedObjectName().ToTableName()
 13755      $$.val = tree.TableNames{name}
 13756    }
 13757  | relation_expr_list ',' relation_expr
 13758    {
 13759      name := $3.unresolvedObjectName().ToTableName()
 13760      $$.val = append($1.tableNames(), name)
 13761    }
 13762  
 13763  // UNLISTEN
 13764  unlisten_stmt:
 13765     UNLISTEN type_name
 13766      {
 13767          $$.val = &tree.Unlisten{ ChannelName: $2.unresolvedObjectName(), Star: false}
 13768      }
 13769  |  UNLISTEN '*'
 13770        {
 13771            $$.val = &tree.Unlisten{ ChannelName:nil, Star: true}
 13772        }
 13773  
 13774  
 13775  // Given "UPDATE foo set set ...", we have to decide without looking any
 13776  // further ahead whether the first "set" is an alias or the UPDATE's SET
 13777  // keyword. Since "set" is allowed as a column name both interpretations are
 13778  // feasible. We resolve the shift/reduce conflict by giving the first
 13779  // table_expr_opt_alias_idx production a higher precedence than the SET token
 13780  // has, causing the parser to prefer to reduce, in effect assuming that the SET
 13781  // is not an alias.
 13782  table_expr_opt_alias_idx:
 13783    table_name_opt_idx %prec UMINUS
 13784    {
 13785       $$.val = $1.tblExpr()
 13786    }
 13787  | table_name_opt_idx table_alias_name
 13788    {
 13789       alias := $1.tblExpr().(*tree.AliasedTableExpr)
 13790       alias.As = tree.AliasClause{Alias: tree.Name($2)}
 13791       $$.val = alias
 13792    }
 13793  | table_name_opt_idx AS table_alias_name
 13794    {
 13795       alias := $1.tblExpr().(*tree.AliasedTableExpr)
 13796       alias.As = tree.AliasClause{Alias: tree.Name($3)}
 13797       $$.val = alias
 13798    }
 13799  | numeric_table_ref opt_index_flags
 13800    {
 13801      /* SKIP DOC */
 13802      $$.val = &tree.AliasedTableExpr{
 13803        Expr: $1.tblExpr(),
 13804        IndexFlags: $2.indexFlags(),
 13805      }
 13806    }
 13807  
 13808  table_name_opt_idx:
 13809    opt_only table_name opt_index_flags opt_descendant
 13810    {
 13811      name := $2.unresolvedObjectName().ToTableName()
 13812      $$.val = &tree.AliasedTableExpr{
 13813        Expr: &name,
 13814        IndexFlags: $3.indexFlags(),
 13815      }
 13816    }
 13817  
 13818  opt_only:
 13819  	ONLY
 13820    {
 13821      $$.val = true
 13822    }
 13823  | /* EMPTY */
 13824    {
 13825      $$.val = false
 13826    }
 13827  
 13828  opt_descendant:
 13829  	'*'
 13830    {
 13831      $$.val = true
 13832    }
 13833  | /* EMPTY */
 13834    {
 13835      $$.val = false
 13836    }
 13837  
 13838  where_clause:
 13839    WHERE a_expr
 13840    {
 13841      $$.val = $2.expr()
 13842    }
 13843  
 13844  opt_where_clause:
 13845    where_clause
 13846  | /* EMPTY */
 13847    {
 13848      $$.val = tree.Expr(nil)
 13849    }
 13850  
 13851  // Type syntax
 13852  //   SQL introduces a large amount of type-specific syntax.
 13853  //   Define individual clauses to handle these cases, and use
 13854  //   the generic case to handle regular type-extensible Postgres syntax.
 13855  //   - thomas 1997-10-10
 13856  
 13857  typename:
 13858    simple_typename opt_array_bounds
 13859    {
 13860      if bounds := $2.int32s(); bounds != nil {
 13861        var err error
 13862        $$.val, err = arrayOf($1.typeReference(), bounds)
 13863        if err != nil {
 13864          return setErr(sqllex, err)
 13865        }
 13866      } else {
 13867        $$.val = $1.typeReference()
 13868      }
 13869    }
 13870    // SQL standard syntax, currently only one-dimensional
 13871    // Undocumented but support for potential Postgres compat
 13872  | simple_typename ARRAY '[' ICONST ']' {
 13873      /* SKIP DOC */
 13874      var err error
 13875      $$.val, err = arrayOf($1.typeReference(), nil)
 13876      if err != nil {
 13877        return setErr(sqllex, err)
 13878      }
 13879    }
 13880  | simple_typename ARRAY '[' ICONST ']' '[' error { return unimplementedWithIssue(sqllex, 32552) }
 13881  | simple_typename ARRAY {
 13882      var err error
 13883      $$.val, err = arrayOf($1.typeReference(), nil)
 13884      if err != nil {
 13885        return setErr(sqllex, err)
 13886      }
 13887    }
 13888  
 13889  cast_target:
 13890    typename
 13891    {
 13892      $$.val = $1.typeReference()
 13893    }
 13894  
 13895  opt_array_bounds:
 13896    // TODO(justin): reintroduce multiple array bounds
 13897    // opt_array_bounds '[' ']' { $$.val = append($1.int32s(), -1) }
 13898    '[' ']' { $$.val = []int32{-1} }
 13899  | '[' ']' '[' error { return unimplementedWithIssue(sqllex, 32552) }
 13900  | '[' ICONST ']'
 13901    {
 13902      /* SKIP DOC */
 13903      bound, err := $2.numVal().AsInt32()
 13904      if err != nil {
 13905        return setErr(sqllex, err)
 13906      }
 13907      $$.val = []int32{bound}
 13908    }
 13909  | '[' ICONST ']' '[' error { return unimplementedWithIssue(sqllex, 32552) }
 13910  | /* EMPTY */ { $$.val = []int32(nil) }
 13911  
 13912  // general_type_name is a variant of type_or_function_name but does not
 13913  // include some extra keywords (like FAMILY) which cause ambiguity with
 13914  // parsing of typenames in certain contexts.
 13915  general_type_name:
 13916    type_function_name_no_crdb_extra
 13917  
 13918  // complex_type_name mirrors the rule for complex_db_object_name, but uses
 13919  // general_type_name rather than db_object_name_component to avoid conflicts.
 13920  complex_type_name:
 13921    general_type_name '.' unrestricted_name
 13922    {
 13923      aIdx := sqllex.(*lexer).NewAnnotation()
 13924      res, err := tree.NewUnresolvedObjectName(2, [3]string{$3, $1}, aIdx)
 13925      if err != nil { return setErr(sqllex, err) }
 13926      $$.val = res
 13927    }
 13928  | general_type_name '.' unrestricted_name '.' unrestricted_name
 13929    {
 13930      aIdx := sqllex.(*lexer).NewAnnotation()
 13931      res, err := tree.NewUnresolvedObjectName(3, [3]string{$5, $3, $1}, aIdx)
 13932      if err != nil { return setErr(sqllex, err) }
 13933      $$.val = res
 13934    }
 13935  
 13936  simple_typename:
 13937    general_type_name
 13938    {
 13939      /* FORCE DOC */
 13940      // See https://www.postgresql.org/docs/9.1/static/datatype-character.html
 13941      // Postgres supports a special character type named "char" (with the quotes)
 13942      // that is a single-character column type. It's used by system tables.
 13943      // Eventually this clause will be used to parse user-defined types as well,
 13944      // since their names can be quoted.
 13945      if $1 == "char" {
 13946        $$.val = types.QChar
 13947      } else if $1 == "serial" {
 13948          switch sqllex.(*lexer).nakedIntType.Width() {
 13949          case 32:
 13950            $$.val = &types.Serial4Type
 13951          default:
 13952            $$.val = &types.Serial8Type
 13953          }
 13954      } else {
 13955        // Check the the type is one of our "non-keyword" type names.
 13956        // Otherwise, package it up as a type reference for later.
 13957        var ok bool
 13958        var err error
 13959        var unimp int
 13960        $$.val, ok, unimp = types.TypeForNonKeywordTypeName($1)
 13961        if !ok {
 13962          switch unimp {
 13963            case 0:
 13964              // In this case, we don't think this type is one of our
 13965              // known unsupported types, so make a type reference for it.
 13966              aIdx := sqllex.(*lexer).NewAnnotation()
 13967              $$.val, err = tree.NewUnresolvedObjectName(1, [3]string{$1}, aIdx)
 13968              if err != nil { return setErr(sqllex, err) }
 13969            case -1:
 13970              return unimplemented(sqllex, "type name " + $1)
 13971            default:
 13972              return unimplementedWithIssueDetail(sqllex, unimp, $1)
 13973          }
 13974        }
 13975      }
 13976    }
 13977  | '@' iconst32
 13978    {
 13979      id := $2.int32()
 13980      $$.val = &tree.OIDTypeReference{OID: oid.Oid(id)}
 13981    }
 13982  | complex_type_name
 13983    {
 13984      $$.val = $1.typeReference()
 13985    }
 13986  | const_typename
 13987  | interval_type
 13988  | POINT error { return unimplementedWithIssueDetail(sqllex, 21286, "point") } // needed or else it generates a syntax error.
 13989  | POLYGON error { return unimplementedWithIssueDetail(sqllex, 21286, "polygon") } // needed or else it generates a syntax error.
 13990  
 13991  geo_shape_type:
 13992    POINT { $$.val = geopb.ShapeType_Point }
 13993  | POINTM { $$.val = geopb.ShapeType_PointM }
 13994  | POINTZ { $$.val = geopb.ShapeType_PointZ }
 13995  | POINTZM { $$.val = geopb.ShapeType_PointZM }
 13996  | LINESTRING { $$.val = geopb.ShapeType_LineString }
 13997  | LINESTRINGM { $$.val = geopb.ShapeType_LineStringM }
 13998  | LINESTRINGZ { $$.val = geopb.ShapeType_LineStringZ }
 13999  | LINESTRINGZM { $$.val = geopb.ShapeType_LineStringZM }
 14000  | POLYGON { $$.val = geopb.ShapeType_Polygon }
 14001  | POLYGONM { $$.val = geopb.ShapeType_PolygonM }
 14002  | POLYGONZ { $$.val = geopb.ShapeType_PolygonZ }
 14003  | POLYGONZM { $$.val = geopb.ShapeType_PolygonZM }
 14004  | MULTIPOINT { $$.val = geopb.ShapeType_MultiPoint }
 14005  | MULTIPOINTM { $$.val = geopb.ShapeType_MultiPointM }
 14006  | MULTIPOINTZ { $$.val = geopb.ShapeType_MultiPointZ }
 14007  | MULTIPOINTZM { $$.val = geopb.ShapeType_MultiPointZM }
 14008  | MULTILINESTRING { $$.val = geopb.ShapeType_MultiLineString }
 14009  | MULTILINESTRINGM { $$.val = geopb.ShapeType_MultiLineStringM }
 14010  | MULTILINESTRINGZ { $$.val = geopb.ShapeType_MultiLineStringZ }
 14011  | MULTILINESTRINGZM { $$.val = geopb.ShapeType_MultiLineStringZM }
 14012  | MULTIPOLYGON { $$.val = geopb.ShapeType_MultiPolygon }
 14013  | MULTIPOLYGONM { $$.val = geopb.ShapeType_MultiPolygonM }
 14014  | MULTIPOLYGONZ { $$.val = geopb.ShapeType_MultiPolygonZ }
 14015  | MULTIPOLYGONZM { $$.val = geopb.ShapeType_MultiPolygonZM }
 14016  | GEOMETRYCOLLECTION { $$.val = geopb.ShapeType_GeometryCollection }
 14017  | GEOMETRYCOLLECTIONM { $$.val = geopb.ShapeType_GeometryCollectionM }
 14018  | GEOMETRYCOLLECTIONZ { $$.val = geopb.ShapeType_GeometryCollectionZ }
 14019  | GEOMETRYCOLLECTIONZM { $$.val = geopb.ShapeType_GeometryCollectionZM }
 14020  | GEOMETRY { $$.val = geopb.ShapeType_Geometry }
 14021  | GEOMETRYM { $$.val = geopb.ShapeType_GeometryM }
 14022  | GEOMETRYZ { $$.val = geopb.ShapeType_GeometryZ }
 14023  | GEOMETRYZM { $$.val = geopb.ShapeType_GeometryZM }
 14024  
 14025  const_geo:
 14026    GEOGRAPHY { $$.val = types.Geography }
 14027  | GEOMETRY  { $$.val = types.Geometry }
 14028  | BOX2D     { $$.val = types.Box2D }
 14029  | GEOMETRY '(' geo_shape_type ')'
 14030    {
 14031      $$.val = types.MakeGeometry($3.geoShapeType(), 0)
 14032    }
 14033  | GEOGRAPHY '(' geo_shape_type ')'
 14034    {
 14035      $$.val = types.MakeGeography($3.geoShapeType(), 0)
 14036    }
 14037  | GEOMETRY '(' geo_shape_type ',' signed_iconst ')'
 14038    {
 14039      val, err := $5.numVal().AsInt32()
 14040      if err != nil {
 14041        return setErr(sqllex, err)
 14042      }
 14043      $$.val = types.MakeGeometry($3.geoShapeType(), geopb.SRID(val))
 14044    }
 14045  | GEOGRAPHY '(' geo_shape_type ',' signed_iconst ')'
 14046    {
 14047      val, err := $5.numVal().AsInt32()
 14048      if err != nil {
 14049        return setErr(sqllex, err)
 14050      }
 14051      $$.val = types.MakeGeography($3.geoShapeType(), geopb.SRID(val))
 14052    }
 14053  
 14054  // We have a separate const_typename to allow defaulting fixed-length types such
 14055  // as CHAR() and BIT() to an unspecified length. SQL9x requires that these
 14056  // default to a length of one, but this makes no sense for constructs like CHAR
 14057  // 'hi' and BIT '0101', where there is an obvious better choice to make. This
 14058  // rule *also* supports length-specified types like BIT(1), CHAR(3), etc. Note
 14059  // that interval_type is not included here since it must be pushed up higher in
 14060  // the rules to accommodate the postfix options (e.g. INTERVAL '1' YEAR).
 14061  // Likewise, we have to handle the generic-type-name case in a_expr_const to
 14062  // avoid premature reduce/reduce conflicts against function names.
 14063  const_typename:
 14064    numeric
 14065  | bit_without_length
 14066  | bit_with_length
 14067  | character_without_length
 14068  | character_with_length
 14069  | const_datetime
 14070  | const_geo
 14071  
 14072  opt_numeric_modifiers:
 14073    '(' iconst32 ')'
 14074    {
 14075      dec, err := newDecimal($2.int32(), 0)
 14076      if err != nil {
 14077        return setErr(sqllex, err)
 14078      }
 14079      $$.val = dec
 14080    }
 14081  | '(' iconst32 ',' iconst32 ')'
 14082    {
 14083      dec, err := newDecimal($2.int32(), $4.int32())
 14084      if err != nil {
 14085        return setErr(sqllex, err)
 14086      }
 14087      $$.val = dec
 14088    }
 14089  | /* EMPTY */
 14090    {
 14091      $$.val = nil
 14092    }
 14093  
 14094  // SQL numeric data types
 14095  numeric:
 14096    INT
 14097    {
 14098      $$.val = sqllex.(*lexer).nakedIntType
 14099    }
 14100  | INTEGER
 14101    {
 14102      $$.val = sqllex.(*lexer).nakedIntType
 14103    }
 14104  | SMALLINT
 14105    {
 14106      $$.val = types.Int2
 14107    }
 14108  | BIGINT
 14109    {
 14110      $$.val = types.Int
 14111    }
 14112  | REAL
 14113    {
 14114      $$.val = types.Float4
 14115    }
 14116  | FLOAT opt_float
 14117    {
 14118      $$.val = $2.colType()
 14119    }
 14120  | DOUBLE PRECISION
 14121    {
 14122      $$.val = types.Float
 14123    }
 14124  | DECIMAL opt_numeric_modifiers
 14125    {
 14126      typ := $2.colType()
 14127      if typ == nil {
 14128        typ = types.Decimal
 14129      }
 14130      $$.val = typ
 14131    }
 14132  | DEC opt_numeric_modifiers
 14133    {
 14134      typ := $2.colType()
 14135      if typ == nil {
 14136        typ = types.Decimal
 14137      }
 14138      $$.val = typ
 14139    }
 14140  | NUMERIC opt_numeric_modifiers
 14141    {
 14142      typ := $2.colType()
 14143      if typ == nil {
 14144        typ = types.Decimal
 14145      }
 14146      $$.val = typ
 14147    }
 14148  | BOOLEAN
 14149    {
 14150      $$.val = types.Bool
 14151    }
 14152  
 14153  opt_float:
 14154    '(' ICONST ')'
 14155    {
 14156      nv := $2.numVal()
 14157      prec, err := nv.AsInt64()
 14158      if err != nil {
 14159        return setErr(sqllex, err)
 14160      }
 14161      typ, err := newFloat(prec)
 14162      if err != nil {
 14163        return setErr(sqllex, err)
 14164      }
 14165      $$.val = typ
 14166    }
 14167  | /* EMPTY */
 14168    {
 14169      $$.val = types.Float
 14170    }
 14171  
 14172  bit_with_length:
 14173    BIT opt_varying '(' iconst32 ')'
 14174    {
 14175      bit, err := newBitType($4.int32(), $2.bool())
 14176      if err != nil { return setErr(sqllex, err) }
 14177      $$.val = bit
 14178    }
 14179  | VARBIT '(' iconst32 ')'
 14180    {
 14181      bit, err := newBitType($3.int32(), true)
 14182      if err != nil { return setErr(sqllex, err) }
 14183      $$.val = bit
 14184    }
 14185  
 14186  bit_without_length:
 14187    BIT
 14188    {
 14189      $$.val = types.MakeBit(1)
 14190    }
 14191  | BIT VARYING
 14192    {
 14193      $$.val = types.VarBit
 14194    }
 14195  | VARBIT
 14196    {
 14197      $$.val = types.VarBit
 14198    }
 14199  
 14200  character_with_length:
 14201    character_base '(' iconst32 ')'
 14202    {
 14203      colTyp := *$1.colType()
 14204      n := $3.int32()
 14205      if n == 0 {
 14206        sqllex.Error(fmt.Sprintf("length for type %s must be at least 1", colTyp.SQLString()))
 14207        return 1
 14208      }
 14209      $$.val = types.MakeScalar(types.StringFamily, colTyp.Oid(), colTyp.Precision(), n, colTyp.Locale())
 14210    }
 14211  
 14212  character_without_length:
 14213    character_base
 14214    {
 14215      $$.val = $1.colType()
 14216    }
 14217  
 14218  character_base:
 14219    char_aliases
 14220    {
 14221      $$.val = types.MakeChar(1)
 14222    }
 14223  | char_aliases VARYING
 14224    {
 14225      $$.val = types.VarChar
 14226    }
 14227  | VARCHAR
 14228    {
 14229      $$.val = types.VarChar
 14230    }
 14231  | STRING
 14232    {
 14233      $$.val = types.String
 14234    }
 14235  
 14236  char_aliases:
 14237    CHAR
 14238  | CHARACTER
 14239  
 14240  opt_varying:
 14241    VARYING     { $$.val = true }
 14242  | /* EMPTY */ { $$.val = false }
 14243  
 14244  // SQL date/time types
 14245  const_datetime:
 14246    DATE
 14247    {
 14248      $$.val = types.Date
 14249    }
 14250  | TIME opt_timezone
 14251    {
 14252      if $2.bool() {
 14253        $$.val = types.TimeTZ
 14254      } else {
 14255        $$.val = types.Time
 14256      }
 14257    }
 14258  | TIME '(' iconst32 ')' opt_timezone
 14259    {
 14260      prec := $3.int32()
 14261      if prec < 0 || prec > 6 {
 14262        sqllex.Error(fmt.Sprintf("precision %d out of range", prec))
 14263        return 1
 14264      }
 14265      if $5.bool() {
 14266        $$.val = types.MakeTimeTZ(prec)
 14267      } else {
 14268        $$.val = types.MakeTime(prec)
 14269      }
 14270    }
 14271  | TIMETZ                             { $$.val = types.TimeTZ }
 14272  | TIMETZ '(' iconst32 ')'
 14273    {
 14274      prec := $3.int32()
 14275      if prec < 0 || prec > 6 {
 14276        sqllex.Error(fmt.Sprintf("precision %d out of range", prec))
 14277        return 1
 14278      }
 14279      $$.val = types.MakeTimeTZ(prec)
 14280    }
 14281  | TIMESTAMP opt_timezone
 14282    {
 14283      if $2.bool() {
 14284        $$.val = types.TimestampTZ
 14285      } else {
 14286        $$.val = types.Timestamp
 14287      }
 14288    }
 14289  | TIMESTAMP '(' iconst32 ')' opt_timezone
 14290    {
 14291      prec := $3.int32()
 14292      if prec < 0 || prec > 6 {
 14293        sqllex.Error(fmt.Sprintf("precision %d out of range", prec))
 14294        return 1
 14295      }
 14296      if $5.bool() {
 14297        $$.val = types.MakeTimestampTZ(prec)
 14298      } else {
 14299        $$.val = types.MakeTimestamp(prec)
 14300      }
 14301    }
 14302  | TIMESTAMPTZ
 14303    {
 14304      $$.val = types.TimestampTZ
 14305    }
 14306  | TIMESTAMPTZ '(' iconst32 ')'
 14307    {
 14308      prec := $3.int32()
 14309      if prec < 0 || prec > 6 {
 14310        sqllex.Error(fmt.Sprintf("precision %d out of range", prec))
 14311        return 1
 14312      }
 14313      $$.val = types.MakeTimestampTZ(prec)
 14314    }
 14315  
 14316  opt_timezone:
 14317    WITH_LA TIME ZONE { $$.val = true; }
 14318  | WITHOUT TIME ZONE { $$.val = false; }
 14319  | /*EMPTY*/         { $$.val = false; }
 14320  
 14321  interval_type:
 14322    INTERVAL
 14323    {
 14324      $$.val = types.Interval
 14325    }
 14326  | INTERVAL interval_qualifier
 14327    {
 14328      $$.val = types.MakeInterval($2.intervalTypeMetadata())
 14329    }
 14330  | INTERVAL '(' iconst32 ')'
 14331    {
 14332      prec := $3.int32()
 14333      if prec < 0 || prec > 6 {
 14334        sqllex.Error(fmt.Sprintf("precision %d out of range", prec))
 14335        return 1
 14336      }
 14337      $$.val = types.MakeInterval(types.IntervalTypeMetadata{Precision: prec, PrecisionIsSet: true})
 14338    }
 14339  
 14340  interval_qualifier:
 14341    YEAR %prec INTERVAL_SIMPLE
 14342    {
 14343      $$.val = types.IntervalTypeMetadata{
 14344        DurationField: types.IntervalDurationField{
 14345          DurationType: types.IntervalDurationType_YEAR,
 14346        },
 14347      }
 14348    }
 14349  | MONTH %prec INTERVAL_SIMPLE
 14350    {
 14351      $$.val = types.IntervalTypeMetadata{
 14352        DurationField: types.IntervalDurationField{
 14353          DurationType: types.IntervalDurationType_MONTH,
 14354        },
 14355      }
 14356    }
 14357  | DAY %prec INTERVAL_SIMPLE
 14358    {
 14359      $$.val = types.IntervalTypeMetadata{
 14360        DurationField: types.IntervalDurationField{
 14361          DurationType: types.IntervalDurationType_DAY,
 14362        },
 14363      }
 14364    }
 14365  | HOUR %prec INTERVAL_SIMPLE
 14366    {
 14367      $$.val = types.IntervalTypeMetadata{
 14368        DurationField: types.IntervalDurationField{
 14369          DurationType: types.IntervalDurationType_HOUR,
 14370        },
 14371      }
 14372    }
 14373  | MINUTE %prec INTERVAL_SIMPLE
 14374    {
 14375      $$.val = types.IntervalTypeMetadata{
 14376        DurationField: types.IntervalDurationField{
 14377          DurationType: types.IntervalDurationType_MINUTE,
 14378        },
 14379      }
 14380    }
 14381  | interval_second
 14382    {
 14383      $$.val = $1.intervalTypeMetadata()
 14384    }
 14385  // Like Postgres, we ignore the left duration field. See explanation:
 14386  // https://www.postgresql.org/message-id/20110510040219.GD5617%40tornado.gateway.2wire.net
 14387  | YEAR TO MONTH %prec TO
 14388    {
 14389      $$.val = types.IntervalTypeMetadata{
 14390        DurationField: types.IntervalDurationField{
 14391          FromDurationType: types.IntervalDurationType_YEAR,
 14392          DurationType: types.IntervalDurationType_MONTH,
 14393        },
 14394      }
 14395    }
 14396  | DAY TO HOUR %prec TO
 14397    {
 14398      $$.val = types.IntervalTypeMetadata{
 14399        DurationField: types.IntervalDurationField{
 14400          FromDurationType: types.IntervalDurationType_DAY,
 14401          DurationType: types.IntervalDurationType_HOUR,
 14402        },
 14403      }
 14404    }
 14405  | DAY TO MINUTE %prec TO
 14406    {
 14407      $$.val = types.IntervalTypeMetadata{
 14408        DurationField: types.IntervalDurationField{
 14409          FromDurationType: types.IntervalDurationType_DAY,
 14410          DurationType: types.IntervalDurationType_MINUTE,
 14411        },
 14412      }
 14413    }
 14414  | DAY TO interval_second %prec TO
 14415    {
 14416      ret := $3.intervalTypeMetadata()
 14417      ret.DurationField.FromDurationType = types.IntervalDurationType_DAY
 14418      $$.val = ret
 14419    }
 14420  | HOUR TO MINUTE %prec TO
 14421    {
 14422      $$.val = types.IntervalTypeMetadata{
 14423        DurationField: types.IntervalDurationField{
 14424          FromDurationType: types.IntervalDurationType_HOUR,
 14425          DurationType: types.IntervalDurationType_MINUTE,
 14426        },
 14427      }
 14428    }
 14429  | HOUR TO interval_second %prec TO
 14430    {
 14431      ret := $3.intervalTypeMetadata()
 14432      ret.DurationField.FromDurationType = types.IntervalDurationType_HOUR
 14433      $$.val = ret
 14434    }
 14435  | MINUTE TO interval_second %prec TO
 14436    {
 14437      $$.val = $3.intervalTypeMetadata()
 14438      ret := $3.intervalTypeMetadata()
 14439      ret.DurationField.FromDurationType = types.IntervalDurationType_MINUTE
 14440      $$.val = ret
 14441    }
 14442  
 14443  opt_interval_qualifier:
 14444    interval_qualifier
 14445  | /* EMPTY */
 14446    {
 14447      $$.val = nil
 14448    }
 14449  
 14450  interval_second:
 14451    SECOND
 14452    {
 14453      $$.val = types.IntervalTypeMetadata{
 14454        DurationField: types.IntervalDurationField{
 14455          DurationType: types.IntervalDurationType_SECOND,
 14456        },
 14457      }
 14458    }
 14459  | SECOND '(' iconst32 ')'
 14460    {
 14461      prec := $3.int32()
 14462      if prec < 0 || prec > 6 {
 14463        sqllex.Error(fmt.Sprintf("precision %d out of range", prec))
 14464        return 1
 14465      }
 14466      $$.val = types.IntervalTypeMetadata{
 14467        DurationField: types.IntervalDurationField{
 14468          DurationType: types.IntervalDurationType_SECOND,
 14469        },
 14470        PrecisionIsSet: true,
 14471        Precision: prec,
 14472      }
 14473    }
 14474  
 14475  // General expressions. This is the heart of the expression syntax.
 14476  //
 14477  // We have two expression types: a_expr is the unrestricted kind, and b_expr is
 14478  // a subset that must be used in some places to avoid shift/reduce conflicts.
 14479  // For example, we can't do BETWEEN as "BETWEEN a_expr AND a_expr" because that
 14480  // use of AND conflicts with AND as a boolean operator. So, b_expr is used in
 14481  // BETWEEN and we remove boolean keywords from b_expr.
 14482  //
 14483  // Note that '(' a_expr ')' is a b_expr, so an unrestricted expression can
 14484  // always be used by surrounding it with parens.
 14485  //
 14486  // c_expr is all the productions that are common to a_expr and b_expr; it's
 14487  // factored out just to eliminate redundant coding.
 14488  //
 14489  // Be careful of productions involving more than one terminal token. By
 14490  // default, bison will assign such productions the precedence of their last
 14491  // terminal, but in nearly all cases you want it to be the precedence of the
 14492  // first terminal instead; otherwise you will not get the behavior you expect!
 14493  // So we use %prec annotations freely to set precedences.
 14494  a_expr:
 14495    c_expr
 14496  | a_expr TYPECAST cast_target
 14497    {
 14498      $$.val = &tree.CastExpr{Expr: $1.expr(), Type: $3.typeReference(), SyntaxMode: tree.CastShort}
 14499    }
 14500  | a_expr TYPEANNOTATE typename
 14501    {
 14502      $$.val = &tree.AnnotateTypeExpr{Expr: $1.expr(), Type: $3.typeReference(), SyntaxMode: tree.AnnotateShort}
 14503    }
 14504  | a_expr COLLATE collation_name
 14505    {
 14506      $$.val = &tree.CollateExpr{Expr: $1.expr(), Locale: $3}
 14507    }
 14508  | a_expr AT TIME ZONE a_expr %prec AT
 14509    {
 14510      $$.val = &tree.FuncExpr{Func: tree.WrapFunction("timezone"), Exprs: tree.Exprs{$5.expr(), $1.expr()}}
 14511    }
 14512    // These operators must be called out explicitly in order to make use of
 14513    // bison's automatic operator-precedence handling. All other operator names
 14514    // are handled by the generic productions using "OP", below; and all those
 14515    // operators will have the same precedence.
 14516    //
 14517    // If you add more explicitly-known operators, be sure to add them also to
 14518    // b_expr and to the all_op list below.
 14519  | '+' a_expr %prec UMINUS
 14520    {
 14521      // Unary plus is a no-op. Desugar immediately.
 14522      $$.val = $2.expr()
 14523    }
 14524  | '-' a_expr %prec UMINUS
 14525    {
 14526      $$.val = unaryNegation($2.expr())
 14527    }
 14528  | '~' a_expr %prec UMINUS
 14529    {
 14530      $$.val = &tree.UnaryExpr{Operator: tree.MakeUnaryOperator(tree.UnaryComplement), Expr: $2.expr()}
 14531    }
 14532  | SQRT a_expr
 14533    {
 14534      $$.val = &tree.UnaryExpr{Operator: tree.MakeUnaryOperator(tree.UnarySqrt), Expr: $2.expr()}
 14535    }
 14536  | CBRT a_expr
 14537    {
 14538      $$.val = &tree.UnaryExpr{Operator: tree.MakeUnaryOperator(tree.UnaryCbrt), Expr: $2.expr()}
 14539    }
 14540  | a_expr '+' a_expr
 14541    {
 14542      $$.val = &tree.BinaryExpr{Operator: treebin.MakeBinaryOperator(treebin.Plus), Left: $1.expr(), Right: $3.expr()}
 14543    }
 14544  | a_expr '-' a_expr
 14545    {
 14546      $$.val = &tree.BinaryExpr{Operator: treebin.MakeBinaryOperator(treebin.Minus), Left: $1.expr(), Right: $3.expr()}
 14547    }
 14548  | a_expr '*' a_expr
 14549    {
 14550      $$.val = &tree.BinaryExpr{Operator: treebin.MakeBinaryOperator(treebin.Mult), Left: $1.expr(), Right: $3.expr()}
 14551    }
 14552  | a_expr '/' a_expr
 14553    {
 14554      $$.val = &tree.BinaryExpr{Operator: treebin.MakeBinaryOperator(treebin.Div), Left: $1.expr(), Right: $3.expr()}
 14555    }
 14556  | a_expr FLOORDIV a_expr
 14557    {
 14558      $$.val = &tree.BinaryExpr{Operator: treebin.MakeBinaryOperator(treebin.FloorDiv), Left: $1.expr(), Right: $3.expr()}
 14559    }
 14560  | a_expr '%' a_expr
 14561    {
 14562      $$.val = &tree.BinaryExpr{Operator: treebin.MakeBinaryOperator(treebin.Mod), Left: $1.expr(), Right: $3.expr()}
 14563    }
 14564  | a_expr '^' a_expr
 14565    {
 14566      $$.val = &tree.BinaryExpr{Operator: treebin.MakeBinaryOperator(treebin.Pow), Left: $1.expr(), Right: $3.expr()}
 14567    }
 14568  | a_expr '#' a_expr
 14569    {
 14570      $$.val = &tree.BinaryExpr{Operator: treebin.MakeBinaryOperator(treebin.Bitxor), Left: $1.expr(), Right: $3.expr()}
 14571    }
 14572  | a_expr '&' a_expr
 14573    {
 14574      $$.val = &tree.BinaryExpr{Operator: treebin.MakeBinaryOperator(treebin.Bitand), Left: $1.expr(), Right: $3.expr()}
 14575    }
 14576  | a_expr '|' a_expr
 14577    {
 14578      $$.val = &tree.BinaryExpr{Operator: treebin.MakeBinaryOperator(treebin.Bitor), Left: $1.expr(), Right: $3.expr()}
 14579    }
 14580  | a_expr '<' a_expr
 14581    {
 14582      $$.val = &tree.ComparisonExpr{Operator: treecmp.MakeComparisonOperator(treecmp.LT), Left: $1.expr(), Right: $3.expr()}
 14583    }
 14584  | a_expr '>' a_expr
 14585    {
 14586      $$.val = &tree.ComparisonExpr{Operator: treecmp.MakeComparisonOperator(treecmp.GT), Left: $1.expr(), Right: $3.expr()}
 14587    }
 14588  | a_expr '?' a_expr
 14589    {
 14590      $$.val = &tree.ComparisonExpr{Operator: treecmp.MakeComparisonOperator(treecmp.JSONExists), Left: $1.expr(), Right: $3.expr()}
 14591    }
 14592  | a_expr JSON_SOME_EXISTS a_expr
 14593    {
 14594      $$.val = &tree.ComparisonExpr{Operator: treecmp.MakeComparisonOperator(treecmp.JSONSomeExists), Left: $1.expr(), Right: $3.expr()}
 14595    }
 14596  | a_expr JSON_ALL_EXISTS a_expr
 14597    {
 14598      $$.val = &tree.ComparisonExpr{Operator: treecmp.MakeComparisonOperator(treecmp.JSONAllExists), Left: $1.expr(), Right: $3.expr()}
 14599    }
 14600  | a_expr CONTAINS a_expr
 14601    {
 14602      $$.val = &tree.ComparisonExpr{Operator: treecmp.MakeComparisonOperator(treecmp.Contains), Left: $1.expr(), Right: $3.expr()}
 14603    }
 14604  | a_expr CONTAINED_BY a_expr
 14605    {
 14606      $$.val = &tree.ComparisonExpr{Operator: treecmp.MakeComparisonOperator(treecmp.ContainedBy), Left: $1.expr(), Right: $3.expr()}
 14607    }
 14608  | a_expr '=' a_expr
 14609    {
 14610      $$.val = &tree.ComparisonExpr{Operator: treecmp.MakeComparisonOperator(treecmp.EQ), Left: $1.expr(), Right: $3.expr()}
 14611    }
 14612  | a_expr CONCAT a_expr
 14613    {
 14614      $$.val = &tree.BinaryExpr{Operator: treebin.MakeBinaryOperator(treebin.Concat), Left: $1.expr(), Right: $3.expr()}
 14615    }
 14616  | a_expr LSHIFT a_expr
 14617    {
 14618      $$.val = &tree.BinaryExpr{Operator: treebin.MakeBinaryOperator(treebin.LShift), Left: $1.expr(), Right: $3.expr()}
 14619    }
 14620  | a_expr RSHIFT a_expr
 14621    {
 14622      $$.val = &tree.BinaryExpr{Operator: treebin.MakeBinaryOperator(treebin.RShift), Left: $1.expr(), Right: $3.expr()}
 14623    }
 14624  | a_expr FETCHVAL a_expr
 14625    {
 14626      $$.val = &tree.BinaryExpr{Operator: treebin.MakeBinaryOperator(treebin.JSONFetchVal), Left: $1.expr(), Right: $3.expr()}
 14627    }
 14628  | a_expr FETCHTEXT a_expr
 14629    {
 14630      $$.val = &tree.BinaryExpr{Operator: treebin.MakeBinaryOperator(treebin.JSONFetchText), Left: $1.expr(), Right: $3.expr()}
 14631    }
 14632  | a_expr FETCHVAL_PATH a_expr
 14633    {
 14634      $$.val = &tree.BinaryExpr{Operator: treebin.MakeBinaryOperator(treebin.JSONFetchValPath), Left: $1.expr(), Right: $3.expr()}
 14635    }
 14636  | a_expr FETCHTEXT_PATH a_expr
 14637    {
 14638      $$.val = &tree.BinaryExpr{Operator: treebin.MakeBinaryOperator(treebin.JSONFetchTextPath), Left: $1.expr(), Right: $3.expr()}
 14639    }
 14640  | a_expr REMOVE_PATH a_expr
 14641    {
 14642      $$.val = &tree.FuncExpr{Func: tree.WrapFunction("json_remove_path"), Exprs: tree.Exprs{$1.expr(), $3.expr()}}
 14643    }
 14644  | a_expr INET_CONTAINED_BY_OR_EQUALS a_expr
 14645    {
 14646      $$.val = &tree.FuncExpr{Func: tree.WrapFunction("inet_contained_by_or_equals"), Exprs: tree.Exprs{$1.expr(), $3.expr()}}
 14647    }
 14648  | a_expr AND_AND a_expr
 14649    {
 14650      $$.val = &tree.ComparisonExpr{Operator: treecmp.MakeComparisonOperator(treecmp.Overlaps), Left: $1.expr(), Right: $3.expr()}
 14651    }
 14652  | a_expr AT_AT a_expr
 14653    {
 14654      $$.val = &tree.ComparisonExpr{Operator: treecmp.MakeComparisonOperator(treecmp.TSMatches), Left: $1.expr(), Right: $3.expr()}
 14655    }
 14656  | a_expr INET_CONTAINS_OR_EQUALS a_expr
 14657    {
 14658      $$.val = &tree.FuncExpr{Func: tree.WrapFunction("inet_contains_or_equals"), Exprs: tree.Exprs{$1.expr(), $3.expr()}}
 14659    }
 14660  | a_expr LESS_EQUALS a_expr
 14661    {
 14662      $$.val = &tree.ComparisonExpr{Operator: treecmp.MakeComparisonOperator(treecmp.LE), Left: $1.expr(), Right: $3.expr()}
 14663    }
 14664  | a_expr GREATER_EQUALS a_expr
 14665    {
 14666      $$.val = &tree.ComparisonExpr{Operator: treecmp.MakeComparisonOperator(treecmp.GE), Left: $1.expr(), Right: $3.expr()}
 14667    }
 14668  | a_expr NOT_EQUALS a_expr
 14669    {
 14670      $$.val = &tree.ComparisonExpr{Operator: treecmp.MakeComparisonOperator(treecmp.NE), Left: $1.expr(), Right: $3.expr()}
 14671    }
 14672  | qual_op a_expr %prec CBRT
 14673    {
 14674      var retCode int
 14675      $$.val, retCode = processUnaryQualOp(sqllex, $1.op(), $2.expr())
 14676      if retCode != 0 {
 14677        return retCode
 14678      }
 14679    }
 14680  | a_expr qual_op a_expr %prec CBRT
 14681    {
 14682      {
 14683        var retCode int
 14684        $$.val, retCode = processBinaryQualOp(sqllex, $2.op(), $1.expr(), $3.expr())
 14685        if retCode != 0 {
 14686          return retCode
 14687        }
 14688      }
 14689    }
 14690  | a_expr AND a_expr
 14691    {
 14692      $$.val = &tree.AndExpr{Left: $1.expr(), Right: $3.expr()}
 14693    }
 14694  | a_expr OR a_expr
 14695    {
 14696      $$.val = &tree.OrExpr{Left: $1.expr(), Right: $3.expr()}
 14697    }
 14698  | NOT a_expr
 14699    {
 14700      $$.val = &tree.NotExpr{Expr: $2.expr()}
 14701    }
 14702  | NOT_LA a_expr %prec NOT
 14703    {
 14704      $$.val = &tree.NotExpr{Expr: $2.expr()}
 14705    }
 14706  | a_expr LIKE a_expr
 14707    {
 14708      $$.val = &tree.ComparisonExpr{Operator: treecmp.MakeComparisonOperator(treecmp.Like), Left: $1.expr(), Right: $3.expr()}
 14709    }
 14710  | a_expr LIKE a_expr ESCAPE a_expr %prec ESCAPE
 14711    {
 14712      $$.val = &tree.FuncExpr{Func: tree.WrapFunction("like_escape"), Exprs: tree.Exprs{$1.expr(), $3.expr(), $5.expr()}}
 14713    }
 14714  | a_expr NOT_LA LIKE a_expr %prec NOT_LA
 14715    {
 14716      $$.val = &tree.ComparisonExpr{Operator: treecmp.MakeComparisonOperator(treecmp.NotLike), Left: $1.expr(), Right: $4.expr()}
 14717    }
 14718  | a_expr NOT_LA LIKE a_expr ESCAPE a_expr %prec ESCAPE
 14719   {
 14720     $$.val = &tree.FuncExpr{Func: tree.WrapFunction("not_like_escape"), Exprs: tree.Exprs{$1.expr(), $4.expr(), $6.expr()}}
 14721   }
 14722  | a_expr ILIKE a_expr
 14723    {
 14724      $$.val = &tree.ComparisonExpr{Operator: treecmp.MakeComparisonOperator(treecmp.ILike), Left: $1.expr(), Right: $3.expr()}
 14725    }
 14726  | a_expr ILIKE a_expr ESCAPE a_expr %prec ESCAPE
 14727    {
 14728      $$.val = &tree.FuncExpr{Func: tree.WrapFunction("ilike_escape"), Exprs: tree.Exprs{$1.expr(), $3.expr(), $5.expr()}}
 14729    }
 14730  | a_expr NOT_LA ILIKE a_expr %prec NOT_LA
 14731    {
 14732      $$.val = &tree.ComparisonExpr{Operator: treecmp.MakeComparisonOperator(treecmp.NotILike), Left: $1.expr(), Right: $4.expr()}
 14733    }
 14734  | a_expr NOT_LA ILIKE a_expr ESCAPE a_expr %prec ESCAPE
 14735   {
 14736     $$.val = &tree.FuncExpr{Func: tree.WrapFunction("not_ilike_escape"), Exprs: tree.Exprs{$1.expr(), $4.expr(), $6.expr()}}
 14737   }
 14738  | a_expr SIMILAR TO a_expr %prec SIMILAR
 14739    {
 14740      $$.val = &tree.ComparisonExpr{Operator: treecmp.MakeComparisonOperator(treecmp.SimilarTo), Left: $1.expr(), Right: $4.expr()}
 14741    }
 14742  | a_expr SIMILAR TO a_expr ESCAPE a_expr %prec ESCAPE
 14743    {
 14744      $$.val = &tree.FuncExpr{Func: tree.WrapFunction("similar_to_escape"), Exprs: tree.Exprs{$1.expr(), $4.expr(), $6.expr()}}
 14745    }
 14746  | a_expr NOT_LA SIMILAR TO a_expr %prec NOT_LA
 14747    {
 14748      $$.val = &tree.ComparisonExpr{Operator: treecmp.MakeComparisonOperator(treecmp.NotSimilarTo), Left: $1.expr(), Right: $5.expr()}
 14749    }
 14750  | a_expr NOT_LA SIMILAR TO a_expr ESCAPE a_expr %prec ESCAPE
 14751    {
 14752      $$.val = &tree.FuncExpr{Func: tree.WrapFunction("not_similar_to_escape"), Exprs: tree.Exprs{$1.expr(), $5.expr(), $7.expr()}}
 14753    }
 14754  | a_expr '~' a_expr
 14755    {
 14756      $$.val = &tree.ComparisonExpr{Operator: treecmp.MakeComparisonOperator(treecmp.RegMatch), Left: $1.expr(), Right: $3.expr()}
 14757    }
 14758  | a_expr NOT_REGMATCH a_expr
 14759    {
 14760      $$.val = &tree.ComparisonExpr{Operator: treecmp.MakeComparisonOperator(treecmp.NotRegMatch), Left: $1.expr(), Right: $3.expr()}
 14761    }
 14762  | a_expr REGIMATCH a_expr
 14763    {
 14764      $$.val = &tree.ComparisonExpr{Operator: treecmp.MakeComparisonOperator(treecmp.RegIMatch), Left: $1.expr(), Right: $3.expr()}
 14765    }
 14766  | a_expr NOT_REGIMATCH a_expr
 14767    {
 14768      $$.val = &tree.ComparisonExpr{Operator: treecmp.MakeComparisonOperator(treecmp.NotRegIMatch), Left: $1.expr(), Right: $3.expr()}
 14769    }
 14770  | a_expr IS NAN %prec IS
 14771    {
 14772      $$.val = &tree.ComparisonExpr{
 14773        Operator: treecmp.MakeComparisonOperator(treecmp.EQ),
 14774        Left: $1.expr(),
 14775        Right: tree.NewNumVal(constant.MakeFloat64(math.NaN()), "NaN", false /*negative*/),
 14776      }
 14777    }
 14778  | a_expr IS NOT NAN %prec IS
 14779    {
 14780      $$.val = &tree.ComparisonExpr{
 14781        Operator: treecmp.MakeComparisonOperator(treecmp.NE),
 14782        Left: $1.expr(),
 14783        Right: tree.NewNumVal(constant.MakeFloat64(math.NaN()), "NaN", false /*negative*/),
 14784      }
 14785    }
 14786  | a_expr IS NULL %prec IS
 14787    {
 14788      $$.val = &tree.IsNullExpr{Expr: $1.expr()}
 14789    }
 14790  | a_expr ISNULL %prec IS
 14791    {
 14792      $$.val = &tree.IsNullExpr{Expr: $1.expr()}
 14793    }
 14794  | a_expr IS NOT NULL %prec IS
 14795    {
 14796      $$.val = &tree.IsNotNullExpr{Expr: $1.expr()}
 14797    }
 14798  | a_expr NOTNULL %prec IS
 14799    {
 14800      $$.val = &tree.IsNotNullExpr{Expr: $1.expr()}
 14801    }
 14802  | row OVERLAPS row
 14803    {
 14804     t1, t2 := $1.tuple(), $3.tuple()
 14805     if len(t1.Exprs) != 2 {
 14806       sqllex.Error("wrong number of parameters on left side of OVERLAPS expression")
 14807       return 1
 14808     }
 14809     if len(t2.Exprs) != 2 {
 14810       sqllex.Error("wrong number of parameters on right side of OVERLAPS expression")
 14811       return 1
 14812     }
 14813     $$.val = &tree.FuncExpr{Func: tree.WrapFunction("overlaps"), Exprs: tree.Exprs{t1.Exprs[0], t1.Exprs[1], t2.Exprs[0], t2.Exprs[1]}}
 14814    }
 14815  | a_expr IS TRUE %prec IS
 14816    {
 14817      $$.val = &tree.ComparisonExpr{Operator: treecmp.MakeComparisonOperator(treecmp.IsNotDistinctFrom), Left: $1.expr(), Right: tree.MakeDBool(true)}
 14818    }
 14819  | a_expr IS NOT TRUE %prec IS
 14820    {
 14821      $$.val = &tree.ComparisonExpr{Operator: treecmp.MakeComparisonOperator(treecmp.IsDistinctFrom), Left: $1.expr(), Right: tree.MakeDBool(true)}
 14822    }
 14823  | a_expr IS FALSE %prec IS
 14824    {
 14825      $$.val = &tree.ComparisonExpr{Operator: treecmp.MakeComparisonOperator(treecmp.IsNotDistinctFrom), Left: $1.expr(), Right: tree.MakeDBool(false)}
 14826    }
 14827  | a_expr IS NOT FALSE %prec IS
 14828    {
 14829      $$.val = &tree.ComparisonExpr{Operator: treecmp.MakeComparisonOperator(treecmp.IsDistinctFrom), Left: $1.expr(), Right: tree.MakeDBool(false)}
 14830    }
 14831  | a_expr IS UNKNOWN %prec IS
 14832    {
 14833      $$.val = &tree.ComparisonExpr{Operator: treecmp.MakeComparisonOperator(treecmp.IsNotDistinctFrom), Left: $1.expr(), Right: tree.DNull}
 14834    }
 14835  | a_expr IS NOT UNKNOWN %prec IS
 14836    {
 14837      $$.val = &tree.ComparisonExpr{Operator: treecmp.MakeComparisonOperator(treecmp.IsDistinctFrom), Left: $1.expr(), Right: tree.DNull}
 14838    }
 14839  | a_expr IS DISTINCT FROM a_expr %prec IS
 14840    {
 14841      $$.val = &tree.ComparisonExpr{Operator: treecmp.MakeComparisonOperator(treecmp.IsDistinctFrom), Left: $1.expr(), Right: $5.expr()}
 14842    }
 14843  | a_expr IS NOT DISTINCT FROM a_expr %prec IS
 14844    {
 14845      $$.val = &tree.ComparisonExpr{Operator: treecmp.MakeComparisonOperator(treecmp.IsNotDistinctFrom), Left: $1.expr(), Right: $6.expr()}
 14846    }
 14847  | a_expr IS OF '(' type_list ')' %prec IS
 14848    {
 14849      $$.val = &tree.IsOfTypeExpr{Expr: $1.expr(), Types: $5.typeReferences()}
 14850    }
 14851  | a_expr IS NOT OF '(' type_list ')' %prec IS
 14852    {
 14853      $$.val = &tree.IsOfTypeExpr{Not: true, Expr: $1.expr(), Types: $6.typeReferences()}
 14854    }
 14855  | a_expr BETWEEN opt_asymmetric b_expr AND a_expr %prec BETWEEN
 14856    {
 14857      $$.val = &tree.RangeCond{Left: $1.expr(), From: $4.expr(), To: $6.expr()}
 14858    }
 14859  | a_expr NOT_LA BETWEEN opt_asymmetric b_expr AND a_expr %prec NOT_LA
 14860    {
 14861      $$.val = &tree.RangeCond{Not: true, Left: $1.expr(), From: $5.expr(), To: $7.expr()}
 14862    }
 14863  | a_expr BETWEEN SYMMETRIC b_expr AND a_expr %prec BETWEEN
 14864    {
 14865      $$.val = &tree.RangeCond{Symmetric: true, Left: $1.expr(), From: $4.expr(), To: $6.expr()}
 14866    }
 14867  | a_expr NOT_LA BETWEEN SYMMETRIC b_expr AND a_expr %prec NOT_LA
 14868    {
 14869      $$.val = &tree.RangeCond{Not: true, Symmetric: true, Left: $1.expr(), From: $5.expr(), To: $7.expr()}
 14870    }
 14871  | a_expr IN in_expr
 14872    {
 14873      $$.val = &tree.ComparisonExpr{Operator: treecmp.MakeComparisonOperator(treecmp.In), Left: $1.expr(), Right: $3.expr()}
 14874    }
 14875  | a_expr NOT_LA IN in_expr %prec NOT_LA
 14876    {
 14877      $$.val = &tree.ComparisonExpr{Operator: treecmp.MakeComparisonOperator(treecmp.NotIn), Left: $1.expr(), Right: $4.expr()}
 14878    }
 14879  | a_expr subquery_op sub_type a_expr %prec CONCAT
 14880    {
 14881      op := $3.cmpOp()
 14882      subOp := $2.op()
 14883      subOpCmp, ok := subOp.(treecmp.ComparisonOperator)
 14884      if !ok {
 14885        // It is possible that we found `~` operator which was incorrectly typed
 14886        // as "unary complement" math operator. Check whether that's the case and
 14887        // override it to the correct "reg match" comparison operator.
 14888        if tree.IsUnaryComplement(subOp) {
 14889          subOp = treecmp.MakeComparisonOperator(treecmp.RegMatch)
 14890        } else {
 14891          sqllex.Error(fmt.Sprintf("%s %s <array> is invalid because %q is not a boolean operator",
 14892            subOp, op, subOp))
 14893          return 1
 14894        }
 14895      }
 14896      $$.val = &tree.ComparisonExpr{
 14897        Operator: op,
 14898        SubOperator: subOpCmp,
 14899        Left: $1.expr(),
 14900        Right: $4.expr(),
 14901      }
 14902    }
 14903  | DEFAULT
 14904    {
 14905      $$.val = tree.DefaultVal{}
 14906    }
 14907  // The UNIQUE predicate is a standard SQL feature but not yet implemented
 14908  // in PostgreSQL (as of 10.5).
 14909  | UNIQUE '(' error { return unimplemented(sqllex, "UNIQUE predicate") }
 14910  
 14911  // Restricted expressions
 14912  //
 14913  // b_expr is a subset of the complete expression syntax defined by a_expr.
 14914  //
 14915  // Presently, AND, NOT, IS, and IN are the a_expr keywords that would cause
 14916  // trouble in the places where b_expr is used. For simplicity, we just
 14917  // eliminate all the boolean-keyword-operator productions from b_expr.
 14918  b_expr:
 14919    c_expr
 14920  | b_expr TYPECAST cast_target
 14921    {
 14922      $$.val = &tree.CastExpr{Expr: $1.expr(), Type: $3.typeReference(), SyntaxMode: tree.CastShort}
 14923    }
 14924  | b_expr TYPEANNOTATE typename
 14925    {
 14926      $$.val = &tree.AnnotateTypeExpr{Expr: $1.expr(), Type: $3.typeReference(), SyntaxMode: tree.AnnotateShort}
 14927    }
 14928  | '+' b_expr %prec UMINUS
 14929    {
 14930      $$.val = $2.expr()
 14931    }
 14932  | '-' b_expr %prec UMINUS
 14933    {
 14934      $$.val = unaryNegation($2.expr())
 14935    }
 14936  | '~' b_expr %prec UMINUS
 14937    {
 14938      $$.val = &tree.UnaryExpr{Operator: tree.MakeUnaryOperator(tree.UnaryComplement), Expr: $2.expr()}
 14939    }
 14940  | b_expr '+' b_expr
 14941    {
 14942      $$.val = &tree.BinaryExpr{Operator: treebin.MakeBinaryOperator(treebin.Plus), Left: $1.expr(), Right: $3.expr()}
 14943    }
 14944  | b_expr '-' b_expr
 14945    {
 14946      $$.val = &tree.BinaryExpr{Operator: treebin.MakeBinaryOperator(treebin.Minus), Left: $1.expr(), Right: $3.expr()}
 14947    }
 14948  | b_expr '*' b_expr
 14949    {
 14950      $$.val = &tree.BinaryExpr{Operator: treebin.MakeBinaryOperator(treebin.Mult), Left: $1.expr(), Right: $3.expr()}
 14951    }
 14952  | b_expr '/' b_expr
 14953    {
 14954      $$.val = &tree.BinaryExpr{Operator: treebin.MakeBinaryOperator(treebin.Div), Left: $1.expr(), Right: $3.expr()}
 14955    }
 14956  | b_expr FLOORDIV b_expr
 14957    {
 14958      $$.val = &tree.BinaryExpr{Operator: treebin.MakeBinaryOperator(treebin.FloorDiv), Left: $1.expr(), Right: $3.expr()}
 14959    }
 14960  | b_expr '%' b_expr
 14961    {
 14962      $$.val = &tree.BinaryExpr{Operator: treebin.MakeBinaryOperator(treebin.Mod), Left: $1.expr(), Right: $3.expr()}
 14963    }
 14964  | b_expr '^' b_expr
 14965    {
 14966      $$.val = &tree.BinaryExpr{Operator: treebin.MakeBinaryOperator(treebin.Pow), Left: $1.expr(), Right: $3.expr()}
 14967    }
 14968  | b_expr '#' b_expr
 14969    {
 14970      $$.val = &tree.BinaryExpr{Operator: treebin.MakeBinaryOperator(treebin.Bitxor), Left: $1.expr(), Right: $3.expr()}
 14971    }
 14972  | b_expr '&' b_expr
 14973    {
 14974      $$.val = &tree.BinaryExpr{Operator: treebin.MakeBinaryOperator(treebin.Bitand), Left: $1.expr(), Right: $3.expr()}
 14975    }
 14976  | b_expr '|' b_expr
 14977    {
 14978      $$.val = &tree.BinaryExpr{Operator: treebin.MakeBinaryOperator(treebin.Bitor), Left: $1.expr(), Right: $3.expr()}
 14979    }
 14980  | b_expr '<' b_expr
 14981    {
 14982      $$.val = &tree.ComparisonExpr{Operator: treecmp.MakeComparisonOperator(treecmp.LT), Left: $1.expr(), Right: $3.expr()}
 14983    }
 14984  | b_expr '>' b_expr
 14985    {
 14986      $$.val = &tree.ComparisonExpr{Operator: treecmp.MakeComparisonOperator(treecmp.GT), Left: $1.expr(), Right: $3.expr()}
 14987    }
 14988  | b_expr '=' b_expr
 14989    {
 14990      $$.val = &tree.ComparisonExpr{Operator: treecmp.MakeComparisonOperator(treecmp.EQ), Left: $1.expr(), Right: $3.expr()}
 14991    }
 14992  | b_expr CONCAT b_expr
 14993    {
 14994      $$.val = &tree.BinaryExpr{Operator: treebin.MakeBinaryOperator(treebin.Concat), Left: $1.expr(), Right: $3.expr()}
 14995    }
 14996  | b_expr LSHIFT b_expr
 14997    {
 14998      $$.val = &tree.BinaryExpr{Operator: treebin.MakeBinaryOperator(treebin.LShift), Left: $1.expr(), Right: $3.expr()}
 14999    }
 15000  | b_expr RSHIFT b_expr
 15001    {
 15002      $$.val = &tree.BinaryExpr{Operator: treebin.MakeBinaryOperator(treebin.RShift), Left: $1.expr(), Right: $3.expr()}
 15003    }
 15004  | b_expr LESS_EQUALS b_expr
 15005    {
 15006      $$.val = &tree.ComparisonExpr{Operator: treecmp.MakeComparisonOperator(treecmp.LE), Left: $1.expr(), Right: $3.expr()}
 15007    }
 15008  | b_expr GREATER_EQUALS b_expr
 15009    {
 15010      $$.val = &tree.ComparisonExpr{Operator: treecmp.MakeComparisonOperator(treecmp.GE), Left: $1.expr(), Right: $3.expr()}
 15011    }
 15012  | b_expr NOT_EQUALS b_expr
 15013    {
 15014      $$.val = &tree.ComparisonExpr{Operator: treecmp.MakeComparisonOperator(treecmp.NE), Left: $1.expr(), Right: $3.expr()}
 15015    }
 15016  | qual_op b_expr %prec CBRT
 15017    {
 15018      var retCode int
 15019      $$.val, retCode = processUnaryQualOp(sqllex, $1.op(), $2.expr())
 15020      if retCode != 0 {
 15021        return retCode
 15022      }
 15023    }
 15024  | b_expr qual_op b_expr %prec CBRT
 15025    {
 15026      {
 15027        var retCode int
 15028        $$.val, retCode = processBinaryQualOp(sqllex, $2.op(), $1.expr(), $3.expr())
 15029        if retCode != 0 {
 15030          return retCode
 15031        }
 15032      }
 15033    }
 15034  | b_expr IS DISTINCT FROM b_expr %prec IS
 15035    {
 15036      $$.val = &tree.ComparisonExpr{Operator: treecmp.MakeComparisonOperator(treecmp.IsDistinctFrom), Left: $1.expr(), Right: $5.expr()}
 15037    }
 15038  | b_expr IS NOT DISTINCT FROM b_expr %prec IS
 15039    {
 15040      $$.val = &tree.ComparisonExpr{Operator: treecmp.MakeComparisonOperator(treecmp.IsNotDistinctFrom), Left: $1.expr(), Right: $6.expr()}
 15041    }
 15042  | b_expr IS OF '(' type_list ')' %prec IS
 15043    {
 15044      $$.val = &tree.IsOfTypeExpr{Expr: $1.expr(), Types: $5.typeReferences()}
 15045    }
 15046  | b_expr IS NOT OF '(' type_list ')' %prec IS
 15047    {
 15048      $$.val = &tree.IsOfTypeExpr{Not: true, Expr: $1.expr(), Types: $6.typeReferences()}
 15049    }
 15050  
 15051  // Productions that can be used in both a_expr and b_expr.
 15052  //
 15053  // Note: productions that refer recursively to a_expr or b_expr mostly cannot
 15054  // appear here. However, it's OK to refer to a_exprs that occur inside
 15055  // parentheses, such as function arguments; that cannot introduce ambiguity to
 15056  // the b_expr syntax.
 15057  //
 15058  c_expr:
 15059    d_expr
 15060  | d_expr array_subscripts
 15061    {
 15062      $$.val = &tree.IndirectionExpr{
 15063        Expr: $1.expr(),
 15064        Indirection: $2.arraySubscripts(),
 15065      }
 15066    }
 15067  | case_expr
 15068  | EXISTS select_with_parens
 15069    {
 15070      $$.val = &tree.Subquery{Select: $2.selectStmt(), Exists: true}
 15071    }
 15072  
 15073  // Productions that can be followed by a postfix operator.
 15074  //
 15075  // Currently we support array indexing (see c_expr above).
 15076  //
 15077  // TODO(knz/jordan): this is the rule that can be extended to support
 15078  // composite types (#27792) with e.g.:
 15079  //
 15080  //     | '(' a_expr ')' field_access_ops
 15081  //
 15082  //     [...]
 15083  //
 15084  //     // field_access_ops supports the notations:
 15085  //     // - .a
 15086  //     // - .a[123]
 15087  //     // - .a.b[123][5456].c.d
 15088  //     // NOT [123] directly, this is handled in c_expr above.
 15089  //
 15090  //     field_access_ops:
 15091  //       field_access_op
 15092  //     | field_access_op other_subscripts
 15093  //
 15094  //     field_access_op:
 15095  //       '.' name
 15096  //     other_subscripts:
 15097  //       other_subscript
 15098  //     | other_subscripts other_subscript
 15099  //     other_subscript:
 15100  //        field_access_op
 15101  //     |  array_subscripts
 15102  
 15103  d_expr:
 15104    ICONST
 15105    {
 15106      $$.val = $1.numVal()
 15107    }
 15108  | FCONST
 15109    {
 15110      $$.val = $1.numVal()
 15111    }
 15112  | SCONST
 15113    {
 15114      $$.val = tree.NewStrVal($1)
 15115    }
 15116  | BCONST
 15117    {
 15118      $$.val = tree.NewBytesStrVal($1)
 15119    }
 15120  | BITCONST
 15121    {
 15122      d, err := tree.ParseDBitArray($1)
 15123      if err != nil { return setErr(sqllex, err) }
 15124      $$.val = d
 15125    }
 15126  | func_application_name '(' expr_list opt_sort_clause_no_index ')' SCONST { return unimplemented(sqllex, $1.resolvableFuncRef().String() + "(...) SCONST") }
 15127  | typed_literal
 15128    {
 15129      $$.val = $1.expr()
 15130    }
 15131  | interval_value
 15132    {
 15133      $$.val = $1.expr()
 15134    }
 15135  | TRUE
 15136    {
 15137      $$.val = tree.MakeDBool(true)
 15138    }
 15139  | FALSE
 15140    {
 15141      $$.val = tree.MakeDBool(false)
 15142    }
 15143  | NULL
 15144    {
 15145      $$.val = tree.DNull
 15146    }
 15147  | column_path_with_star
 15148    {
 15149      $$.val = tree.Expr($1.unresolvedName())
 15150    }
 15151  | '@' iconst64
 15152    {
 15153      colNum := $2.int64()
 15154      if colNum < 1 || colNum > int64(MaxInt) {
 15155        sqllex.Error(fmt.Sprintf("invalid column ordinal: @%d", colNum))
 15156        return 1
 15157      }
 15158      $$.val = tree.NewOrdinalReference(int(colNum-1))
 15159    }
 15160  | PLACEHOLDER
 15161    {
 15162      p := $1.placeholder()
 15163      sqllex.(*lexer).UpdateNumPlaceholders(p)
 15164      $$.val = p
 15165    }
 15166  // TODO(knz/jordan): extend this for compound types. See explanation above.
 15167  | '(' a_expr ')' '.' '*'
 15168    {
 15169      $$.val = &tree.TupleStar{Expr: $2.expr()}
 15170    }
 15171  | '(' a_expr ')' '.' unrestricted_name
 15172    {
 15173      $$.val = &tree.ColumnAccessExpr{Expr: $2.expr(), ColName: tree.Name($5) }
 15174    }
 15175  | '(' a_expr ')' '.' '@' ICONST
 15176    {
 15177      idx, err := $6.numVal().AsInt32()
 15178      if err != nil { return setErr(sqllex, err) }
 15179      if idx <= 0 {
 15180        err := errors.New("invalid numeric tuple index: indexes must be > 0")
 15181        return setErr(sqllex, err)
 15182      }
 15183      $$.val = &tree.ColumnAccessExpr{Expr: $2.expr(), ByIndex: true, ColIndex: int(idx-1)}
 15184    }
 15185  | '(' a_expr ')'
 15186    {
 15187      $$.val = &tree.ParenExpr{Expr: $2.expr()}
 15188    }
 15189  | func_expr
 15190  | select_with_parens %prec UMINUS
 15191    {
 15192      $$.val = &tree.Subquery{Select: $1.selectStmt()}
 15193    }
 15194  | labeled_row
 15195    {
 15196      $$.val = $1.tuple()
 15197    }
 15198  | ARRAY select_with_parens %prec UMINUS
 15199    {
 15200      $$.val = &tree.ArrayFlatten{Subquery: &tree.Subquery{Select: $2.selectStmt()}}
 15201    }
 15202  | ARRAY row
 15203    {
 15204      $$.val = &tree.Array{Exprs: $2.tuple().Exprs}
 15205    }
 15206  | ARRAY array_expr
 15207    {
 15208      $$.val = $2.expr()
 15209    }
 15210  | GROUPING '(' expr_list ')' { return unimplemented(sqllex, "d_expr grouping") }
 15211  
 15212  func_application:
 15213    func_application_name '(' ')'
 15214    {
 15215      $$.val = &tree.FuncExpr{Func: $1.resolvableFuncRef()}
 15216    }
 15217  | func_application_name '(' expr_list opt_sort_clause_no_index ')'
 15218    {
 15219      $$.val = &tree.FuncExpr{Func: $1.resolvableFuncRef(), Exprs: $3.exprs(), OrderBy: $4.orderBy(), AggType: tree.GeneralAgg}
 15220    }
 15221  | func_application_name '(' VARIADIC a_expr opt_sort_clause_no_index ')' { return unimplemented(sqllex, "variadic") }
 15222  | func_application_name '(' expr_list ',' VARIADIC a_expr opt_sort_clause_no_index ')' { return unimplemented(sqllex, "variadic") }
 15223  | func_application_name '(' ALL expr_list opt_sort_clause_no_index ')'
 15224    {
 15225      $$.val = &tree.FuncExpr{Func: $1.resolvableFuncRef(), Type: tree.AllFuncType, Exprs: $4.exprs(), OrderBy: $5.orderBy(), AggType: tree.GeneralAgg}
 15226    }
 15227  // TODO(ridwanmsharif): Once DISTINCT is supported by window aggregates,
 15228  // allow ordering to be specified below.
 15229  | func_application_name '(' DISTINCT expr_list ')'
 15230    {
 15231      $$.val = &tree.FuncExpr{Func: $1.resolvableFuncRef(), Type: tree.DistinctFuncType, Exprs: $4.exprs()}
 15232    }
 15233  | func_application_name '(' '*' ')'
 15234    {
 15235      $$.val = &tree.FuncExpr{Func: $1.resolvableFuncRef(), Exprs: tree.Exprs{tree.StarExpr()}}
 15236    }
 15237  | func_application_name '(' error { return helpWithFunction(sqllex, $1.resolvableFuncRef()) }
 15238  
 15239  func_application_name:
 15240    func_name
 15241    {
 15242      $$.val = $1.resolvableFuncRefFromName()
 15243    }
 15244  | '[' FUNCTION iconst32 ']'
 15245    {
 15246      id := $3.int32()
 15247      $$.val = tree.ResolvableFunctionReference{
 15248        FunctionReference: &tree.FunctionOID{OID: oid.Oid(id)},
 15249      }
 15250    }
 15251  
 15252  // typed_literal represents expressions like INT '4', or generally <TYPE> SCONST.
 15253  // This rule handles both the case of qualified and non-qualified typenames.
 15254  typed_literal:
 15255    // The key here is that none of the keywords in the func_name_no_crdb_extra
 15256    // production can overlap with the type rules in const_typename, otherwise
 15257    // we will have conflicts between this rule and the one below.
 15258    func_name_no_crdb_extra SCONST
 15259    {
 15260      name := $1.unresolvedName()
 15261      if name.NumParts == 1 {
 15262        typName := name.Parts[0]
 15263        /* FORCE DOC */
 15264        // See https://www.postgresql.org/docs/9.1/static/datatype-character.html
 15265        // Postgres supports a special character type named "char" (with the quotes)
 15266        // that is a single-character column type. It's used by system tables.
 15267        // Eventually this clause will be used to parse user-defined types as well,
 15268        // since their names can be quoted.
 15269        if typName == "char" {
 15270          $$.val = &tree.CastExpr{Expr: tree.NewStrVal($2), Type: types.QChar, SyntaxMode: tree.CastPrepend}
 15271        } else if typName == "serial" {
 15272          switch sqllex.(*lexer).nakedIntType.Width() {
 15273          case 32:
 15274            $$.val = &tree.CastExpr{Expr: tree.NewStrVal($2), Type: &types.Serial4Type, SyntaxMode: tree.CastPrepend}
 15275          default:
 15276            $$.val = &tree.CastExpr{Expr: tree.NewStrVal($2), Type: &types.Serial8Type, SyntaxMode: tree.CastPrepend}
 15277          }
 15278        } else {
 15279          // Check the the type is one of our "non-keyword" type names.
 15280          // Otherwise, package it up as a type reference for later.
 15281          // However, if the type name is one of our known unsupported
 15282          // types, return an unimplemented error message.
 15283          var typ tree.ResolvableTypeReference
 15284          var ok bool
 15285          var unimp int
 15286          typ, ok, unimp = types.TypeForNonKeywordTypeName(typName)
 15287          if !ok {
 15288            switch unimp {
 15289              case 0:
 15290                // In this case, we don't think this type is one of our
 15291                // known unsupported types, so make a type reference for it.
 15292                aIdx := sqllex.(*lexer).NewAnnotation()
 15293                un, err := name.ToUnresolvedObjectName(aIdx)
 15294                if err != nil { return setErr(sqllex, err) }
 15295                typ = &un
 15296              case -1:
 15297                return unimplemented(sqllex, "type name " + typName)
 15298              default:
 15299                return unimplementedWithIssueDetail(sqllex, unimp, typName)
 15300            }
 15301          }
 15302        $$.val = &tree.CastExpr{Expr: tree.NewStrVal($2), Type: typ, SyntaxMode: tree.CastPrepend}
 15303        }
 15304      } else {
 15305        aIdx := sqllex.(*lexer).NewAnnotation()
 15306        res, err := name.ToUnresolvedObjectName(aIdx)
 15307        if err != nil { return setErr(sqllex, err) }
 15308        $$.val = &tree.CastExpr{Expr: tree.NewStrVal($2), Type: &res, SyntaxMode: tree.CastPrepend}
 15309      }
 15310    }
 15311  | const_typename SCONST
 15312    {
 15313      $$.val = &tree.CastExpr{Expr: tree.NewStrVal($2), Type: $1.colType(), SyntaxMode: tree.CastPrepend}
 15314    }
 15315  
 15316  // func_expr and its cousin func_expr_windowless are split out from c_expr just
 15317  // so that we have classifications for "everything that is a function call or
 15318  // looks like one". This isn't very important, but it saves us having to
 15319  // document which variants are legal in places like "FROM function()" or the
 15320  // backwards-compatible functional-index syntax for CREATE INDEX. (Note that
 15321  // many of the special SQL functions wouldn't actually make any sense as
 15322  // functional index entries, but we ignore that consideration here.)
 15323  func_expr:
 15324    func_application within_group_clause filter_clause over_clause
 15325    {
 15326      f := $1.expr().(*tree.FuncExpr)
 15327      w := $2.expr().(*tree.FuncExpr)
 15328      if w.AggType != 0 {
 15329        f.AggType = w.AggType
 15330        f.OrderBy = w.OrderBy
 15331      }
 15332      f.Filter = $3.expr()
 15333      f.WindowDef = $4.windowDef()
 15334      $$.val = f
 15335    }
 15336  | func_expr_common_subexpr
 15337    {
 15338      $$.val = $1.expr()
 15339    }
 15340  
 15341  // As func_expr but does not accept WINDOW functions directly (but they can
 15342  // still be contained in arguments for functions etc). Use this when window
 15343  // expressions are not allowed, where needed to disambiguate the grammar
 15344  // (e.g. in CREATE INDEX).
 15345  func_expr_windowless:
 15346    func_application { $$.val = $1.expr() }
 15347  | func_expr_common_subexpr { $$.val = $1.expr() }
 15348  
 15349  // Special expressions that are considered to be functions.
 15350  func_expr_common_subexpr:
 15351    COLLATION FOR '(' a_expr ')'
 15352    {
 15353      $$.val = &tree.FuncExpr{Func: tree.WrapFunction("pg_collation_for"), Exprs: tree.Exprs{$4.expr()}}
 15354    }
 15355  | CURRENT_DATE
 15356    {
 15357      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1)}
 15358    }
 15359  | CURRENT_SCHEMA
 15360    {
 15361      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1)}
 15362    }
 15363  // Special identifier current_catalog is equivalent to current_database().
 15364  // https://www.postgresql.org/docs/10/static/functions-info.html
 15365  | CURRENT_CATALOG
 15366    {
 15367      $$.val = &tree.FuncExpr{Func: tree.WrapFunction("current_database")}
 15368    }
 15369  | CURRENT_TIMESTAMP
 15370    {
 15371      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1)}
 15372    }
 15373  | CURRENT_TIME
 15374    {
 15375      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1)}
 15376    }
 15377  | LOCALTIMESTAMP
 15378    {
 15379      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1)}
 15380    }
 15381  | LOCALTIME
 15382    {
 15383      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1)}
 15384    }
 15385  | CURRENT_USER
 15386    {
 15387      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1)}
 15388    }
 15389  // Special identifier current_role is equivalent to current_user.
 15390  // https://www.postgresql.org/docs/10/static/functions-info.html
 15391  | CURRENT_ROLE
 15392    {
 15393      $$.val = &tree.FuncExpr{Func: tree.WrapFunction("current_user")}
 15394    }
 15395  | SESSION_USER
 15396    {
 15397      $$.val = &tree.FuncExpr{Func: tree.WrapFunction("session_user")}
 15398    }
 15399  | USER
 15400    {
 15401      $$.val = &tree.FuncExpr{Func: tree.WrapFunction("current_user")}
 15402    }
 15403  | CAST '(' a_expr AS cast_target ')'
 15404    {
 15405      $$.val = &tree.CastExpr{Expr: $3.expr(), Type: $5.typeReference(), SyntaxMode: tree.CastExplicit}
 15406    }
 15407  | ANNOTATE_TYPE '(' a_expr ',' typename ')'
 15408    {
 15409      $$.val = &tree.AnnotateTypeExpr{Expr: $3.expr(), Type: $5.typeReference(), SyntaxMode: tree.AnnotateExplicit}
 15410    }
 15411  | IF '(' a_expr ',' a_expr ',' a_expr ')'
 15412    {
 15413      $$.val = &tree.IfExpr{Cond: $3.expr(), True: $5.expr(), Else: $7.expr()}
 15414    }
 15415  | IFERROR '(' a_expr ',' a_expr ',' a_expr ')'
 15416    {
 15417      $$.val = &tree.IfErrExpr{Cond: $3.expr(), Else: $5.expr(), ErrCode: $7.expr()}
 15418    }
 15419  | IFERROR '(' a_expr ',' a_expr ')'
 15420    {
 15421      $$.val = &tree.IfErrExpr{Cond: $3.expr(), Else: $5.expr()}
 15422    }
 15423  | ISERROR '(' a_expr ')'
 15424    {
 15425      $$.val = &tree.IfErrExpr{Cond: $3.expr()}
 15426    }
 15427  | ISERROR '(' a_expr ',' a_expr ')'
 15428    {
 15429      $$.val = &tree.IfErrExpr{Cond: $3.expr(), ErrCode: $5.expr()}
 15430    }
 15431  | NULLIF '(' a_expr ',' a_expr ')'
 15432    {
 15433      $$.val = &tree.NullIfExpr{Expr1: $3.expr(), Expr2: $5.expr()}
 15434    }
 15435  | IFNULL '(' a_expr ',' a_expr ')'
 15436    {
 15437      $$.val = &tree.CoalesceExpr{Name: "IFNULL", Exprs: tree.Exprs{$3.expr(), $5.expr()}}
 15438    }
 15439  | COALESCE '(' expr_list ')'
 15440    {
 15441      $$.val = &tree.CoalesceExpr{Name: "COALESCE", Exprs: $3.exprs()}
 15442    }
 15443  | special_function
 15444  
 15445  special_function:
 15446    CURRENT_DATE '(' ')'
 15447    {
 15448      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1)}
 15449    }
 15450  | CURRENT_DATE '(' error { return helpWithFunctionByName(sqllex, $1) }
 15451  | CURRENT_SCHEMA '(' ')'
 15452    {
 15453      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1)}
 15454    }
 15455  | CURRENT_SCHEMA '(' error { return helpWithFunctionByName(sqllex, $1) }
 15456  | CURRENT_TIMESTAMP '(' ')'
 15457    {
 15458      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1)}
 15459    }
 15460  | CURRENT_TIMESTAMP '(' a_expr ')'
 15461    {
 15462      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1), Exprs: tree.Exprs{$3.expr()}}
 15463    }
 15464  | CURRENT_TIMESTAMP '(' error { return helpWithFunctionByName(sqllex, $1) }
 15465  | CURRENT_TIME '(' ')'
 15466    {
 15467      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1)}
 15468    }
 15469  | CURRENT_TIME '(' a_expr ')'
 15470    {
 15471      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1), Exprs: tree.Exprs{$3.expr()}}
 15472    }
 15473  | CURRENT_TIME '(' error { return helpWithFunctionByName(sqllex, $1) }
 15474  | LOCALTIMESTAMP '(' ')'
 15475    {
 15476      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1)}
 15477    }
 15478  | LOCALTIMESTAMP '(' a_expr ')'
 15479    {
 15480      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1), Exprs: tree.Exprs{$3.expr()}}
 15481    }
 15482  | LOCALTIMESTAMP '(' error { return helpWithFunctionByName(sqllex, $1) }
 15483  | LOCALTIME '(' ')'
 15484    {
 15485      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1)}
 15486    }
 15487  | LOCALTIME '(' a_expr ')'
 15488    {
 15489      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1), Exprs: tree.Exprs{$3.expr()}}
 15490    }
 15491  | LOCALTIME '(' error { return helpWithFunctionByName(sqllex, $1) }
 15492  | CURRENT_USER '(' ')'
 15493    {
 15494      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1)}
 15495    }
 15496  | CURRENT_USER '(' error { return helpWithFunctionByName(sqllex, $1) }
 15497  | SESSION_USER '(' ')'
 15498    {
 15499      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1)}
 15500    }
 15501  | SESSION_USER '(' error { return helpWithFunctionByName(sqllex, $1) }
 15502  | EXTRACT '(' extract_list ')'
 15503    {
 15504      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1), Exprs: $3.exprs()}
 15505    }
 15506  | EXTRACT '(' error { return helpWithFunctionByName(sqllex, $1) }
 15507  | EXTRACT_DURATION '(' extract_list ')'
 15508    {
 15509      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1), Exprs: $3.exprs()}
 15510    }
 15511  | EXTRACT_DURATION '(' error { return helpWithFunctionByName(sqllex, $1) }
 15512  | OVERLAY '(' overlay_list ')'
 15513    {
 15514      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1), Exprs: $3.exprs()}
 15515    }
 15516  | OVERLAY '(' error { return helpWithFunctionByName(sqllex, $1) }
 15517  | POSITION '(' position_list ')'
 15518    {
 15519      $$.val = &tree.FuncExpr{Func: tree.WrapFunction("strpos"), Exprs: $3.exprs()}
 15520    }
 15521  | SUBSTRING '(' substr_list ')'
 15522    {
 15523      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1), Exprs: $3.exprs()}
 15524    }
 15525  | SUBSTRING '(' error { return helpWithFunctionByName(sqllex, $1) }
 15526  | TREAT '(' a_expr AS typename ')' { return unimplemented(sqllex, "treat") }
 15527  | TRIM '(' BOTH trim_list ')'
 15528    {
 15529      $$.val = &tree.FuncExpr{Func: tree.WrapFunction("btrim"), Exprs: $4.exprs()}
 15530    }
 15531  | TRIM '(' LEADING trim_list ')'
 15532    {
 15533      $$.val = &tree.FuncExpr{Func: tree.WrapFunction("ltrim"), Exprs: $4.exprs()}
 15534    }
 15535  | TRIM '(' TRAILING trim_list ')'
 15536    {
 15537      $$.val = &tree.FuncExpr{Func: tree.WrapFunction("rtrim"), Exprs: $4.exprs()}
 15538    }
 15539  | TRIM '(' trim_list ')'
 15540    {
 15541      $$.val = &tree.FuncExpr{Func: tree.WrapFunction("btrim"), Exprs: $3.exprs()}
 15542    }
 15543  | GREATEST '(' expr_list ')'
 15544    {
 15545      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1), Exprs: $3.exprs()}
 15546    }
 15547  | GREATEST '(' error { return helpWithFunctionByName(sqllex, $1) }
 15548  | LEAST '(' expr_list ')'
 15549    {
 15550      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1), Exprs: $3.exprs()}
 15551    }
 15552  | LEAST '(' error { return helpWithFunctionByName(sqllex, $1) }
 15553  
 15554  
 15555  // Aggregate decoration clauses
 15556  within_group_clause:
 15557    WITHIN GROUP '(' single_sort_clause ')'
 15558    {
 15559      $$.val = &tree.FuncExpr{OrderBy: $4.orderBy(), AggType: tree.OrderedSetAgg}
 15560    }
 15561  | /* EMPTY */
 15562    {
 15563      $$.val = &tree.FuncExpr{}
 15564    }
 15565  
 15566  filter_clause:
 15567    FILTER '(' WHERE a_expr ')'
 15568    {
 15569      $$.val = $4.expr()
 15570    }
 15571  | /* EMPTY */
 15572    {
 15573      $$.val = tree.Expr(nil)
 15574    }
 15575  
 15576  // Window Definitions
 15577  window_clause:
 15578    WINDOW window_definition_list
 15579    {
 15580      $$.val = $2.window()
 15581    }
 15582  | /* EMPTY */
 15583    {
 15584      $$.val = tree.Window(nil)
 15585    }
 15586  
 15587  window_definition_list:
 15588    window_definition
 15589    {
 15590      $$.val = tree.Window{$1.windowDef()}
 15591    }
 15592  | window_definition_list ',' window_definition
 15593    {
 15594      $$.val = append($1.window(), $3.windowDef())
 15595    }
 15596  
 15597  window_definition:
 15598    window_name AS window_specification
 15599    {
 15600      n := $3.windowDef()
 15601      n.Name = tree.Name($1)
 15602      $$.val = n
 15603    }
 15604  
 15605  over_clause:
 15606    OVER window_specification
 15607    {
 15608      $$.val = $2.windowDef()
 15609    }
 15610  | OVER window_name
 15611    {
 15612      $$.val = &tree.WindowDef{Name: tree.Name($2)}
 15613    }
 15614  | /* EMPTY */
 15615    {
 15616      $$.val = (*tree.WindowDef)(nil)
 15617    }
 15618  
 15619  window_specification:
 15620    '(' opt_existing_window_name opt_partition_clause
 15621      opt_sort_clause_no_index opt_frame_clause ')'
 15622    {
 15623      $$.val = &tree.WindowDef{
 15624        RefName: tree.Name($2),
 15625        Partitions: $3.exprs(),
 15626        OrderBy: $4.orderBy(),
 15627        Frame: $5.windowFrame(),
 15628      }
 15629    }
 15630  
 15631  // If we see PARTITION, RANGE, ROWS, or GROUPS as the first token after the '('
 15632  // of a window_specification, we want the assumption to be that there is no
 15633  // existing_window_name; but those keywords are unreserved and so could be
 15634  // names. We fix this by making them have the same precedence as IDENT and
 15635  // giving the empty production here a slightly higher precedence, so that the
 15636  // shift/reduce conflict is resolved in favor of reducing the rule. These
 15637  // keywords are thus precluded from being an existing_window_name but are not
 15638  // reserved for any other purpose.
 15639  opt_existing_window_name:
 15640    name
 15641  | /* EMPTY */ %prec CONCAT
 15642    {
 15643      $$ = ""
 15644    }
 15645  
 15646  opt_partition_clause:
 15647    PARTITION BY expr_list
 15648    {
 15649      $$.val = $3.exprs()
 15650    }
 15651  | /* EMPTY */
 15652    {
 15653      $$.val = tree.Exprs(nil)
 15654    }
 15655  
 15656  opt_frame_clause:
 15657    RANGE frame_extent opt_frame_exclusion
 15658    {
 15659      $$.val = &tree.WindowFrame{
 15660        Mode: treewindow.RANGE,
 15661        Bounds: $2.windowFrameBounds(),
 15662        Exclusion: $3.windowFrameExclusion(),
 15663      }
 15664    }
 15665  | ROWS frame_extent opt_frame_exclusion
 15666    {
 15667      $$.val = &tree.WindowFrame{
 15668        Mode: treewindow.ROWS,
 15669        Bounds: $2.windowFrameBounds(),
 15670        Exclusion: $3.windowFrameExclusion(),
 15671      }
 15672    }
 15673  | GROUPS frame_extent opt_frame_exclusion
 15674    {
 15675      $$.val = &tree.WindowFrame{
 15676        Mode: treewindow.GROUPS,
 15677        Bounds: $2.windowFrameBounds(),
 15678        Exclusion: $3.windowFrameExclusion(),
 15679      }
 15680    }
 15681  | /* EMPTY */
 15682    {
 15683      $$.val = (*tree.WindowFrame)(nil)
 15684    }
 15685  
 15686  frame_extent:
 15687    frame_bound
 15688    {
 15689      startBound := $1.windowFrameBound()
 15690      switch {
 15691      case startBound.BoundType == treewindow.UnboundedFollowing:
 15692        sqllex.Error("frame start cannot be UNBOUNDED FOLLOWING")
 15693        return 1
 15694      case startBound.BoundType == treewindow.OffsetFollowing:
 15695        sqllex.Error("frame starting from following row cannot end with current row")
 15696        return 1
 15697      }
 15698      $$.val = tree.WindowFrameBounds{StartBound: startBound}
 15699    }
 15700  | BETWEEN frame_bound AND frame_bound
 15701    {
 15702      startBound := $2.windowFrameBound()
 15703      endBound := $4.windowFrameBound()
 15704      switch {
 15705      case startBound.BoundType == treewindow.UnboundedFollowing:
 15706        sqllex.Error("frame start cannot be UNBOUNDED FOLLOWING")
 15707        return 1
 15708      case endBound.BoundType == treewindow.UnboundedPreceding:
 15709        sqllex.Error("frame end cannot be UNBOUNDED PRECEDING")
 15710        return 1
 15711      case startBound.BoundType == treewindow.CurrentRow && endBound.BoundType == treewindow.OffsetPreceding:
 15712        sqllex.Error("frame starting from current row cannot have preceding rows")
 15713        return 1
 15714      case startBound.BoundType == treewindow.OffsetFollowing && endBound.BoundType == treewindow.OffsetPreceding:
 15715        sqllex.Error("frame starting from following row cannot have preceding rows")
 15716        return 1
 15717      case startBound.BoundType == treewindow.OffsetFollowing && endBound.BoundType == treewindow.CurrentRow:
 15718        sqllex.Error("frame starting from following row cannot have preceding rows")
 15719        return 1
 15720      }
 15721      $$.val = tree.WindowFrameBounds{StartBound: startBound, EndBound: endBound}
 15722    }
 15723  
 15724  // This is used for both frame start and frame end, with output set up on the
 15725  // assumption it's frame start; the frame_extent productions must reject
 15726  // invalid cases.
 15727  frame_bound:
 15728    UNBOUNDED PRECEDING
 15729    {
 15730      $$.val = &tree.WindowFrameBound{BoundType: treewindow.UnboundedPreceding}
 15731    }
 15732  | UNBOUNDED FOLLOWING
 15733    {
 15734      $$.val = &tree.WindowFrameBound{BoundType: treewindow.UnboundedFollowing}
 15735    }
 15736  | CURRENT ROW
 15737    {
 15738      $$.val = &tree.WindowFrameBound{BoundType: treewindow.CurrentRow}
 15739    }
 15740  | a_expr PRECEDING
 15741    {
 15742      $$.val = &tree.WindowFrameBound{
 15743        OffsetExpr: $1.expr(),
 15744        BoundType: treewindow.OffsetPreceding,
 15745      }
 15746    }
 15747  | a_expr FOLLOWING
 15748    {
 15749      $$.val = &tree.WindowFrameBound{
 15750        OffsetExpr: $1.expr(),
 15751        BoundType: treewindow.OffsetFollowing,
 15752      }
 15753    }
 15754  
 15755  opt_frame_exclusion:
 15756    EXCLUDE CURRENT ROW
 15757    {
 15758      $$.val = treewindow.ExcludeCurrentRow
 15759    }
 15760  | EXCLUDE GROUP
 15761    {
 15762      $$.val = treewindow.ExcludeGroup
 15763    }
 15764  | EXCLUDE TIES
 15765    {
 15766      $$.val = treewindow.ExcludeTies
 15767    }
 15768  | EXCLUDE NO OTHERS
 15769    {
 15770      // EXCLUDE NO OTHERS is equivalent to omitting the frame exclusion clause.
 15771      $$.val = treewindow.NoExclusion
 15772    }
 15773  | /* EMPTY */
 15774    {
 15775      $$.val = treewindow.NoExclusion
 15776    }
 15777  
 15778  // Supporting nonterminals for expressions.
 15779  
 15780  // Explicit row production.
 15781  //
 15782  // SQL99 allows an optional ROW keyword, so we can now do single-element rows
 15783  // without conflicting with the parenthesized a_expr production. Without the
 15784  // ROW keyword, there must be more than one a_expr inside the parens.
 15785  row:
 15786    ROW '(' opt_expr_list ')'
 15787    {
 15788      $$.val = &tree.Tuple{Exprs: $3.exprs(), Row: true}
 15789    }
 15790  | expr_tuple_unambiguous
 15791    {
 15792      $$.val = $1.tuple()
 15793    }
 15794  
 15795  labeled_row:
 15796    row
 15797  | '(' row AS name_list ')'
 15798    {
 15799      t := $2.tuple()
 15800      labels := $4.nameList()
 15801      t.Labels = make([]string, len(labels))
 15802      for i, l := range labels {
 15803        t.Labels[i] = string(l)
 15804      }
 15805      $$.val = t
 15806    }
 15807  
 15808  sub_type:
 15809    ANY
 15810    {
 15811      $$.val = treecmp.MakeComparisonOperator(treecmp.Any)
 15812    }
 15813  | SOME
 15814    {
 15815      $$.val = treecmp.MakeComparisonOperator(treecmp.Some)
 15816    }
 15817  | ALL
 15818    {
 15819      $$.val = treecmp.MakeComparisonOperator(treecmp.All)
 15820    }
 15821  
 15822  // We combine mathOp and Op from PostgreSQL's gram.y there.
 15823  // In PostgreSQL, mathOp have an order of operations as defined by the
 15824  // assoc rules.
 15825  //
 15826  // In CockroachDB, we have defined further operations that have a defined
 15827  // order of operations (e.g. <@, |, &, ~, #, FLOORDIV) which is broken
 15828  // if we split them up to math_ops and ops, which breaks compatibility
 15829  // with PostgreSQL's qual_op.
 15830  //
 15831  // Ensure you also update process.*QualOp above when adding to this.
 15832  all_op:
 15833    // exactly from MathOp
 15834    '+' { $$.val = treebin.MakeBinaryOperator(treebin.Plus)  }
 15835  | '-' { $$.val = treebin.MakeBinaryOperator(treebin.Minus) }
 15836  | '*' { $$.val = treebin.MakeBinaryOperator(treebin.Mult)  }
 15837  | '/' { $$.val = treebin.MakeBinaryOperator(treebin.Div)   }
 15838  | '%' { $$.val = treebin.MakeBinaryOperator(treebin.Mod)   }
 15839  | '^' { $$.val = treebin.MakeBinaryOperator(treebin.Pow) }
 15840  | '<' { $$.val = treecmp.MakeComparisonOperator(treecmp.LT) }
 15841  | '>' { $$.val = treecmp.MakeComparisonOperator(treecmp.GT) }
 15842  | '=' { $$.val = treecmp.MakeComparisonOperator(treecmp.EQ) }
 15843  | LESS_EQUALS    { $$.val = treecmp.MakeComparisonOperator(treecmp.LE) }
 15844  | GREATER_EQUALS { $$.val = treecmp.MakeComparisonOperator(treecmp.GE) }
 15845  | NOT_EQUALS     { $$.val = treecmp.MakeComparisonOperator(treecmp.NE) }
 15846    // partial set of operators from from Op
 15847  | '?' { $$.val = treecmp.MakeComparisonOperator(treecmp.JSONExists) }
 15848  | '&' { $$.val = treebin.MakeBinaryOperator(treebin.Bitand) }
 15849  | '|' { $$.val = treebin.MakeBinaryOperator(treebin.Bitor)  }
 15850  | '#' { $$.val = treebin.MakeBinaryOperator(treebin.Bitxor) }
 15851  | FLOORDIV { $$.val = treebin.MakeBinaryOperator(treebin.FloorDiv) }
 15852  | CONTAINS { $$.val = treecmp.MakeComparisonOperator(treecmp.Contains) }
 15853  | CONTAINED_BY { $$.val = treecmp.MakeComparisonOperator(treecmp.ContainedBy) }
 15854  | LSHIFT { $$.val = treebin.MakeBinaryOperator(treebin.LShift) }
 15855  | RSHIFT { $$.val = treebin.MakeBinaryOperator(treebin.RShift) }
 15856  | CONCAT { $$.val = treebin.MakeBinaryOperator(treebin.Concat) }
 15857  | FETCHVAL { $$.val = treebin.MakeBinaryOperator(treebin.JSONFetchVal) }
 15858  | FETCHTEXT { $$.val = treebin.MakeBinaryOperator(treebin.JSONFetchText) }
 15859  | FETCHVAL_PATH { $$.val = treebin.MakeBinaryOperator(treebin.JSONFetchValPath) }
 15860  | FETCHTEXT_PATH { $$.val = treebin.MakeBinaryOperator(treebin.JSONFetchTextPath) }
 15861  | JSON_SOME_EXISTS { $$.val = treecmp.MakeComparisonOperator(treecmp.JSONSomeExists) }
 15862  | JSON_ALL_EXISTS { $$.val = treecmp.MakeComparisonOperator(treecmp.JSONAllExists) }
 15863  | NOT_REGMATCH { $$.val = treecmp.MakeComparisonOperator(treecmp.NotRegMatch) }
 15864  | REGIMATCH { $$.val = treecmp.MakeComparisonOperator(treecmp.RegIMatch) }
 15865  | NOT_REGIMATCH { $$.val = treecmp.MakeComparisonOperator(treecmp.NotRegIMatch) }
 15866  | AND_AND { $$.val = treecmp.MakeComparisonOperator(treecmp.Overlaps) }
 15867  | AT_AT { $$.val = treecmp.MakeComparisonOperator(treecmp.TSMatches) }
 15868  | '~' { $$.val = tree.MakeUnaryOperator(tree.UnaryComplement) }
 15869  | SQRT { $$.val = tree.MakeUnaryOperator(tree.UnarySqrt) }
 15870  | CBRT { $$.val = tree.MakeUnaryOperator(tree.UnaryCbrt) }
 15871  
 15872  operator_op:
 15873    all_op
 15874  | name '.' all_op
 15875    {
 15876      // Only support operators on pg_catalog.
 15877      if $1 != "pg_catalog" {
 15878        return unimplementedWithIssue(sqllex, 65017)
 15879      }
 15880      $$ = $3
 15881    }
 15882  
 15883  // qual_op partially matches qualOp PostgreSQL's gram.y.
 15884  // In an ideal circumstance, we also include non math_ops in this
 15885  // definition. However, this would break cross compatibility as we
 15886  // need %prec (keyword before OPERATOR) in a_expr/b_expr, which
 15887  // breaks order of operations for older versions of CockroachDB.
 15888  // See #64699 for the attempt.
 15889  qual_op:
 15890    OPERATOR '(' operator_op ')'
 15891    {
 15892      $$ = $3
 15893    }
 15894  
 15895  subquery_op:
 15896    all_op
 15897  | qual_op
 15898  | LIKE         { $$.val = treecmp.MakeComparisonOperator(treecmp.Like)     }
 15899  | NOT_LA LIKE  { $$.val = treecmp.MakeComparisonOperator(treecmp.NotLike)  }
 15900  | ILIKE        { $$.val = treecmp.MakeComparisonOperator(treecmp.ILike)    }
 15901  | NOT_LA ILIKE { $$.val = treecmp.MakeComparisonOperator(treecmp.NotILike) }
 15902    // cannot put SIMILAR TO here, because SIMILAR TO is a hack.
 15903    // the regular expression is preprocessed by a function (similar_escape),
 15904    // and the ~ operator for posix regular expressions is used.
 15905    //        x SIMILAR TO y     ->    x ~ similar_escape(y)
 15906    // this transformation is made on the fly by the parser upwards.
 15907    // however the SubLink structure which handles any/some/all stuff
 15908    // is not ready for such a thing.
 15909  
 15910  // expr_tuple1_ambiguous is a tuple expression with at least one expression.
 15911  // The allowable syntax is:
 15912  // ( )         -- empty tuple.
 15913  // ( E )       -- just one value, this is potentially ambiguous with
 15914  //             -- grouping parentheses. The ambiguity is resolved
 15915  //             -- by only allowing expr_tuple1_ambiguous on the RHS
 15916  //             -- of a IN expression.
 15917  // ( E, E, E ) -- comma-separated values, no trailing comma allowed.
 15918  // ( E, )      -- just one value with a comma, makes the syntax unambiguous
 15919  //             -- with grouping parentheses. This is not usually produced
 15920  //             -- by SQL clients, but can be produced by pretty-printing
 15921  //             -- internally in CockroachDB.
 15922  expr_tuple1_ambiguous:
 15923    '(' ')'
 15924    {
 15925      $$.val = &tree.Tuple{}
 15926    }
 15927  | '(' tuple1_ambiguous_values ')'
 15928    {
 15929      $$.val = &tree.Tuple{Exprs: $2.exprs()}
 15930    }
 15931  
 15932  tuple1_ambiguous_values:
 15933    a_expr
 15934    {
 15935      $$.val = tree.Exprs{$1.expr()}
 15936    }
 15937  | a_expr ','
 15938    {
 15939      $$.val = tree.Exprs{$1.expr()}
 15940    }
 15941  | a_expr ',' expr_list
 15942    {
 15943       $$.val = append(tree.Exprs{$1.expr()}, $3.exprs()...)
 15944    }
 15945  
 15946  // expr_tuple_unambiguous is a tuple expression with zero or more
 15947  // expressions. The allowable syntax is:
 15948  // ( )         -- zero values
 15949  // ( E, )      -- just one value. This is unambiguous with the (E) grouping syntax.
 15950  // ( E, E, E ) -- comma-separated values, more than 1.
 15951  expr_tuple_unambiguous:
 15952    '(' ')'
 15953    {
 15954      $$.val = &tree.Tuple{}
 15955    }
 15956  | '(' tuple1_unambiguous_values ')'
 15957    {
 15958      $$.val = &tree.Tuple{Exprs: $2.exprs()}
 15959    }
 15960  
 15961  tuple1_unambiguous_values:
 15962    a_expr ','
 15963    {
 15964      $$.val = tree.Exprs{$1.expr()}
 15965    }
 15966  | a_expr ',' expr_list
 15967    {
 15968       $$.val = append(tree.Exprs{$1.expr()}, $3.exprs()...)
 15969    }
 15970  
 15971  opt_expr_list:
 15972    expr_list
 15973  | /* EMPTY */
 15974    {
 15975      $$.val = tree.Exprs(nil)
 15976    }
 15977  
 15978  expr_list:
 15979    a_expr
 15980    {
 15981      $$.val = tree.Exprs{$1.expr()}
 15982    }
 15983  | expr_list ',' a_expr
 15984    {
 15985      $$.val = append($1.exprs(), $3.expr())
 15986    }
 15987  
 15988  type_list:
 15989    typename
 15990    {
 15991      $$.val = []tree.ResolvableTypeReference{$1.typeReference()}
 15992    }
 15993  | type_list ',' typename
 15994    {
 15995      $$.val = append($1.typeReferences(), $3.typeReference())
 15996    }
 15997  
 15998  array_expr:
 15999    '[' opt_expr_list ']'
 16000    {
 16001      $$.val = &tree.Array{Exprs: $2.exprs()}
 16002    }
 16003  | '[' array_expr_list ']'
 16004    {
 16005      $$.val = &tree.Array{Exprs: $2.exprs()}
 16006    }
 16007  
 16008  array_expr_list:
 16009    array_expr
 16010    {
 16011      $$.val = tree.Exprs{$1.expr()}
 16012    }
 16013  | array_expr_list ',' array_expr
 16014    {
 16015      $$.val = append($1.exprs(), $3.expr())
 16016    }
 16017  
 16018  extract_list:
 16019    extract_arg FROM a_expr
 16020    {
 16021      $$.val = tree.Exprs{tree.NewStrVal(strings.ToLower($1)), $3.expr()}
 16022    }
 16023  | expr_list
 16024    {
 16025      $$.val = $1.exprs()
 16026    }
 16027  
 16028  // TODO(vivek): Narrow down to just IDENT once the other
 16029  // terms are not keywords.
 16030  extract_arg:
 16031    IDENT
 16032  | YEAR
 16033  | MONTH
 16034  | DAY
 16035  | HOUR
 16036  | MINUTE
 16037  | SECOND
 16038  | SCONST
 16039  
 16040  // OVERLAY() arguments
 16041  // SQL99 defines the OVERLAY() function:
 16042  //   - overlay(text placing text from int for int)
 16043  //   - overlay(text placing text from int)
 16044  // and similarly for binary strings
 16045  overlay_list:
 16046    a_expr overlay_placing substr_from substr_for
 16047    {
 16048      $$.val = tree.Exprs{$1.expr(), $2.expr(), $3.expr(), $4.expr()}
 16049    }
 16050  | a_expr overlay_placing substr_from
 16051    {
 16052      $$.val = tree.Exprs{$1.expr(), $2.expr(), $3.expr()}
 16053    }
 16054  | expr_list
 16055    {
 16056      $$.val = $1.exprs()
 16057    }
 16058  
 16059  overlay_placing:
 16060    PLACING a_expr
 16061    {
 16062      $$.val = $2.expr()
 16063    }
 16064  
 16065  // position_list uses b_expr not a_expr to avoid conflict with general IN
 16066  position_list:
 16067    b_expr IN b_expr
 16068    {
 16069      $$.val = tree.Exprs{$3.expr(), $1.expr()}
 16070    }
 16071  | /* EMPTY */
 16072    {
 16073      $$.val = tree.Exprs(nil)
 16074    }
 16075  
 16076  // SUBSTRING() arguments
 16077  // SQL9x defines a specific syntax for arguments to SUBSTRING():
 16078  //   - substring(text from int for int)
 16079  //   - substring(text from int) get entire string from starting point "int"
 16080  //   - substring(text for int) get first "int" characters of string
 16081  //   - substring(text from pattern) get entire string matching pattern
 16082  //   - substring(text from pattern for escape) same with specified escape char
 16083  // We also want to support generic substring functions which accept
 16084  // the usual generic list of arguments. So we will accept both styles
 16085  // here, and convert the SQL9x style to the generic list for further
 16086  // processing. - thomas 2000-11-28
 16087  substr_list:
 16088    a_expr substr_from substr_for
 16089    {
 16090      $$.val = tree.Exprs{$1.expr(), $2.expr(), $3.expr()}
 16091    }
 16092  | a_expr substr_for substr_from
 16093    {
 16094      $$.val = tree.Exprs{$1.expr(), $3.expr(), $2.expr()}
 16095    }
 16096  | a_expr substr_from
 16097    {
 16098      $$.val = tree.Exprs{$1.expr(), $2.expr()}
 16099    }
 16100  | a_expr substr_for
 16101    {
 16102      $$.val = tree.Exprs{$1.expr(), tree.NewDInt(1), $2.expr()}
 16103    }
 16104  | opt_expr_list
 16105    {
 16106      $$.val = $1.exprs()
 16107    }
 16108  
 16109  substr_from:
 16110    FROM a_expr
 16111    {
 16112      $$.val = $2.expr()
 16113    }
 16114  
 16115  substr_for:
 16116    FOR a_expr
 16117    {
 16118      $$.val = $2.expr()
 16119    }
 16120  
 16121  trim_list:
 16122    a_expr FROM expr_list
 16123    {
 16124      $$.val = append($3.exprs(), $1.expr())
 16125    }
 16126  | FROM expr_list
 16127    {
 16128      $$.val = $2.exprs()
 16129    }
 16130  | expr_list
 16131    {
 16132      $$.val = $1.exprs()
 16133    }
 16134  
 16135  in_expr:
 16136    select_with_parens
 16137    {
 16138      $$.val = &tree.Subquery{Select: $1.selectStmt()}
 16139    }
 16140  | expr_tuple1_ambiguous
 16141  
 16142  // Define SQL-style CASE clause.
 16143  // - Full specification
 16144  //      CASE WHEN a = b THEN c ... ELSE d END
 16145  // - Implicit argument
 16146  //      CASE a WHEN b THEN c ... ELSE d END
 16147  case_expr:
 16148    CASE case_arg when_clause_list case_default END
 16149    {
 16150      $$.val = &tree.CaseExpr{Expr: $2.expr(), Whens: $3.whens(), Else: $4.expr()}
 16151    }
 16152  
 16153  when_clause_list:
 16154    // There must be at least one
 16155    when_clause
 16156    {
 16157      $$.val = []*tree.When{$1.when()}
 16158    }
 16159  | when_clause_list when_clause
 16160    {
 16161      $$.val = append($1.whens(), $2.when())
 16162    }
 16163  
 16164  when_clause:
 16165    WHEN a_expr THEN a_expr
 16166    {
 16167      $$.val = &tree.When{Cond: $2.expr(), Val: $4.expr()}
 16168    }
 16169  
 16170  case_default:
 16171    ELSE a_expr
 16172    {
 16173      $$.val = $2.expr()
 16174    }
 16175  | /* EMPTY */
 16176    {
 16177      $$.val = tree.Expr(nil)
 16178    }
 16179  
 16180  case_arg:
 16181    a_expr
 16182  | /* EMPTY */
 16183    {
 16184      $$.val = tree.Expr(nil)
 16185    }
 16186  
 16187  array_subscript:
 16188    '[' a_expr ']'
 16189    {
 16190      $$.val = &tree.ArraySubscript{Begin: $2.expr()}
 16191    }
 16192  | '[' opt_slice_bound ':' opt_slice_bound ']'
 16193    {
 16194      $$.val = &tree.ArraySubscript{Begin: $2.expr(), End: $4.expr(), Slice: true}
 16195    }
 16196  
 16197  opt_slice_bound:
 16198    a_expr
 16199  | /*EMPTY*/
 16200    {
 16201      $$.val = tree.Expr(nil)
 16202    }
 16203  
 16204  array_subscripts:
 16205    array_subscript
 16206    {
 16207      $$.val = tree.ArraySubscripts{$1.arraySubscript()}
 16208    }
 16209  | array_subscripts array_subscript
 16210    {
 16211      $$.val = append($1.arraySubscripts(), $2.arraySubscript())
 16212    }
 16213  
 16214  opt_asymmetric:
 16215    ASYMMETRIC {}
 16216  | /* EMPTY */ {}
 16217  
 16218  target_list:
 16219    target_elem
 16220    {
 16221      $$.val = tree.SelectExprs{$1.selExpr()}
 16222    }
 16223  | target_list ',' target_elem
 16224    {
 16225      $$.val = append($1.selExprs(), $3.selExpr())
 16226    }
 16227  
 16228  target_elem:
 16229    a_expr AS target_name
 16230    {
 16231      $$.val = tree.SelectExpr{Expr: $1.expr(), As: tree.UnrestrictedName($3)}
 16232    }
 16233    // We support omitting AS only for column labels that aren't any known
 16234    // keyword. There is an ambiguity against postfix operators: is "a ! b" an
 16235    // infix expression, or a postfix expression and a column label?  We prefer
 16236    // to resolve this as an infix expression, which we accomplish by assigning
 16237    // IDENT a precedence higher than POSTFIXOP.
 16238  | a_expr bare_col_label
 16239    {
 16240      $$.val = tree.SelectExpr{Expr: $1.expr(), As: tree.UnrestrictedName($2)}
 16241    }
 16242  | a_expr
 16243    {
 16244      $$.val = tree.SelectExpr{Expr: $1.expr()}
 16245    }
 16246  | '*'
 16247    {
 16248      $$.val = tree.StarSelectExpr()
 16249    }
 16250  
 16251  bare_col_label:
 16252    IDENT
 16253  | bare_label_keywords
 16254  
 16255  // Names and constants.
 16256  
 16257  table_index_name_list:
 16258    table_index_name
 16259    {
 16260      $$.val = tree.TableIndexNames{$1.newTableIndexName()}
 16261    }
 16262  | table_index_name_list ',' table_index_name
 16263    {
 16264      $$.val = append($1.newTableIndexNames(), $3.newTableIndexName())
 16265    }
 16266  
 16267  table_pattern_list:
 16268    table_pattern
 16269    {
 16270      $$.val = tree.TablePatterns{$1.unresolvedName()}
 16271    }
 16272  | table_pattern_list ',' table_pattern
 16273    {
 16274      $$.val = append($1.tablePatterns(), $3.unresolvedName())
 16275    }
 16276  
 16277  // An index can be specified in a few different ways:
 16278  //
 16279  //   - with explicit table name:
 16280  //       <table>@<index>
 16281  //       <schema>.<table>@<index>
 16282  //       <catalog/db>.<table>@<index>
 16283  //       <catalog/db>.<schema>.<table>@<index>
 16284  //
 16285  //   - without explicit table name:
 16286  //       <index>
 16287  //       <schema>.<index>
 16288  //       <catalog/db>.<index>
 16289  //       <catalog/db>.<schema>.<index>
 16290  table_index_name:
 16291    table_name '@' index_name
 16292    {
 16293      name := $1.unresolvedObjectName().ToTableName()
 16294      $$.val = tree.TableIndexName{
 16295         Table: name,
 16296         Index: tree.UnrestrictedName($3),
 16297      }
 16298    }
 16299  | standalone_index_name
 16300    {
 16301      // Treat it as a table name, then pluck out the ObjectName.
 16302      name := $1.unresolvedObjectName().ToTableName()
 16303      indexName := tree.UnrestrictedName(name.ObjectName)
 16304      name.ObjectName = ""
 16305      $$.val = tree.TableIndexName{
 16306          Table: name,
 16307          Index: indexName,
 16308      }
 16309    }
 16310  
 16311  // table_pattern selects zero or more tables using a wildcard.
 16312  // Accepted patterns:
 16313  // - Patterns accepted by db_object_name
 16314  //   <table>
 16315  //   <schema>.<table>
 16316  //   <catalog/db>.<schema>.<table>
 16317  // - Wildcards:
 16318  //   <db/catalog>.<schema>.*
 16319  //   <schema>.*
 16320  //   *
 16321  table_pattern:
 16322    simple_db_object_name
 16323    {
 16324       $$.val = $1.unresolvedObjectName().ToUnresolvedName()
 16325    }
 16326  | complex_table_pattern
 16327  
 16328  // complex_table_pattern is the part of table_pattern which recognizes
 16329  // every pattern not composed of a single identifier.
 16330  complex_table_pattern:
 16331    complex_db_object_name
 16332    {
 16333       $$.val = $1.unresolvedObjectName().ToUnresolvedName()
 16334    }
 16335  | db_object_name_component '.' unrestricted_name '.' '*'
 16336    {
 16337       $$.val = &tree.UnresolvedName{Star: true, NumParts: 3, Parts: tree.NameParts{"", $3, $1}}
 16338    }
 16339  | db_object_name_component '.' '*'
 16340    {
 16341       $$.val = &tree.UnresolvedName{Star: true, NumParts: 2, Parts: tree.NameParts{"", $1}}
 16342    }
 16343  | '*'
 16344    {
 16345       $$.val = &tree.UnresolvedName{Star: true, NumParts: 1}
 16346    }
 16347  
 16348  name_list:
 16349    name
 16350    {
 16351      $$.val = tree.NameList{tree.Name($1)}
 16352    }
 16353  | name_list ',' name
 16354    {
 16355      $$.val = append($1.nameList(), tree.Name($3))
 16356    }
 16357  
 16358  // Constants
 16359  numeric_only:
 16360    signed_iconst
 16361  | signed_fconst
 16362  
 16363  signed_iconst:
 16364    ICONST
 16365  | only_signed_iconst
 16366  
 16367  only_signed_iconst:
 16368    '+' ICONST
 16369    {
 16370      $$.val = $2.numVal()
 16371    }
 16372  | '-' ICONST
 16373    {
 16374      n := $2.numVal()
 16375      n.SetNegative()
 16376      $$.val = n
 16377    }
 16378  
 16379  signed_fconst:
 16380    FCONST
 16381  | only_signed_fconst
 16382  
 16383  only_signed_fconst:
 16384    '+' FCONST
 16385    {
 16386      $$.val = $2.numVal()
 16387    }
 16388  | '-' FCONST
 16389    {
 16390      n := $2.numVal()
 16391      n.SetNegative()
 16392      $$.val = n
 16393    }
 16394  
 16395  // iconst32 accepts only unsigned integer literals that fit in an int32.
 16396  iconst32:
 16397    ICONST
 16398    {
 16399      val, err := $1.numVal().AsInt32()
 16400      if err != nil { return setErr(sqllex, err) }
 16401      $$.val = val
 16402    }
 16403  
 16404  // signed_iconst64 is a variant of signed_iconst which only accepts (signed) integer literals that fit in an int64.
 16405  // If you use signed_iconst, you have to call AsInt64(), which returns an error if the value is too big.
 16406  // This rule just doesn't match in that case.
 16407  signed_iconst64:
 16408    signed_iconst
 16409    {
 16410      val, err := $1.numVal().AsInt64()
 16411      if err != nil { return setErr(sqllex, err) }
 16412      $$.val = val
 16413    }
 16414  
 16415  // iconst64 accepts only unsigned integer literals that fit in an int64.
 16416  iconst64:
 16417    ICONST
 16418    {
 16419      val, err := $1.numVal().AsInt64()
 16420      if err != nil { return setErr(sqllex, err) }
 16421      $$.val = val
 16422    }
 16423  
 16424  interval_value:
 16425    INTERVAL SCONST opt_interval_qualifier
 16426    {
 16427      var t *types.T
 16428      if $3.val == nil {
 16429        t = types.Interval
 16430      } else {
 16431        t = types.MakeInterval($3.intervalTypeMetadata())
 16432      }
 16433      $$.val = &tree.CastExpr{
 16434        Expr: tree.NewStrVal($2),
 16435        Type: t,
 16436        // TODO(#sql-sessions): This should be CastPrepend, but
 16437        // that does not work with parenthesized expressions
 16438        // (using FmtAlwaysGroupExprs).
 16439        SyntaxMode: tree.CastShort,
 16440      }
 16441    }
 16442  | INTERVAL '(' iconst32 ')' SCONST
 16443    {
 16444      prec := $3.int32()
 16445      if prec < 0 || prec > 6 {
 16446        sqllex.Error(fmt.Sprintf("precision %d out of range", prec))
 16447        return 1
 16448      }
 16449      $$.val = &tree.CastExpr{
 16450        Expr: tree.NewStrVal($5),
 16451        Type: types.MakeInterval(
 16452          types.IntervalTypeMetadata{Precision: prec, PrecisionIsSet: true},
 16453        ),
 16454        // TODO(#sql-sessions): This should be CastPrepend, but
 16455        // that does not work with parenthesized expressions
 16456        // (using FmtAlwaysGroupExprs).
 16457        SyntaxMode: tree.CastShort,
 16458      }
 16459    }
 16460  
 16461  // Name classification hierarchy.
 16462  //
 16463  // IDENT is the lexeme returned by the lexer for identifiers that match no
 16464  // known keyword. In most cases, we can accept certain keywords as names, not
 16465  // only IDENTs. We prefer to accept as many such keywords as possible to
 16466  // minimize the impact of "reserved words" on programmers. So, we divide names
 16467  // into several possible classes. The classification is chosen in part to make
 16468  // keywords acceptable as names wherever possible.
 16469  
 16470  // Names specific to syntactic positions.
 16471  //
 16472  // The non-terminals "name", "unrestricted_name", "non_reserved_word",
 16473  // "unreserved_keyword", "non_reserved_word_or_sconst" etc. defined
 16474  // below are low-level, structural constructs.
 16475  //
 16476  // They are separate only because having them all as one rule would
 16477  // make the rest of the grammar ambiguous. However, because they are
 16478  // separate the question is then raised throughout the rest of the
 16479  // grammar: which of the name non-terminals should one use when
 16480  // defining a grammar rule?  Is an index a "name" or
 16481  // "unrestricted_name"? A partition? What about an index option?
 16482  //
 16483  // To make the decision easier, this section of the grammar creates
 16484  // meaningful, purpose-specific aliases to the non-terminals. These
 16485  // both make it easier to decide "which one should I use in this
 16486  // context" and also improves the readability of
 16487  // automatically-generated syntax diagrams.
 16488  
 16489  // Note: newlines between non-terminals matter to the doc generator.
 16490  
 16491  collation_name:        unrestricted_name
 16492  
 16493  partition_name:        unrestricted_name
 16494  
 16495  index_name:            unrestricted_name
 16496  
 16497  opt_index_name:        opt_name
 16498  
 16499  zone_name:             unrestricted_name
 16500  
 16501  target_name:           unrestricted_name
 16502  
 16503  constraint_name:       name
 16504  
 16505  database_name:         name
 16506  
 16507  column_name:           name
 16508  
 16509  family_name:           name
 16510  
 16511  opt_family_name:       opt_name
 16512  
 16513  table_alias_name:      name
 16514  
 16515  statistics_name:       name
 16516  
 16517  window_name:           name
 16518  
 16519  view_name:             table_name
 16520  
 16521  type_name:             db_object_name
 16522  
 16523  sequence_name:         db_object_name
 16524  
 16525  region_name:
 16526    name
 16527  | SCONST
 16528  
 16529  region_name_list:
 16530    region_name
 16531    {
 16532      $$.val = tree.NameList{tree.Name($1)}
 16533    }
 16534  | region_name_list ',' region_name
 16535    {
 16536      $$.val = append($1.nameList(), tree.Name($3))
 16537    }
 16538  
 16539  schema_name:           name
 16540  
 16541  qualifiable_schema_name:
 16542  	name
 16543  	{
 16544  		$$.val = tree.ObjectNamePrefix{SchemaName: tree.Name($1), ExplicitSchema: true}
 16545  	}
 16546  | name '.' name
 16547  	{
 16548  		$$.val = tree.ObjectNamePrefix{CatalogName: tree.Name($1), SchemaName: tree.Name($3), ExplicitCatalog: true, ExplicitSchema: true}
 16549  	}
 16550  
 16551  schema_name_list:
 16552    qualifiable_schema_name
 16553    {
 16554      $$.val = tree.ObjectNamePrefixList{$1.objectNamePrefix()}
 16555    }
 16556  | schema_name_list ',' qualifiable_schema_name
 16557    {
 16558      $$.val = append($1.objectNamePrefixList(), $3.objectNamePrefix())
 16559    }
 16560  
 16561  schema_wildcard:
 16562  	wildcard_pattern
 16563  	{
 16564      $$.val = tree.ObjectNamePrefixList{$1.objectNamePrefix()}
 16565  	}
 16566  
 16567  wildcard_pattern:
 16568  	name '.' '*'
 16569  	{
 16570  		$$.val = tree.ObjectNamePrefix{CatalogName: tree.Name($1), SchemaName: tree.Name('*'), ExplicitCatalog: true, ExplicitSchema: true}
 16571  	}
 16572  
 16573  opt_schema_name:
 16574  	qualifiable_schema_name
 16575  | /* EMPTY */
 16576  	{
 16577  		$$.val = tree.ObjectNamePrefix{ExplicitSchema: false}
 16578  	}
 16579  
 16580  table_name:            db_object_name
 16581  
 16582  db_name:               db_object_name
 16583  
 16584  standalone_index_name: db_object_name
 16585  
 16586  explain_option_name:   non_reserved_word
 16587  
 16588  cursor_name:           name
 16589  
 16590  // Names for column references.
 16591  // Accepted patterns:
 16592  // <colname>
 16593  // <table>.<colname>
 16594  // <schema>.<table>.<colname>
 16595  // <catalog/db>.<schema>.<table>.<colname>
 16596  //
 16597  // Note: the rule for accessing compound types, if those are ever
 16598  // supported, is not to be handled here. The syntax `a.b.c.d....y.z`
 16599  // in `select a.b.c.d from t` *always* designates a column `z` in a
 16600  // table `y`, regardless of the meaning of what's before.
 16601  column_path:
 16602    name
 16603    {
 16604        $$.val = &tree.UnresolvedName{NumParts:1, Parts: tree.NameParts{$1}}
 16605    }
 16606  | prefixed_column_path
 16607  
 16608  prefixed_column_path:
 16609    db_object_name_component '.' unrestricted_name
 16610    {
 16611        $$.val = &tree.UnresolvedName{NumParts:2, Parts: tree.NameParts{$3,$1}}
 16612    }
 16613  | db_object_name_component '.' unrestricted_name '.' unrestricted_name
 16614    {
 16615        $$.val = &tree.UnresolvedName{NumParts:3, Parts: tree.NameParts{$5,$3,$1}}
 16616    }
 16617  | db_object_name_component '.' unrestricted_name '.' unrestricted_name '.' unrestricted_name
 16618    {
 16619        $$.val = &tree.UnresolvedName{NumParts:4, Parts: tree.NameParts{$7,$5,$3,$1}}
 16620    }
 16621  
 16622  // Names for column references and wildcards.
 16623  // Accepted patterns:
 16624  // - those from column_path
 16625  // - <table>.*
 16626  // - <schema>.<table>.*
 16627  // - <catalog/db>.<schema>.<table>.*
 16628  // The single unqualified star is handled separately by target_elem.
 16629  column_path_with_star:
 16630    column_path
 16631  | db_object_name_component '.' unrestricted_name '.' unrestricted_name '.' '*'
 16632    {
 16633      $$.val = &tree.UnresolvedName{Star:true, NumParts:4, Parts: tree.NameParts{"",$5,$3,$1}}
 16634    }
 16635  | db_object_name_component '.' unrestricted_name '.' '*'
 16636    {
 16637      $$.val = &tree.UnresolvedName{Star:true, NumParts:3, Parts: tree.NameParts{"",$3,$1}}
 16638    }
 16639  | db_object_name_component '.' '*'
 16640    {
 16641      $$.val = &tree.UnresolvedName{Star:true, NumParts:2, Parts: tree.NameParts{"",$1}}
 16642    }
 16643  
 16644  // Names for functions.
 16645  // The production for a qualified func_name has to exactly match the production
 16646  // for a column_path, because we cannot tell which we are parsing until
 16647  // we see what comes after it ('(' or SCONST for a func_name, anything else for
 16648  // a name).
 16649  // However we cannot use column_path directly, because for a single function name
 16650  // we allow more possible tokens than a simple column name.
 16651  func_name:
 16652    type_function_name
 16653    {
 16654      $$.val = &tree.UnresolvedName{NumParts:1, Parts: tree.NameParts{$1}}
 16655    }
 16656  | prefixed_column_path
 16657  | INDEX_BEFORE_PAREN
 16658    {
 16659      $$.val = &tree.UnresolvedName{NumParts:1, Parts: tree.NameParts{$1}}
 16660    }
 16661  
 16662  // func_name_no_crdb_extra is the same rule as func_name, but does not
 16663  // contain some CRDB specific keywords like FAMILY.
 16664  func_name_no_crdb_extra:
 16665    type_function_name_no_crdb_extra
 16666    {
 16667      $$.val = &tree.UnresolvedName{NumParts:1, Parts: tree.NameParts{$1}}
 16668    }
 16669  | prefixed_column_path
 16670  
 16671  // Names for database objects (tables, sequences, views, stored functions).
 16672  // Accepted patterns:
 16673  // <table>
 16674  // <schema>.<table>
 16675  // <catalog/db>.<schema>.<table>
 16676  db_object_name:
 16677    simple_db_object_name
 16678  | complex_db_object_name
 16679  
 16680  // simple_db_object_name is the part of db_object_name that recognizes
 16681  // simple identifiers.
 16682  simple_db_object_name:
 16683    db_object_name_component
 16684    {
 16685      aIdx := sqllex.(*lexer).NewAnnotation()
 16686      res, err := tree.NewUnresolvedObjectName(1, [3]string{$1}, aIdx)
 16687      if err != nil { return setErr(sqllex, err) }
 16688      $$.val = res
 16689    }
 16690  
 16691  // complex_db_object_name is the part of db_object_name that recognizes
 16692  // composite names (not simple identifiers).
 16693  // It is split away from db_object_name in order to enable the definition
 16694  // of table_pattern.
 16695  complex_db_object_name:
 16696    db_object_name_component '.' unrestricted_name
 16697    {
 16698      aIdx := sqllex.(*lexer).NewAnnotation()
 16699      res, err := tree.NewUnresolvedObjectName(2, [3]string{$3, $1}, aIdx)
 16700      if err != nil { return setErr(sqllex, err) }
 16701      $$.val = res
 16702    }
 16703  | db_object_name_component '.' unrestricted_name '.' unrestricted_name
 16704    {
 16705      aIdx := sqllex.(*lexer).NewAnnotation()
 16706      res, err := tree.NewUnresolvedObjectName(3, [3]string{$5, $3, $1}, aIdx)
 16707      if err != nil { return setErr(sqllex, err) }
 16708      $$.val = res
 16709    }
 16710  
 16711  // DB object name component -- this cannot not include any reserved
 16712  // keyword because of ambiguity after FROM, but we've been too lax
 16713  // with reserved keywords and made INDEX and FAMILY reserved, so we're
 16714  // trying to gain them back here.
 16715  db_object_name_component:
 16716    name
 16717  | type_func_name_crdb_extra_keyword
 16718  | cockroachdb_extra_reserved_keyword
 16719  
 16720  // General name --- names that can be column, table, etc names.
 16721  name:
 16722    IDENT
 16723  | unreserved_keyword
 16724  | col_name_keyword
 16725  
 16726  opt_name:
 16727    name
 16728  | /* EMPTY */
 16729    {
 16730      $$ = ""
 16731    }
 16732  
 16733  opt_name_parens:
 16734    '(' name ')'
 16735    {
 16736      $$ = $2
 16737    }
 16738  | /* EMPTY */
 16739    {
 16740      $$ = ""
 16741    }
 16742  
 16743  // Structural, low-level names
 16744  
 16745  // Non-reserved word and also string literal constants.
 16746  non_reserved_word_or_sconst:
 16747    non_reserved_word
 16748  | SCONST
 16749  
 16750  // Type/function identifier --- names that can be type or function names.
 16751  type_function_name:
 16752    IDENT
 16753  | unreserved_keyword
 16754  | type_func_name_keyword
 16755  
 16756  // Type/function identifier without CRDB extra reserved keywords.
 16757  type_function_name_no_crdb_extra:
 16758    IDENT
 16759  | unreserved_keyword
 16760  | type_func_name_no_crdb_extra_keyword
 16761  
 16762  param_name:
 16763    type_function_name
 16764  
 16765  // Any not-fully-reserved word --- these names can be, eg, variable names.
 16766  non_reserved_word:
 16767    IDENT
 16768  | unreserved_keyword
 16769  | col_name_keyword
 16770  | type_func_name_keyword
 16771  
 16772  // Unrestricted name --- allowable names when there is no ambiguity with even
 16773  // reserved keywords, like in "AS" clauses. This presently includes *all*
 16774  // Postgres keywords.
 16775  unrestricted_name:
 16776    IDENT
 16777  | unreserved_keyword
 16778  | col_name_keyword
 16779  | type_func_name_keyword
 16780  | reserved_keyword
 16781  
 16782  // Keyword category lists. Generally, every keyword present in the Postgres
 16783  // grammar should appear in exactly one of these "x_keyword" lists.
 16784  //
 16785  // Put a new keyword into the first list that it can go into without causing
 16786  // shift or reduce conflicts. The earlier lists define "less reserved"
 16787  // categories of keywords.
 16788  //
 16789  // Note: also add the **new** keyword to `bare_label_keywords` list to not break
 16790  // user queries using column label without `AS`.
 16791  // "Unreserved" keywords --- available for use as any kind of name.
 16792  unreserved_keyword:
 16793    ABORT
 16794  | ABSOLUTE
 16795  | ACTION
 16796  | ACCESS
 16797  | ADD
 16798  | ADMIN
 16799  | AFTER
 16800  | AGGREGATE
 16801  | ALTER
 16802  | ALWAYS
 16803  | ASENSITIVE
 16804  | AS_JSON
 16805  | AT
 16806  | ATOMIC
 16807  | ATTRIBUTE
 16808  | AUTOMATIC
 16809  | AVAILABILITY
 16810  | BACKUP
 16811  | BACKUPS
 16812  | BACKWARD
 16813  | BATCH
 16814  | BEFORE
 16815  | BEGIN
 16816  | BINARY
 16817  | BUCKET_COUNT
 16818  | BUNDLE
 16819  | BY
 16820  | CACHE
 16821  | CALL
 16822  | CALLED
 16823  | CANCEL
 16824  | CANCELQUERY
 16825  | CAPABILITIES
 16826  | CAPABILITY
 16827  | CASCADE
 16828  | CHANGEFEED
 16829  | CHECK_FILES
 16830  | CLOSE
 16831  | CLUSTER
 16832  | CLUSTERS
 16833  | COLUMNS
 16834  | COMMENT
 16835  | COMMENTS
 16836  | COMMIT
 16837  | COMMITTED
 16838  | COMPACT
 16839  | COMPLETE
 16840  | COMPLETIONS
 16841  | CONFLICT
 16842  | CONFIGURATION
 16843  | CONFIGURATIONS
 16844  | CONFIGURE
 16845  | CONNECTION
 16846  | CONNECTIONS
 16847  | CONSTRAINTS
 16848  | CONTROLCHANGEFEED
 16849  | CONTROLJOB
 16850  | CONVERSION
 16851  | CONVERT
 16852  | COPY
 16853  | COST
 16854  | COVERING
 16855  | CREATEDB
 16856  | CREATELOGIN
 16857  | CREATEROLE
 16858  | CSV
 16859  | CUBE
 16860  | CURRENT
 16861  | CURSOR
 16862  | CYCLE
 16863  | DATA
 16864  | DATABASE
 16865  | DATABASES
 16866  | DAY
 16867  | DEALLOCATE
 16868  | DEBUG_IDS
 16869  | DEBUG_PAUSE_ON
 16870  | DEBUG_DUMP_METADATA_SST
 16871  | DECLARE
 16872  | DELETE
 16873  | DEFAULTS
 16874  | DEFERRED
 16875  | DEFINER
 16876  | DELIMITER
 16877  | DEPENDS
 16878  | DESTINATION
 16879  | DETACHED
 16880  | DETAILS
 16881  | DISCARD
 16882  | DOMAIN
 16883  | DOUBLE
 16884  | DROP
 16885  | ENCODING
 16886  | ENCRYPTED
 16887  | ENCRYPTION_PASSPHRASE
 16888  | ENCRYPTION_INFO_DIR
 16889  | ENUM
 16890  | ENUMS
 16891  | ESCAPE
 16892  | EXCLUDE
 16893  | EXCLUDING
 16894  | EXECUTE
 16895  | EXECUTION
 16896  | EXPERIMENTAL
 16897  | EXPERIMENTAL_AUDIT
 16898  | EXPERIMENTAL_FINGERPRINTS
 16899  | EXPERIMENTAL_RELOCATE
 16900  | EXPERIMENTAL_REPLICA
 16901  | EXPIRATION
 16902  | EXPLAIN
 16903  | EXPORT
 16904  | EXTENSION
 16905  | EXTERNAL
 16906  | EXTREMES
 16907  | FAILURE
 16908  | FILES
 16909  | FILTER
 16910  | FIRST
 16911  | FOLLOWING
 16912  | FORMAT
 16913  | FORCE
 16914  | FORCE_NOT_NULL
 16915  | FORCE_NULL
 16916  | FORCE_QUOTE
 16917  | FORCE_INDEX
 16918  | FORCE_ZIGZAG
 16919  | FORWARD
 16920  | FREEZE
 16921  | FUNCTION
 16922  | FUNCTIONS
 16923  | GENERATED
 16924  | GEOMETRYM
 16925  | GEOMETRYZ
 16926  | GEOMETRYZM
 16927  | GEOMETRYCOLLECTION
 16928  | GEOMETRYCOLLECTIONM
 16929  | GEOMETRYCOLLECTIONZ
 16930  | GEOMETRYCOLLECTIONZM
 16931  | GLOBAL
 16932  | GOAL
 16933  | GRANTEE
 16934  | GRANTS
 16935  | GROUPS
 16936  | HASH
 16937  | HEADER
 16938  | HIGH
 16939  | HISTOGRAM
 16940  | HOLD
 16941  | HOUR
 16942  | IDENTITY
 16943  | IMMEDIATE
 16944  | IMMUTABLE
 16945  | IMPORT
 16946  | INCLUDE
 16947  | INCLUDING
 16948  | INCLUDE_ALL_SECONDARY_TENANTS
 16949  | INCLUDE_ALL_VIRTUAL_CLUSTERS
 16950  | INCREMENT
 16951  | INCREMENTAL
 16952  | INCREMENTAL_LOCATION
 16953  | INDEX
 16954  | INDEXES
 16955  | INHERITS
 16956  | INJECT
 16957  | INPUT
 16958  | INSERT
 16959  | INTO_DB
 16960  | INVERTED
 16961  | INVISIBLE
 16962  | ISOLATION
 16963  | INVOKER
 16964  | JOB
 16965  | JOBS
 16966  | JSON
 16967  | KEY
 16968  | KEYS
 16969  | KMS
 16970  | KV
 16971  | LABEL
 16972  | LANGUAGE
 16973  | LAST
 16974  | LATEST
 16975  | LC_COLLATE
 16976  | LC_CTYPE
 16977  | LEAKPROOF
 16978  | LEASE
 16979  | LESS
 16980  | LEVEL
 16981  | LINESTRING
 16982  | LINESTRINGM
 16983  | LINESTRINGZ
 16984  | LINESTRINGZM
 16985  | LIST
 16986  | LOCAL
 16987  | LOCKED
 16988  | LOGIN
 16989  | LOCALITY
 16990  | LOOKUP
 16991  | LOW
 16992  | MATCH
 16993  | MATERIALIZED
 16994  | MAXVALUE
 16995  | MERGE
 16996  | METHOD
 16997  | MINUTE
 16998  | MINVALUE
 16999  | MODIFYCLUSTERSETTING
 17000  | MODIFYSQLCLUSTERSETTING
 17001  | MULTILINESTRING
 17002  | MULTILINESTRINGM
 17003  | MULTILINESTRINGZ
 17004  | MULTILINESTRINGZM
 17005  | MULTIPOINT
 17006  | MULTIPOINTM
 17007  | MULTIPOINTZ
 17008  | MULTIPOINTZM
 17009  | MULTIPOLYGON
 17010  | MULTIPOLYGONM
 17011  | MULTIPOLYGONZ
 17012  | MULTIPOLYGONZM
 17013  | MONTH
 17014  | MOVE
 17015  | NAMES
 17016  | NAN
 17017  | NEVER
 17018  | NEW_DB_NAME
 17019  | NEW_KMS
 17020  | NEXT
 17021  | NO
 17022  | NORMAL
 17023  | NOTHING
 17024  | NO_INDEX_JOIN
 17025  | NO_ZIGZAG_JOIN
 17026  | NO_FULL_SCAN
 17027  | NOCREATEDB
 17028  | NOCREATELOGIN
 17029  | NOCANCELQUERY
 17030  | NOCREATEROLE
 17031  | NOCONTROLCHANGEFEED
 17032  | NOCONTROLJOB
 17033  | NOLOGIN
 17034  | NOMODIFYCLUSTERSETTING
 17035  | NONVOTERS
 17036  | NOREPLICATION
 17037  | NOSQLLOGIN
 17038  | NOVIEWACTIVITY
 17039  | NOVIEWACTIVITYREDACTED
 17040  | NOVIEWCLUSTERSETTING
 17041  | NOWAIT
 17042  | NULLS
 17043  | IGNORE_FOREIGN_KEYS
 17044  | INSENSITIVE
 17045  | OF
 17046  | OFF
 17047  | OIDS
 17048  | OLD_KMS
 17049  | OPERATOR
 17050  | OPT
 17051  | OPTION
 17052  | OPTIONS
 17053  | ORDINALITY
 17054  | OTHERS
 17055  | OVER
 17056  | OWNED
 17057  | OWNER
 17058  | PARALLEL
 17059  | PARENT
 17060  | PARTIAL
 17061  | PARTITION
 17062  | PARTITIONS
 17063  | PASSWORD
 17064  | PAUSE
 17065  | PAUSED
 17066  | PHYSICAL
 17067  | PLACEMENT
 17068  | PLAN
 17069  | PLANS
 17070  | POINTM
 17071  | POINTZ
 17072  | POINTZM
 17073  | POLYGONM
 17074  | POLYGONZ
 17075  | POLYGONZM
 17076  | PRECEDING
 17077  | PREPARE
 17078  | PRESERVE
 17079  | PRIOR
 17080  | PRIORITY
 17081  | PRIVILEGES
 17082  | PROCEDURE
 17083  | PROCEDURES
 17084  | PUBLIC
 17085  | PUBLICATION
 17086  | QUERIES
 17087  | QUERY
 17088  | QUOTE
 17089  | RANGE
 17090  | RANGES
 17091  | READ
 17092  | REASON
 17093  | REASSIGN
 17094  | RECURRING
 17095  | RECURSIVE
 17096  | REDACT
 17097  | REF
 17098  | REFRESH
 17099  | REGION
 17100  | REGIONAL
 17101  | REGIONS
 17102  | REINDEX
 17103  | RELATIVE
 17104  | RELEASE
 17105  | RELOCATE
 17106  | REMOVE_REGIONS
 17107  | RENAME
 17108  | REPEATABLE
 17109  | REPLACE
 17110  | REPLICATION
 17111  | RESET
 17112  | RESTART
 17113  | RESTORE
 17114  | RESTRICT
 17115  | RESTRICTED
 17116  | RESUME
 17117  | RETENTION
 17118  | RETRY
 17119  | RETURN
 17120  | RETURNS
 17121  | REVISION_HISTORY
 17122  | REVOKE
 17123  | ROLE
 17124  | ROLES
 17125  | ROLLBACK
 17126  | ROLLUP
 17127  | ROUTINES
 17128  | ROWS
 17129  | RULE
 17130  | RUNNING
 17131  | SCHEDULE
 17132  | SCHEDULES
 17133  | SCHEMA_ONLY
 17134  | SCROLL
 17135  | SETTING
 17136  | SETTINGS
 17137  | STATUS
 17138  | SAVEPOINT
 17139  | SCANS
 17140  | SCATTER
 17141  | SCHEMA
 17142  | SCHEMAS
 17143  | SCRUB
 17144  | SEARCH
 17145  | SECOND
 17146  | SECURITY
 17147  | SECONDARY
 17148  | SERIALIZABLE
 17149  | SEQUENCE
 17150  | SEQUENCES
 17151  | SERVER
 17152  | SERVICE
 17153  | SESSION
 17154  | SESSIONS
 17155  | SET
 17156  | SETS
 17157  | SHARE
 17158  | SHARED
 17159  | SHOW
 17160  | SIMPLE
 17161  | SIZE
 17162  | SKIP
 17163  | SKIP_LOCALITIES_CHECK
 17164  | SKIP_MISSING_FOREIGN_KEYS
 17165  | SKIP_MISSING_SEQUENCES
 17166  | SKIP_MISSING_SEQUENCE_OWNERS
 17167  | SKIP_MISSING_VIEWS
 17168  | SKIP_MISSING_UDFS
 17169  | SNAPSHOT
 17170  | SPLIT
 17171  | SQL
 17172  | SQLLOGIN
 17173  | STABLE
 17174  | START
 17175  | STATE
 17176  | STATEMENTS
 17177  | STATISTICS
 17178  | STDIN
 17179  | STDOUT
 17180  | STOP
 17181  | STORAGE
 17182  | STORE
 17183  | STORED
 17184  | STORING
 17185  | STREAM
 17186  | STRICT
 17187  | SUBSCRIPTION
 17188  | SUPER
 17189  | SUPPORT
 17190  | SURVIVE
 17191  | SURVIVAL
 17192  | SYNTAX
 17193  | SYSTEM
 17194  | TABLES
 17195  | TABLESPACE
 17196  | TEMP
 17197  | TEMPLATE
 17198  | TEMPORARY
 17199  | TENANT
 17200  | TENANT_NAME
 17201  | TENANTS
 17202  | TESTING_RELOCATE
 17203  | TEXT
 17204  | TIES
 17205  | TRACE
 17206  | TRACING
 17207  | TRANSACTION
 17208  | TRANSACTIONS
 17209  | TRANSFER
 17210  | TRANSFORM
 17211  | TRIGGER
 17212  | TRUNCATE
 17213  | TRUSTED
 17214  | TYPE
 17215  | TYPES
 17216  | THROTTLING
 17217  | UNBOUNDED
 17218  | UNCOMMITTED
 17219  | UNKNOWN
 17220  | UNLISTEN
 17221  | UNLOGGED
 17222  | UNSAFE_RESTORE_INCOMPATIBLE_VERSION
 17223  | UNSET
 17224  | UNSPLIT
 17225  | UNTIL
 17226  | UPDATE
 17227  | UPDATES_CLUSTER_MONITORING_METRICS
 17228  | UPSERT
 17229  | USE
 17230  | USERS
 17231  | VALID
 17232  | VALIDATE
 17233  | VALUE
 17234  | VARYING
 17235  | VERIFY_BACKUP_TABLE_DATA
 17236  | VIEW
 17237  | VIEWACTIVITY
 17238  | VIEWACTIVITYREDACTED
 17239  | VIEWCLUSTERMETADATA
 17240  | VIEWCLUSTERSETTING
 17241  | VIEWDEBUG
 17242  | VIRTUAL_CLUSTER_NAME
 17243  | VIRTUAL_CLUSTER
 17244  | VISIBLE
 17245  | VISIBILITY
 17246  | VOLATILE
 17247  | VOTERS
 17248  | WITHIN
 17249  | WITHOUT
 17250  | WRITE
 17251  | YEAR
 17252  | ZONE
 17253  
 17254  // Column label --- keywords that can be column label that doesn't use "AS"
 17255  // before it. This is to guarantee that any new keyword won't break user
 17256  // query like "SELECT col label FROM tab" where "label" is a new keyword.
 17257  // Any new keyword should be added to this list.
 17258  bare_label_keywords:
 17259    ABORT
 17260  | ABSOLUTE
 17261  | ACCESS
 17262  | ACTION
 17263  | ADD
 17264  | ADMIN
 17265  | AFTER
 17266  | AGGREGATE
 17267  | ALL
 17268  | ALTER
 17269  | ALWAYS
 17270  | ANALYSE
 17271  | ANALYZE
 17272  | AND
 17273  | ANNOTATE_TYPE
 17274  | ANY
 17275  | ASC
 17276  | ASENSITIVE
 17277  | ASYMMETRIC
 17278  | AS_JSON
 17279  | AT
 17280  | ATOMIC
 17281  | ATTRIBUTE
 17282  | AUTHORIZATION
 17283  | AUTOMATIC
 17284  | AVAILABILITY
 17285  | BACKUP
 17286  | BACKUPS
 17287  | BACKWARD
 17288  | BATCH
 17289  | BEFORE
 17290  | BEGIN
 17291  | BETWEEN
 17292  | BIGINT
 17293  | BINARY
 17294  | BIT
 17295  | BOOLEAN
 17296  | BOTH
 17297  | BOX2D
 17298  | BUCKET_COUNT
 17299  | BUNDLE
 17300  | BY
 17301  | CACHE
 17302  | CALL
 17303  | CALLED
 17304  | CANCEL
 17305  | CANCELQUERY
 17306  | CAPABILITIES
 17307  | CAPABILITY
 17308  | CASCADE
 17309  | CASE
 17310  | CAST
 17311  | CHANGEFEED
 17312  | CHARACTERISTICS
 17313  | CHECK
 17314  | CHECK_FILES
 17315  | CLOSE
 17316  | CLUSTER
 17317  | CLUSTERS
 17318  | COALESCE
 17319  | COLLATION
 17320  | COLUMN
 17321  | COLUMNS
 17322  | COMMENT
 17323  | COMMENTS
 17324  | COMMIT
 17325  | COMMITTED
 17326  | COMPACT
 17327  | COMPLETE
 17328  | COMPLETIONS
 17329  | CONCURRENTLY
 17330  | CONFIGURATION
 17331  | CONFIGURATIONS
 17332  | CONFIGURE
 17333  | CONFLICT
 17334  | CONNECTION
 17335  | CONNECTIONS
 17336  | CONSTRAINT
 17337  | CONSTRAINTS
 17338  | CONTROLCHANGEFEED
 17339  | CONTROLJOB
 17340  | CONVERSION
 17341  | CONVERT
 17342  | COPY
 17343  | COST
 17344  | COVERING
 17345  | CREATEDB
 17346  | CREATELOGIN
 17347  | CREATEROLE
 17348  | CROSS
 17349  | CSV
 17350  | CUBE
 17351  | CURRENT
 17352  | CURRENT_CATALOG
 17353  | CURRENT_DATE
 17354  | CURRENT_ROLE
 17355  | CURRENT_SCHEMA
 17356  | CURRENT_TIME
 17357  | CURRENT_TIMESTAMP
 17358  | CURRENT_USER
 17359  | CURSOR
 17360  | CYCLE
 17361  | DATA
 17362  | DATABASE
 17363  | DATABASES
 17364  | DEALLOCATE
 17365  | DEBUG_DUMP_METADATA_SST
 17366  | DEBUG_IDS
 17367  | DEBUG_PAUSE_ON
 17368  | DEC
 17369  | DECIMAL
 17370  | DECLARE
 17371  | DEFAULT
 17372  | DEFAULTS
 17373  | DEFERRABLE
 17374  | DEFERRED
 17375  | DEFINER
 17376  | DELETE
 17377  | DELIMITER
 17378  | DEPENDS
 17379  | DESC
 17380  | DESTINATION
 17381  | DETACHED
 17382  | DETAILS
 17383  | DISCARD
 17384  | DISTINCT
 17385  | DO
 17386  | DOMAIN
 17387  | DOUBLE
 17388  | DROP
 17389  | ELSE
 17390  | ENCODING
 17391  | ENCRYPTED
 17392  | ENCRYPTION_INFO_DIR
 17393  | ENCRYPTION_PASSPHRASE
 17394  | END
 17395  | ENUM
 17396  | ENUMS
 17397  | ESCAPE
 17398  | EXCLUDE
 17399  | EXCLUDING
 17400  | EXECUTE
 17401  | EXECUTION
 17402  | EXISTS
 17403  | EXPERIMENTAL
 17404  | EXPERIMENTAL_AUDIT
 17405  | EXPERIMENTAL_FINGERPRINTS
 17406  | EXPERIMENTAL_RELOCATE
 17407  | EXPERIMENTAL_REPLICA
 17408  | EXPIRATION
 17409  | EXPLAIN
 17410  | EXPORT
 17411  | EXTENSION
 17412  | EXTERNAL
 17413  | EXTRACT
 17414  | EXTRACT_DURATION
 17415  | EXTREMES
 17416  | FAILURE
 17417  | FALSE
 17418  | FAMILY
 17419  | FILES
 17420  | FIRST
 17421  | FLOAT
 17422  | FOLLOWING
 17423  | FORCE
 17424  | FORCE_NOT_NULL
 17425  | FORCE_NULL
 17426  | FORCE_QUOTE
 17427  | FORCE_INDEX
 17428  | FORCE_ZIGZAG
 17429  | FOREIGN
 17430  | FORMAT
 17431  | FORWARD
 17432  | FREEZE
 17433  | FULL
 17434  | FUNCTION
 17435  | FUNCTIONS
 17436  | GENERATED
 17437  | GEOGRAPHY
 17438  | GEOMETRY
 17439  | GEOMETRYCOLLECTION
 17440  | GEOMETRYCOLLECTIONM
 17441  | GEOMETRYCOLLECTIONZ
 17442  | GEOMETRYCOLLECTIONZM
 17443  | GEOMETRYM
 17444  | GEOMETRYZ
 17445  | GEOMETRYZM
 17446  | GLOBAL
 17447  | GOAL
 17448  | GRANTEE
 17449  | GRANTS
 17450  | GREATEST
 17451  | GROUPING
 17452  | GROUPS
 17453  | HASH
 17454  | HEADER
 17455  | HIGH
 17456  | HISTOGRAM
 17457  | HOLD
 17458  | IDENTITY
 17459  | IF
 17460  | IFERROR
 17461  | IFNULL
 17462  | IGNORE_FOREIGN_KEYS
 17463  | ILIKE
 17464  | IMMEDIATE
 17465  | IMMUTABLE
 17466  | IMPORT
 17467  | IN
 17468  | INCLUDE
 17469  | INCLUDE_ALL_SECONDARY_TENANTS
 17470  | INCLUDE_ALL_VIRTUAL_CLUSTERS
 17471  | INCLUDING
 17472  | INCREMENT
 17473  | INCREMENTAL
 17474  | INCREMENTAL_LOCATION
 17475  | INDEX
 17476  | INDEXES
 17477  | INDEX_AFTER_ORDER_BY_BEFORE_AT
 17478  | INDEX_BEFORE_NAME_THEN_PAREN
 17479  | INDEX_BEFORE_PAREN
 17480  | INHERITS
 17481  | INITIALLY
 17482  | INJECT
 17483  | INNER
 17484  | INOUT
 17485  | INPUT
 17486  | INSENSITIVE
 17487  | INSERT
 17488  | INT
 17489  | INTEGER
 17490  | INTERVAL
 17491  | INTO_DB
 17492  | INVERTED
 17493  | INVISIBLE
 17494  | INVOKER
 17495  | IS
 17496  | ISERROR
 17497  | ISOLATION
 17498  | JOB
 17499  | JOBS
 17500  | JOIN
 17501  | JSON
 17502  | KEY
 17503  | KEYS
 17504  | KMS
 17505  | KV
 17506  | LABEL
 17507  | LANGUAGE
 17508  | LAST
 17509  | LATERAL
 17510  | LATEST
 17511  | LC_COLLATE
 17512  | LC_CTYPE
 17513  | LEADING
 17514  | LEAKPROOF
 17515  | LEASE
 17516  | LEAST
 17517  | LEFT
 17518  | LESS
 17519  | LEVEL
 17520  | LIKE
 17521  | LINESTRING
 17522  | LINESTRINGM
 17523  | LINESTRINGZ
 17524  | LINESTRINGZM
 17525  | LIST
 17526  | LOCAL
 17527  | LOCALITY
 17528  | LOCALTIME
 17529  | LOCALTIMESTAMP
 17530  | LOCKED
 17531  | LOGIN
 17532  | LOOKUP
 17533  | LOW
 17534  | MATCH
 17535  | MATERIALIZED
 17536  | MAXVALUE
 17537  | MERGE
 17538  | METHOD
 17539  | MINVALUE
 17540  | MODIFYCLUSTERSETTING
 17541  | MODIFYSQLCLUSTERSETTING
 17542  | MOVE
 17543  | MULTILINESTRING
 17544  | MULTILINESTRINGM
 17545  | MULTILINESTRINGZ
 17546  | MULTILINESTRINGZM
 17547  | MULTIPOINT
 17548  | MULTIPOINTM
 17549  | MULTIPOINTZ
 17550  | MULTIPOINTZM
 17551  | MULTIPOLYGON
 17552  | MULTIPOLYGONM
 17553  | MULTIPOLYGONZ
 17554  | MULTIPOLYGONZM
 17555  | NAMES
 17556  | NAN
 17557  | NATURAL
 17558  | NEVER
 17559  | NEW_DB_NAME
 17560  | NEW_KMS
 17561  | NEXT
 17562  | NO
 17563  | NOCANCELQUERY
 17564  | NOCONTROLCHANGEFEED
 17565  | NOCONTROLJOB
 17566  | NOCREATEDB
 17567  | NOCREATELOGIN
 17568  | NOCREATEROLE
 17569  | NOLOGIN
 17570  | NOMODIFYCLUSTERSETTING
 17571  | NONE
 17572  | NONVOTERS
 17573  | NORMAL
 17574  | NOREPLICATION
 17575  | NOSQLLOGIN
 17576  | NOT
 17577  | NOTHING
 17578  | NOTHING_AFTER_RETURNING
 17579  | NOVIEWACTIVITY
 17580  | NOVIEWACTIVITYREDACTED
 17581  | NOVIEWCLUSTERSETTING
 17582  | NOWAIT
 17583  | NO_FULL_SCAN
 17584  | NO_INDEX_JOIN
 17585  | NO_ZIGZAG_JOIN
 17586  | NULL
 17587  | NULLIF
 17588  | NULLS
 17589  | NUMERIC
 17590  | OF
 17591  | OFF
 17592  | OIDS
 17593  | OLD_KMS
 17594  | ONLY
 17595  | OPERATOR
 17596  | OPT
 17597  | OPTION
 17598  | OPTIONS
 17599  | OR
 17600  | ORDINALITY
 17601  | OTHERS
 17602  | OUT
 17603  | OUTER
 17604  | OVERLAY
 17605  | OWNED
 17606  | OWNER
 17607  | PARALLEL
 17608  | PARENT
 17609  | PARTIAL
 17610  | PARTITION
 17611  | PARTITIONS
 17612  | PASSWORD
 17613  | PAUSE
 17614  | PAUSED
 17615  | PHYSICAL
 17616  | PLACEMENT
 17617  | PLACING
 17618  | PLAN
 17619  | PLANS
 17620  | POINT
 17621  | POINTM
 17622  | POINTZ
 17623  | POINTZM
 17624  | POLYGON
 17625  | POLYGONM
 17626  | POLYGONZ
 17627  | POLYGONZM
 17628  | POSITION
 17629  | PRECEDING
 17630  | PREPARE
 17631  | PRESERVE
 17632  | PRIMARY
 17633  | PRIOR
 17634  | PRIORITY
 17635  | PRIVILEGES
 17636  | PROCEDURE
 17637  | PROCEDURES
 17638  | PUBLIC
 17639  | PUBLICATION
 17640  | QUERIES
 17641  | QUERY
 17642  | QUOTE
 17643  | RANGE
 17644  | RANGES
 17645  | READ
 17646  | REAL
 17647  | REASON
 17648  | REASSIGN
 17649  | RECURRING
 17650  | RECURSIVE
 17651  | REDACT
 17652  | REF
 17653  | REFERENCES
 17654  | REFRESH
 17655  | REGION
 17656  | REGIONAL
 17657  | REGIONS
 17658  | REINDEX
 17659  | RELATIVE
 17660  | RELEASE
 17661  | RELOCATE
 17662  | REMOVE_REGIONS
 17663  | RENAME
 17664  | REPEATABLE
 17665  | REPLACE
 17666  | REPLICATION
 17667  | RESET
 17668  | RESTART
 17669  | RESTORE
 17670  | RESTRICT
 17671  | RESTRICTED
 17672  | RESUME
 17673  | RETENTION
 17674  | RETRY
 17675  | RETURN
 17676  | RETURNS
 17677  | REVISION_HISTORY
 17678  | REVOKE
 17679  | RIGHT
 17680  | ROLE
 17681  | ROLES
 17682  | ROLLBACK
 17683  | ROLLUP
 17684  | ROUTINES
 17685  | ROW
 17686  | ROWS
 17687  | RULE
 17688  | RUNNING
 17689  | SAVEPOINT
 17690  | SCANS
 17691  | SCATTER
 17692  | SCHEDULE
 17693  | SCHEDULES
 17694  | SCHEMA
 17695  | SCHEMAS
 17696  | SCHEMA_ONLY
 17697  | SCROLL
 17698  | SCRUB
 17699  | SEARCH
 17700  | SECONDARY
 17701  | SECURITY
 17702  | SELECT
 17703  | SEQUENCE
 17704  | SEQUENCES
 17705  | SERIALIZABLE
 17706  | SERVER
 17707  | SERVICE
 17708  | SESSION
 17709  | SESSIONS
 17710  | SESSION_USER
 17711  | SET
 17712  | SETOF
 17713  | SETS
 17714  | SETTING
 17715  | SETTINGS
 17716  | SHARE
 17717  | SHARED
 17718  | SHOW
 17719  | SIMILAR
 17720  | SIMPLE
 17721  | SIZE
 17722  | SKIP
 17723  | SKIP_LOCALITIES_CHECK
 17724  | SKIP_MISSING_FOREIGN_KEYS
 17725  | SKIP_MISSING_SEQUENCES
 17726  | SKIP_MISSING_SEQUENCE_OWNERS
 17727  | SKIP_MISSING_UDFS
 17728  | SKIP_MISSING_VIEWS
 17729  | SMALLINT
 17730  | SNAPSHOT
 17731  | SOME
 17732  | SPLIT
 17733  | SQL
 17734  | SQLLOGIN
 17735  | STABLE
 17736  | START
 17737  | STATE
 17738  | STATEMENTS
 17739  | STATISTICS
 17740  | STATUS
 17741  | STDIN
 17742  | STDOUT
 17743  | STOP
 17744  | STORAGE
 17745  | STORE
 17746  | STORED
 17747  | STORING
 17748  | STREAM
 17749  | STRICT
 17750  | STRING
 17751  | SUBSCRIPTION
 17752  | SUBSTRING
 17753  | SUPER
 17754  | SUPPORT
 17755  | SURVIVAL
 17756  | SURVIVE
 17757  | SYMMETRIC
 17758  | SYNTAX
 17759  | SYSTEM
 17760  | TABLE
 17761  | TABLES
 17762  | TABLESPACE
 17763  | TEMP
 17764  | TEMPLATE
 17765  | TEMPORARY
 17766  | TENANT
 17767  | TENANTS
 17768  | TENANT_NAME
 17769  | TESTING_RELOCATE
 17770  | TEXT
 17771  | THEN
 17772  | THROTTLING
 17773  | TIES
 17774  | TIME
 17775  | TIMESTAMP
 17776  | TIMESTAMPTZ
 17777  | TIMETZ
 17778  | TRACE
 17779  | TRACING
 17780  | TRAILING
 17781  | TRANSACTION
 17782  | TRANSACTIONS
 17783  | TRANSFER
 17784  | TRANSFORM
 17785  | TREAT
 17786  | TRIGGER
 17787  | TRIM
 17788  | TRUE
 17789  | TRUNCATE
 17790  | TRUSTED
 17791  | TYPE
 17792  | TYPES
 17793  | UNBOUNDED
 17794  | UNCOMMITTED
 17795  | UNIQUE
 17796  | UNKNOWN
 17797  | UNLISTEN
 17798  | UNLOGGED
 17799  | UNSAFE_RESTORE_INCOMPATIBLE_VERSION
 17800  | UNSET
 17801  | UNSPLIT
 17802  | UNTIL
 17803  | UPDATE
 17804  | UPDATES_CLUSTER_MONITORING_METRICS
 17805  | UPSERT
 17806  | USE
 17807  | USER
 17808  | USERS
 17809  | USING
 17810  | VALID
 17811  | VALIDATE
 17812  | VALUE
 17813  | VALUES
 17814  | VARBIT
 17815  | VARCHAR
 17816  | VARIADIC
 17817  | VERIFY_BACKUP_TABLE_DATA
 17818  | VIEW
 17819  | VIEWACTIVITY
 17820  | VIEWACTIVITYREDACTED
 17821  | VIEWCLUSTERMETADATA
 17822  | VIEWCLUSTERSETTING
 17823  | VIEWDEBUG
 17824  | VIRTUAL
 17825  | VIRTUAL_CLUSTER_NAME
 17826  | VIRTUAL_CLUSTER
 17827  | VISIBLE
 17828  | VISIBILITY
 17829  | VOLATILE
 17830  | VOTERS
 17831  | WHEN
 17832  | WORK
 17833  | WRITE
 17834  | ZONE
 17835  
 17836  
 17837  // Column identifier --- keywords that can be column, table, etc names.
 17838  //
 17839  // Many of these keywords will in fact be recognized as type or function names
 17840  // too; but they have special productions for the purpose, and so can't be
 17841  // treated as "generic" type or function names.
 17842  //
 17843  // The type names appearing here are not usable as function names because they
 17844  // can be followed by '(' in typename productions, which looks too much like a
 17845  // function call for an LR(1) parser.
 17846  //
 17847  // Note: also add the new keyword to `bare_label` list to not break
 17848  // user queries using column label without `AS`.
 17849  col_name_keyword:
 17850    ANNOTATE_TYPE
 17851  | BETWEEN
 17852  | BIGINT
 17853  | BIT
 17854  | BOOLEAN
 17855  | BOX2D
 17856  | CHAR
 17857  | CHARACTER
 17858  | CHARACTERISTICS
 17859  | COALESCE
 17860  | DEC
 17861  | DECIMAL
 17862  | EXISTS
 17863  | EXTRACT
 17864  | EXTRACT_DURATION
 17865  | FLOAT
 17866  | GEOGRAPHY
 17867  | GEOMETRY
 17868  | GREATEST
 17869  | GROUPING
 17870  | IF
 17871  | IFERROR
 17872  | IFNULL
 17873  | INOUT
 17874  | INT
 17875  | INTEGER
 17876  | INTERVAL
 17877  | ISERROR
 17878  | LEAST
 17879  | NULLIF
 17880  | NUMERIC
 17881  | OUT
 17882  | OVERLAY
 17883  | POINT
 17884  | POLYGON
 17885  | POSITION
 17886  | PRECISION
 17887  | REAL
 17888  | ROW
 17889  | SETOF
 17890  | SMALLINT
 17891  | STRING
 17892  | SUBSTRING
 17893  | TIME
 17894  | TIMETZ
 17895  | TIMESTAMP
 17896  | TIMESTAMPTZ
 17897  | TREAT
 17898  | TRIM
 17899  | VALUES
 17900  | VARBIT
 17901  | VARCHAR
 17902  | VIRTUAL
 17903  | WORK
 17904  
 17905  // type_func_name_keyword contains both the standard set of
 17906  // type_func_name_keyword's along with the set of CRDB extensions.
 17907  type_func_name_keyword:
 17908    type_func_name_no_crdb_extra_keyword
 17909  | type_func_name_crdb_extra_keyword
 17910  
 17911  // Type/function identifier --- keywords that can be type or function names.
 17912  //
 17913  // Most of these are keywords that are used as operators in expressions; in
 17914  // general such keywords can't be column names because they would be ambiguous
 17915  // with variables, but they are unambiguous as function identifiers.
 17916  //
 17917  // Do not include POSITION, SUBSTRING, etc here since they have explicit
 17918  // productions in a_expr to support the goofy SQL9x argument syntax.
 17919  // - thomas 2000-11-28
 17920  //
 17921  // *** DO NOT ADD COCKROACHDB-SPECIFIC KEYWORDS HERE ***
 17922  //
 17923  // See type_func_name_crdb_extra_keyword below.
 17924  type_func_name_no_crdb_extra_keyword:
 17925    AUTHORIZATION
 17926  | COLLATION
 17927  | CROSS
 17928  | FULL
 17929  | INNER
 17930  | ILIKE
 17931  | IS
 17932  | ISNULL
 17933  | JOIN
 17934  | LEFT
 17935  | LIKE
 17936  | NATURAL
 17937  | NONE
 17938  | NOTNULL
 17939  | OUTER
 17940  | OVERLAPS
 17941  | RIGHT
 17942  | SIMILAR
 17943  
 17944  // CockroachDB-specific keywords that can be used in type/function
 17945  // identifiers.
 17946  //
 17947  // *** REFRAIN FROM ADDING KEYWORDS HERE ***
 17948  //
 17949  // Adding keywords here creates non-resolvable incompatibilities with
 17950  // postgres clients.
 17951  //
 17952  type_func_name_crdb_extra_keyword:
 17953    FAMILY
 17954  
 17955  // Reserved keyword --- these keywords are usable only as an unrestricted_name.
 17956  //
 17957  // Keywords appear here if they could not be distinguished from variable, type,
 17958  // or function names in some contexts.
 17959  //
 17960  // *** NEVER ADD KEYWORDS HERE ***
 17961  //
 17962  // See cockroachdb_extra_reserved_keyword below.
 17963  //
 17964  // Note: also add the new keyword to `bare_label` list to not break
 17965  // user queries using column label without `AS`.
 17966  reserved_keyword:
 17967    ALL
 17968  | ANALYSE
 17969  | ANALYZE
 17970  | AND
 17971  | ANY
 17972  | ARRAY
 17973  | AS
 17974  | ASC
 17975  | ASYMMETRIC
 17976  | BOTH
 17977  | CASE
 17978  | CAST
 17979  | CHECK
 17980  | COLLATE
 17981  | COLUMN
 17982  | CONCURRENTLY
 17983  | CONSTRAINT
 17984  | CREATE
 17985  | CURRENT_CATALOG
 17986  | CURRENT_DATE
 17987  | CURRENT_ROLE
 17988  | CURRENT_SCHEMA
 17989  | CURRENT_TIME
 17990  | CURRENT_TIMESTAMP
 17991  | CURRENT_USER
 17992  | DEFAULT
 17993  | DEFERRABLE
 17994  | DESC
 17995  | DISTINCT
 17996  | DO
 17997  | ELSE
 17998  | END
 17999  | EXCEPT
 18000  | FALSE
 18001  | FETCH
 18002  | FOR
 18003  | FOREIGN
 18004  | FROM
 18005  | GRANT
 18006  | GROUP
 18007  | HAVING
 18008  | IN
 18009  | INITIALLY
 18010  | INTERSECT
 18011  | INTO
 18012  | LATERAL
 18013  | LEADING
 18014  | LIMIT
 18015  | LOCALTIME
 18016  | LOCALTIMESTAMP
 18017  | NOT
 18018  | NULL
 18019  | OFFSET
 18020  | ON
 18021  | ONLY
 18022  | OR
 18023  | ORDER
 18024  | PLACING
 18025  | PRIMARY
 18026  | REFERENCES
 18027  | RETURNING
 18028  | SELECT
 18029  | SESSION_USER
 18030  | SOME
 18031  | SYMMETRIC
 18032  | TABLE
 18033  | THEN
 18034  | TO
 18035  | TRAILING
 18036  | TRUE
 18037  | UNION
 18038  | UNIQUE
 18039  | USER
 18040  | USING
 18041  | VARIADIC
 18042  | WHEN
 18043  | WHERE
 18044  | WINDOW
 18045  | WITH
 18046  | cockroachdb_extra_reserved_keyword
 18047  
 18048  // Reserved keywords in CockroachDB, in addition to those reserved in
 18049  // PostgreSQL.
 18050  //
 18051  // *** REFRAIN FROM ADDING KEYWORDS HERE ***
 18052  //
 18053  // Adding keywords here creates non-resolvable incompatibilities with
 18054  // postgres clients.
 18055  cockroachdb_extra_reserved_keyword:
 18056    INDEX_BEFORE_NAME_THEN_PAREN
 18057  | INDEX_BEFORE_PAREN
 18058  | INDEX_AFTER_ORDER_BY_BEFORE_AT
 18059  | NOTHING_AFTER_RETURNING
 18060  
 18061  %%