github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/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      "strings"
    29  
    30      "go/constant"
    31  
    32      "github.com/cockroachdb/cockroach/pkg/geo/geopb"
    33      "github.com/cockroachdb/cockroach/pkg/sql/lex"
    34      "github.com/cockroachdb/cockroach/pkg/sql/privilege"
    35      "github.com/cockroachdb/cockroach/pkg/sql/roleoption"
    36      "github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
    37      "github.com/cockroachdb/cockroach/pkg/sql/types"
    38  )
    39  
    40  // MaxUint is the maximum value of an uint.
    41  const MaxUint = ^uint(0)
    42  // MaxInt is the maximum value of an int.
    43  const MaxInt = int(MaxUint >> 1)
    44  
    45  func unimplemented(sqllex sqlLexer, feature string) int {
    46      sqllex.(*lexer).Unimplemented(feature)
    47      return 1
    48  }
    49  
    50  func purposelyUnimplemented(sqllex sqlLexer, feature string, reason string) int {
    51      sqllex.(*lexer).PurposelyUnimplemented(feature, reason)
    52      return 1
    53  }
    54  
    55  func setErr(sqllex sqlLexer, err error) int {
    56      sqllex.(*lexer).setErr(err)
    57      return 1
    58  }
    59  
    60  func unimplementedWithIssue(sqllex sqlLexer, issue int) int {
    61      sqllex.(*lexer).UnimplementedWithIssue(issue)
    62      return 1
    63  }
    64  
    65  func unimplementedWithIssueDetail(sqllex sqlLexer, issue int, detail string) int {
    66      sqllex.(*lexer).UnimplementedWithIssueDetail(issue, detail)
    67      return 1
    68  }
    69  %}
    70  
    71  %{
    72  // sqlSymUnion represents a union of types, providing accessor methods
    73  // to retrieve the underlying type stored in the union's empty interface.
    74  // The purpose of the sqlSymUnion struct is to reduce the memory footprint of
    75  // the sqlSymType because only one value (of a variety of types) is ever needed
    76  // to be stored in the union field at a time.
    77  //
    78  // By using an empty interface, we lose the type checking previously provided
    79  // by yacc and the Go compiler when dealing with union values. Instead, runtime
    80  // type assertions must be relied upon in the methods below, and as such, the
    81  // parser should be thoroughly tested whenever new syntax is added.
    82  //
    83  // It is important to note that when assigning values to sqlSymUnion.val, all
    84  // nil values should be typed so that they are stored as nil instances in the
    85  // empty interface, instead of setting the empty interface to nil. This means
    86  // that:
    87  //     $$ = []String(nil)
    88  // should be used, instead of:
    89  //     $$ = nil
    90  // to assign a nil string slice to the union.
    91  type sqlSymUnion struct {
    92      val interface{}
    93  }
    94  
    95  // The following accessor methods come in three forms, depending on the
    96  // type of the value being accessed and whether a nil value is admissible
    97  // for the corresponding grammar rule.
    98  // - Values and pointers are directly type asserted from the empty
    99  //   interface, regardless of whether a nil value is admissible or
   100  //   not. A panic occurs if the type assertion is incorrect; no panic occurs
   101  //   if a nil is not expected but present. (TODO(knz): split this category of
   102  //   accessor in two; with one checking for unexpected nils.)
   103  //   Examples: bool(), tableIndexName().
   104  //
   105  // - Interfaces where a nil is admissible are handled differently
   106  //   because a nil instance of an interface inserted into the empty interface
   107  //   becomes a nil instance of the empty interface and therefore will fail a
   108  //   direct type assertion. Instead, a guarded type assertion must be used,
   109  //   which returns nil if the type assertion fails.
   110  //   Examples: expr(), stmt().
   111  //
   112  // - Interfaces where a nil is not admissible are implemented as a direct
   113  //   type assertion, which causes a panic to occur if an unexpected nil
   114  //   is encountered.
   115  //   Examples: tblDef().
   116  //
   117  func (u *sqlSymUnion) numVal() *tree.NumVal {
   118      return u.val.(*tree.NumVal)
   119  }
   120  func (u *sqlSymUnion) strVal() *tree.StrVal {
   121      if stmt, ok := u.val.(*tree.StrVal); ok {
   122          return stmt
   123      }
   124      return nil
   125  }
   126  func (u *sqlSymUnion) placeholder() *tree.Placeholder {
   127      return u.val.(*tree.Placeholder)
   128  }
   129  func (u *sqlSymUnion) auditMode() tree.AuditMode {
   130      return u.val.(tree.AuditMode)
   131  }
   132  func (u *sqlSymUnion) bool() bool {
   133      return u.val.(bool)
   134  }
   135  func (u *sqlSymUnion) strPtr() *string {
   136      return u.val.(*string)
   137  }
   138  func (u *sqlSymUnion) strs() []string {
   139      return u.val.([]string)
   140  }
   141  func (u *sqlSymUnion) newTableIndexName() *tree.TableIndexName {
   142      tn := u.val.(tree.TableIndexName)
   143      return &tn
   144  }
   145  func (u *sqlSymUnion) tableIndexName() tree.TableIndexName {
   146      return u.val.(tree.TableIndexName)
   147  }
   148  func (u *sqlSymUnion) newTableIndexNames() tree.TableIndexNames {
   149      return u.val.(tree.TableIndexNames)
   150  }
   151  func (u *sqlSymUnion) shardedIndexDef() *tree.ShardedIndexDef {
   152    return u.val.(*tree.ShardedIndexDef)
   153  }
   154  func (u *sqlSymUnion) nameList() tree.NameList {
   155      return u.val.(tree.NameList)
   156  }
   157  func (u *sqlSymUnion) unresolvedName() *tree.UnresolvedName {
   158      return u.val.(*tree.UnresolvedName)
   159  }
   160  func (u *sqlSymUnion) unresolvedObjectName() *tree.UnresolvedObjectName {
   161      return u.val.(*tree.UnresolvedObjectName)
   162  }
   163  func (u *sqlSymUnion) unresolvedObjectNames() []*tree.UnresolvedObjectName {
   164      return u.val.([]*tree.UnresolvedObjectName)
   165  }
   166  func (u *sqlSymUnion) functionReference() tree.FunctionReference {
   167      return u.val.(tree.FunctionReference)
   168  }
   169  func (u *sqlSymUnion) tablePatterns() tree.TablePatterns {
   170      return u.val.(tree.TablePatterns)
   171  }
   172  func (u *sqlSymUnion) tableNames() tree.TableNames {
   173      return u.val.(tree.TableNames)
   174  }
   175  func (u *sqlSymUnion) indexFlags() *tree.IndexFlags {
   176      return u.val.(*tree.IndexFlags)
   177  }
   178  func (u *sqlSymUnion) arraySubscript() *tree.ArraySubscript {
   179      return u.val.(*tree.ArraySubscript)
   180  }
   181  func (u *sqlSymUnion) arraySubscripts() tree.ArraySubscripts {
   182      if as, ok := u.val.(tree.ArraySubscripts); ok {
   183          return as
   184      }
   185      return nil
   186  }
   187  func (u *sqlSymUnion) stmt() tree.Statement {
   188      if stmt, ok := u.val.(tree.Statement); ok {
   189          return stmt
   190      }
   191      return nil
   192  }
   193  func (u *sqlSymUnion) cte() *tree.CTE {
   194      if cte, ok := u.val.(*tree.CTE); ok {
   195          return cte
   196      }
   197      return nil
   198  }
   199  func (u *sqlSymUnion) ctes() []*tree.CTE {
   200      return u.val.([]*tree.CTE)
   201  }
   202  func (u *sqlSymUnion) with() *tree.With {
   203      if with, ok := u.val.(*tree.With); ok {
   204          return with
   205      }
   206      return nil
   207  }
   208  func (u *sqlSymUnion) slct() *tree.Select {
   209      return u.val.(*tree.Select)
   210  }
   211  func (u *sqlSymUnion) selectStmt() tree.SelectStatement {
   212      return u.val.(tree.SelectStatement)
   213  }
   214  func (u *sqlSymUnion) colDef() *tree.ColumnTableDef {
   215      return u.val.(*tree.ColumnTableDef)
   216  }
   217  func (u *sqlSymUnion) constraintDef() tree.ConstraintTableDef {
   218      return u.val.(tree.ConstraintTableDef)
   219  }
   220  func (u *sqlSymUnion) tblDef() tree.TableDef {
   221      return u.val.(tree.TableDef)
   222  }
   223  func (u *sqlSymUnion) tblDefs() tree.TableDefs {
   224      return u.val.(tree.TableDefs)
   225  }
   226  func (u *sqlSymUnion) likeTableOption() tree.LikeTableOption {
   227      return u.val.(tree.LikeTableOption)
   228  }
   229  func (u *sqlSymUnion) likeTableOptionList() []tree.LikeTableOption {
   230      return u.val.([]tree.LikeTableOption)
   231  }
   232  func (u *sqlSymUnion) colQual() tree.NamedColumnQualification {
   233      return u.val.(tree.NamedColumnQualification)
   234  }
   235  func (u *sqlSymUnion) colQualElem() tree.ColumnQualification {
   236      return u.val.(tree.ColumnQualification)
   237  }
   238  func (u *sqlSymUnion) colQuals() []tree.NamedColumnQualification {
   239      return u.val.([]tree.NamedColumnQualification)
   240  }
   241  func (u *sqlSymUnion) storageParam() tree.StorageParam {
   242      return u.val.(tree.StorageParam)
   243  }
   244  func (u *sqlSymUnion) storageParams() []tree.StorageParam {
   245      if params, ok := u.val.([]tree.StorageParam); ok {
   246          return params
   247      }
   248      return nil
   249  }
   250  func (u *sqlSymUnion) persistenceType() bool {
   251   return u.val.(bool)
   252  }
   253  func (u *sqlSymUnion) colType() *types.T {
   254      if colType, ok := u.val.(*types.T); ok && colType != nil {
   255          return colType
   256      }
   257      return nil
   258  }
   259  func (u *sqlSymUnion) tableRefCols() []tree.ColumnID {
   260      if refCols, ok := u.val.([]tree.ColumnID); ok {
   261          return refCols
   262      }
   263      return nil
   264  }
   265  func (u *sqlSymUnion) colTypes() []*types.T {
   266      return u.val.([]*types.T)
   267  }
   268  func (u *sqlSymUnion) int32() int32 {
   269      return u.val.(int32)
   270  }
   271  func (u *sqlSymUnion) int64() int64 {
   272      return u.val.(int64)
   273  }
   274  func (u *sqlSymUnion) seqOpt() tree.SequenceOption {
   275      return u.val.(tree.SequenceOption)
   276  }
   277  func (u *sqlSymUnion) seqOpts() []tree.SequenceOption {
   278      return u.val.([]tree.SequenceOption)
   279  }
   280  func (u *sqlSymUnion) expr() tree.Expr {
   281      if expr, ok := u.val.(tree.Expr); ok {
   282          return expr
   283      }
   284      return nil
   285  }
   286  func (u *sqlSymUnion) exprs() tree.Exprs {
   287      return u.val.(tree.Exprs)
   288  }
   289  func (u *sqlSymUnion) selExpr() tree.SelectExpr {
   290      return u.val.(tree.SelectExpr)
   291  }
   292  func (u *sqlSymUnion) selExprs() tree.SelectExprs {
   293      return u.val.(tree.SelectExprs)
   294  }
   295  func (u *sqlSymUnion) retClause() tree.ReturningClause {
   296          return u.val.(tree.ReturningClause)
   297  }
   298  func (u *sqlSymUnion) aliasClause() tree.AliasClause {
   299      return u.val.(tree.AliasClause)
   300  }
   301  func (u *sqlSymUnion) asOfClause() tree.AsOfClause {
   302      return u.val.(tree.AsOfClause)
   303  }
   304  func (u *sqlSymUnion) tblExpr() tree.TableExpr {
   305      return u.val.(tree.TableExpr)
   306  }
   307  func (u *sqlSymUnion) tblExprs() tree.TableExprs {
   308      return u.val.(tree.TableExprs)
   309  }
   310  func (u *sqlSymUnion) from() tree.From {
   311      return u.val.(tree.From)
   312  }
   313  func (u *sqlSymUnion) int32s() []int32 {
   314      return u.val.([]int32)
   315  }
   316  func (u *sqlSymUnion) joinCond() tree.JoinCond {
   317      return u.val.(tree.JoinCond)
   318  }
   319  func (u *sqlSymUnion) when() *tree.When {
   320      return u.val.(*tree.When)
   321  }
   322  func (u *sqlSymUnion) whens() []*tree.When {
   323      return u.val.([]*tree.When)
   324  }
   325  func (u *sqlSymUnion) lockingClause() tree.LockingClause {
   326      return u.val.(tree.LockingClause)
   327  }
   328  func (u *sqlSymUnion) lockingItem() *tree.LockingItem {
   329      return u.val.(*tree.LockingItem)
   330  }
   331  func (u *sqlSymUnion) lockingStrength() tree.LockingStrength {
   332      return u.val.(tree.LockingStrength)
   333  }
   334  func (u *sqlSymUnion) lockingWaitPolicy() tree.LockingWaitPolicy {
   335      return u.val.(tree.LockingWaitPolicy)
   336  }
   337  func (u *sqlSymUnion) updateExpr() *tree.UpdateExpr {
   338      return u.val.(*tree.UpdateExpr)
   339  }
   340  func (u *sqlSymUnion) updateExprs() tree.UpdateExprs {
   341      return u.val.(tree.UpdateExprs)
   342  }
   343  func (u *sqlSymUnion) limit() *tree.Limit {
   344      return u.val.(*tree.Limit)
   345  }
   346  func (u *sqlSymUnion) targetList() tree.TargetList {
   347      return u.val.(tree.TargetList)
   348  }
   349  func (u *sqlSymUnion) targetListPtr() *tree.TargetList {
   350      return u.val.(*tree.TargetList)
   351  }
   352  func (u *sqlSymUnion) privilegeType() privilege.Kind {
   353      return u.val.(privilege.Kind)
   354  }
   355  func (u *sqlSymUnion) privilegeList() privilege.List {
   356      return u.val.(privilege.List)
   357  }
   358  func (u *sqlSymUnion) onConflict() *tree.OnConflict {
   359      return u.val.(*tree.OnConflict)
   360  }
   361  func (u *sqlSymUnion) orderBy() tree.OrderBy {
   362      return u.val.(tree.OrderBy)
   363  }
   364  func (u *sqlSymUnion) order() *tree.Order {
   365      return u.val.(*tree.Order)
   366  }
   367  func (u *sqlSymUnion) orders() []*tree.Order {
   368      return u.val.([]*tree.Order)
   369  }
   370  func (u *sqlSymUnion) groupBy() tree.GroupBy {
   371      return u.val.(tree.GroupBy)
   372  }
   373  func (u *sqlSymUnion) windowFrame() *tree.WindowFrame {
   374      return u.val.(*tree.WindowFrame)
   375  }
   376  func (u *sqlSymUnion) windowFrameBounds() tree.WindowFrameBounds {
   377      return u.val.(tree.WindowFrameBounds)
   378  }
   379  func (u *sqlSymUnion) windowFrameBound() *tree.WindowFrameBound {
   380      return u.val.(*tree.WindowFrameBound)
   381  }
   382  func (u *sqlSymUnion) windowFrameExclusion() tree.WindowFrameExclusion {
   383      return u.val.(tree.WindowFrameExclusion)
   384  }
   385  func (u *sqlSymUnion) distinctOn() tree.DistinctOn {
   386      return u.val.(tree.DistinctOn)
   387  }
   388  func (u *sqlSymUnion) dir() tree.Direction {
   389      return u.val.(tree.Direction)
   390  }
   391  func (u *sqlSymUnion) nullsOrder() tree.NullsOrder {
   392      return u.val.(tree.NullsOrder)
   393  }
   394  func (u *sqlSymUnion) alterTableCmd() tree.AlterTableCmd {
   395      return u.val.(tree.AlterTableCmd)
   396  }
   397  func (u *sqlSymUnion) alterTableCmds() tree.AlterTableCmds {
   398      return u.val.(tree.AlterTableCmds)
   399  }
   400  func (u *sqlSymUnion) alterIndexCmd() tree.AlterIndexCmd {
   401      return u.val.(tree.AlterIndexCmd)
   402  }
   403  func (u *sqlSymUnion) alterIndexCmds() tree.AlterIndexCmds {
   404      return u.val.(tree.AlterIndexCmds)
   405  }
   406  func (u *sqlSymUnion) isoLevel() tree.IsolationLevel {
   407      return u.val.(tree.IsolationLevel)
   408  }
   409  func (u *sqlSymUnion) userPriority() tree.UserPriority {
   410      return u.val.(tree.UserPriority)
   411  }
   412  func (u *sqlSymUnion) readWriteMode() tree.ReadWriteMode {
   413      return u.val.(tree.ReadWriteMode)
   414  }
   415  func (u *sqlSymUnion) idxElem() tree.IndexElem {
   416      return u.val.(tree.IndexElem)
   417  }
   418  func (u *sqlSymUnion) idxElems() tree.IndexElemList {
   419      return u.val.(tree.IndexElemList)
   420  }
   421  func (u *sqlSymUnion) dropBehavior() tree.DropBehavior {
   422      return u.val.(tree.DropBehavior)
   423  }
   424  func (u *sqlSymUnion) validationBehavior() tree.ValidationBehavior {
   425      return u.val.(tree.ValidationBehavior)
   426  }
   427  func (u *sqlSymUnion) interleave() *tree.InterleaveDef {
   428      return u.val.(*tree.InterleaveDef)
   429  }
   430  func (u *sqlSymUnion) partitionBy() *tree.PartitionBy {
   431      return u.val.(*tree.PartitionBy)
   432  }
   433  func (u *sqlSymUnion) createTableOnCommitSetting() tree.CreateTableOnCommitSetting {
   434      return u.val.(tree.CreateTableOnCommitSetting)
   435  }
   436  func (u *sqlSymUnion) listPartition() tree.ListPartition {
   437      return u.val.(tree.ListPartition)
   438  }
   439  func (u *sqlSymUnion) listPartitions() []tree.ListPartition {
   440      return u.val.([]tree.ListPartition)
   441  }
   442  func (u *sqlSymUnion) rangePartition() tree.RangePartition {
   443      return u.val.(tree.RangePartition)
   444  }
   445  func (u *sqlSymUnion) rangePartitions() []tree.RangePartition {
   446      return u.val.([]tree.RangePartition)
   447  }
   448  func (u *sqlSymUnion) setZoneConfig() *tree.SetZoneConfig {
   449      return u.val.(*tree.SetZoneConfig)
   450  }
   451  func (u *sqlSymUnion) tuples() []*tree.Tuple {
   452      return u.val.([]*tree.Tuple)
   453  }
   454  func (u *sqlSymUnion) tuple() *tree.Tuple {
   455      return u.val.(*tree.Tuple)
   456  }
   457  func (u *sqlSymUnion) windowDef() *tree.WindowDef {
   458      return u.val.(*tree.WindowDef)
   459  }
   460  func (u *sqlSymUnion) window() tree.Window {
   461      return u.val.(tree.Window)
   462  }
   463  func (u *sqlSymUnion) op() tree.Operator {
   464      return u.val.(tree.Operator)
   465  }
   466  func (u *sqlSymUnion) cmpOp() tree.ComparisonOperator {
   467      return u.val.(tree.ComparisonOperator)
   468  }
   469  func (u *sqlSymUnion) intervalTypeMetadata() types.IntervalTypeMetadata {
   470      return u.val.(types.IntervalTypeMetadata)
   471  }
   472  func (u *sqlSymUnion) kvOption() tree.KVOption {
   473      return u.val.(tree.KVOption)
   474  }
   475  func (u *sqlSymUnion) kvOptions() []tree.KVOption {
   476      if colType, ok := u.val.([]tree.KVOption); ok {
   477          return colType
   478      }
   479      return nil
   480  }
   481  func (u *sqlSymUnion) transactionModes() tree.TransactionModes {
   482      return u.val.(tree.TransactionModes)
   483  }
   484  func (u *sqlSymUnion) compositeKeyMatchMethod() tree.CompositeKeyMatchMethod {
   485    return u.val.(tree.CompositeKeyMatchMethod)
   486  }
   487  func (u *sqlSymUnion) referenceAction() tree.ReferenceAction {
   488      return u.val.(tree.ReferenceAction)
   489  }
   490  func (u *sqlSymUnion) referenceActions() tree.ReferenceActions {
   491      return u.val.(tree.ReferenceActions)
   492  }
   493  func (u *sqlSymUnion) createStatsOptions() *tree.CreateStatsOptions {
   494      return u.val.(*tree.CreateStatsOptions)
   495  }
   496  func (u *sqlSymUnion) scrubOptions() tree.ScrubOptions {
   497      return u.val.(tree.ScrubOptions)
   498  }
   499  func (u *sqlSymUnion) scrubOption() tree.ScrubOption {
   500      return u.val.(tree.ScrubOption)
   501  }
   502  func (u *sqlSymUnion) resolvableFuncRefFromName() tree.ResolvableFunctionReference {
   503      return tree.ResolvableFunctionReference{FunctionReference: u.unresolvedName()}
   504  }
   505  func (u *sqlSymUnion) rowsFromExpr() *tree.RowsFromExpr {
   506      return u.val.(*tree.RowsFromExpr)
   507  }
   508  func (u *sqlSymUnion) partitionedBackup() tree.PartitionedBackup {
   509      return u.val.(tree.PartitionedBackup)
   510  }
   511  func (u *sqlSymUnion) partitionedBackups() []tree.PartitionedBackup {
   512      return u.val.([]tree.PartitionedBackup)
   513  }
   514  func (u *sqlSymUnion) geoFigure() geopb.Shape {
   515    return u.val.(geopb.Shape)
   516  }
   517  func newNameFromStr(s string) *tree.Name {
   518      return (*tree.Name)(&s)
   519  }
   520  func (u *sqlSymUnion) typeReference() tree.ResolvableTypeReference {
   521      return u.val.(tree.ResolvableTypeReference)
   522  }
   523  func (u *sqlSymUnion) typeReferences() []tree.ResolvableTypeReference {
   524      return u.val.([]tree.ResolvableTypeReference)
   525  }
   526  func (u *sqlSymUnion) alterTypeAddValuePlacement() *tree.AlterTypeAddValuePlacement {
   527      return u.val.(*tree.AlterTypeAddValuePlacement)
   528  }
   529  %}
   530  
   531  // NB: the %token definitions must come before the %type definitions in this
   532  // file to work around a bug in goyacc. See #16369 for more details.
   533  
   534  // Non-keyword token types.
   535  %token <str> IDENT SCONST BCONST BITCONST
   536  %token <*tree.NumVal> ICONST FCONST
   537  %token <*tree.Placeholder> PLACEHOLDER
   538  %token <str> TYPECAST TYPEANNOTATE DOT_DOT
   539  %token <str> LESS_EQUALS GREATER_EQUALS NOT_EQUALS
   540  %token <str> NOT_REGMATCH REGIMATCH NOT_REGIMATCH
   541  %token <str> ERROR
   542  
   543  // If you want to make any keyword changes, add the new keyword here as well as
   544  // to the appropriate one of the reserved-or-not-so-reserved keyword lists,
   545  // below; search this file for "Keyword category lists".
   546  
   547  // Ordinary key words in alphabetical order.
   548  %token <str> ABORT ACTION ADD ADMIN AFTER AGGREGATE
   549  %token <str> ALL ALTER ALWAYS ANALYSE ANALYZE AND AND_AND ANY ANNOTATE_TYPE ARRAY AS ASC
   550  %token <str> ASYMMETRIC AT ATTRIBUTE AUTHORIZATION AUTOMATIC
   551  
   552  %token <str> BACKUP BEFORE BEGIN BETWEEN BIGINT BIGSERIAL BIT
   553  %token <str> BUCKET_COUNT
   554  %token <str> BOOLEAN BOTH BUNDLE BY
   555  
   556  %token <str> CACHE CANCEL CASCADE CASE CAST CBRT CHANGEFEED CHAR
   557  %token <str> CHARACTER CHARACTERISTICS CHECK CLOSE
   558  %token <str> CLUSTER COALESCE COLLATE COLLATION COLUMN COLUMNS COMMENT COMMENTS COMMIT
   559  %token <str> COMMITTED COMPACT COMPLETE CONCAT CONCURRENTLY CONFIGURATION CONFIGURATIONS CONFIGURE
   560  %token <str> CONFLICT CONSTRAINT CONSTRAINTS CONTAINS CONVERSION COPY COVERING CREATE CREATEROLE
   561  %token <str> CROSS CUBE CURRENT CURRENT_CATALOG CURRENT_DATE CURRENT_SCHEMA
   562  %token <str> CURRENT_ROLE CURRENT_TIME CURRENT_TIMESTAMP
   563  %token <str> CURRENT_USER CYCLE
   564  
   565  %token <str> DATA DATABASE DATABASES DATE DAY DEC DECIMAL DEFAULT DEFAULTS
   566  %token <str> DEALLOCATE DECLARE DEFERRABLE DEFERRED DELETE DESC
   567  %token <str> DISCARD DISTINCT DO DOMAIN DOUBLE DROP
   568  
   569  %token <str> ELSE ENCODING END ENUM ESCAPE EXCEPT EXCLUDE EXCLUDING
   570  %token <str> EXISTS EXECUTE EXPERIMENTAL
   571  %token <str> EXPERIMENTAL_FINGERPRINTS EXPERIMENTAL_REPLICA
   572  %token <str> EXPERIMENTAL_AUDIT
   573  %token <str> EXPIRATION EXPLAIN EXPORT EXTENSION EXTRACT EXTRACT_DURATION
   574  
   575  %token <str> FALSE FAMILY FETCH FETCHVAL FETCHTEXT FETCHVAL_PATH FETCHTEXT_PATH
   576  %token <str> FILES FILTER
   577  %token <str> FIRST FLOAT FLOAT4 FLOAT8 FLOORDIV FOLLOWING FOR FORCE_INDEX FOREIGN FROM FULL FUNCTION
   578  
   579  %token <str> GENERATED GEOGRAPHY GEOMETRY GEOMETRYCOLLECTION
   580  %token <str> GLOBAL GRANT GRANTS GREATEST GROUP GROUPING GROUPS
   581  
   582  %token <str> HAVING HASH HIGH HISTOGRAM HOUR
   583  
   584  %token <str> IDENTITY
   585  %token <str> IF IFERROR IFNULL IGNORE_FOREIGN_KEYS ILIKE IMMEDIATE IMPORT IN INCLUDE INCLUDING INCREMENT INCREMENTAL
   586  %token <str> INET INET_CONTAINED_BY_OR_EQUALS
   587  %token <str> INET_CONTAINS_OR_EQUALS INDEX INDEXES INJECT INTERLEAVE INITIALLY
   588  %token <str> INNER INSERT INT INTEGER
   589  %token <str> INTERSECT INTERVAL INTO INVERTED IS ISERROR ISNULL ISOLATION
   590  
   591  %token <str> JOB JOBS JOIN JSON JSONB JSON_SOME_EXISTS JSON_ALL_EXISTS
   592  
   593  %token <str> KEY KEYS KV
   594  
   595  %token <str> LANGUAGE LAST LATERAL LC_CTYPE LC_COLLATE
   596  %token <str> LEADING LEASE LEAST LEFT LESS LEVEL LIKE LIMIT LINESTRING LIST LOCAL
   597  %token <str> LOCALTIME LOCALTIMESTAMP LOCKED LOGIN LOOKUP LOW LSHIFT
   598  
   599  %token <str> MATCH MATERIALIZED MERGE MINVALUE MAXVALUE MINUTE MONTH
   600  %token <str> MULTILINESTRING MULTIPOINT MULTIPOLYGON
   601  
   602  %token <str> NAN NAME NAMES NATURAL NEXT NO NOCREATEROLE NOLOGIN NO_INDEX_JOIN
   603  %token <str> NONE NORMAL NOT NOTHING NOTNULL NOWAIT NULL NULLIF NULLS NUMERIC
   604  
   605  %token <str> OF OFF OFFSET OID OIDS OIDVECTOR ON ONLY OPT OPTION OPTIONS OR
   606  %token <str> ORDER ORDINALITY OTHERS OUT OUTER OVER OVERLAPS OVERLAY OWNED OWNER OPERATOR
   607  
   608  %token <str> PARENT PARTIAL PARTITION PARTITIONS PASSWORD PAUSE PHYSICAL PLACING
   609  %token <str> PLAN PLANS POINT POLYGON POSITION PRECEDING PRECISION PREPARE PRESERVE PRIMARY PRIORITY
   610  %token <str> PROCEDURAL PUBLIC PUBLICATION
   611  
   612  %token <str> QUERIES QUERY
   613  
   614  %token <str> RANGE RANGES READ REAL RECURSIVE REF REFERENCES
   615  %token <str> REGCLASS REGPROC REGPROCEDURE REGNAMESPACE REGTYPE REINDEX
   616  %token <str> REMOVE_PATH RENAME REPEATABLE REPLACE
   617  %token <str> RELEASE RESET RESTORE RESTRICT RESUME RETURNING REVOKE RIGHT
   618  %token <str> ROLE ROLES ROLLBACK ROLLUP ROW ROWS RSHIFT RULE
   619  
   620  %token <str> SAVEPOINT SCATTER SCHEMA SCHEMAS SCRUB SEARCH SECOND SELECT SEQUENCE SEQUENCES
   621  %token <str> SERIALIZABLE SERVER SESSION SESSIONS SESSION_USER SET SETTING SETTINGS
   622  %token <str> SHARE SHOW SIMILAR SIMPLE SKIP SMALLINT SMALLSERIAL SNAPSHOT SOME SPLIT SQL
   623  
   624  %token <str> START STATISTICS STATUS STDIN STRICT STRING STORAGE STORE STORED STORING SUBSTRING
   625  %token <str> SYMMETRIC SYNTAX SYSTEM SQRT SUBSCRIPTION
   626  
   627  %token <str> TABLE TABLES TEMP TEMPLATE TEMPORARY TESTING_RELOCATE EXPERIMENTAL_RELOCATE TEXT THEN
   628  %token <str> TIES TIME TIMETZ TIMESTAMP TIMESTAMPTZ TO THROTTLING TRAILING TRACE TRANSACTION TREAT TRIGGER TRIM TRUE
   629  %token <str> TRUNCATE TRUSTED TYPE
   630  %token <str> TRACING
   631  
   632  %token <str> UNBOUNDED UNCOMMITTED UNION UNIQUE UNKNOWN UNLOGGED UNSPLIT
   633  %token <str> UPDATE UPSERT UNTIL USE USER USERS USING UUID
   634  
   635  %token <str> VALID VALIDATE VALUE VALUES VARBIT VARCHAR VARIADIC VIEW VARYING VIRTUAL
   636  
   637  %token <str> WHEN WHERE WINDOW WITH WITHIN WITHOUT WORK WRITE
   638  
   639  %token <str> YEAR
   640  
   641  %token <str> ZONE
   642  
   643  // The grammar thinks these are keywords, but they are not in any category
   644  // and so can never be entered directly. The filter in scan.go creates these
   645  // tokens when required (based on looking one token ahead).
   646  //
   647  // NOT_LA exists so that productions such as NOT LIKE can be given the same
   648  // precedence as LIKE; otherwise they'd effectively have the same precedence as
   649  // NOT, at least with respect to their left-hand subexpression. WITH_LA is
   650  // needed to make the grammar LALR(1). GENERATED_ALWAYS is needed to support
   651  // the Postgres syntax for computed columns along with our family related
   652  // extensions (CREATE FAMILY/CREATE FAMILY family_name).
   653  %token NOT_LA WITH_LA AS_LA GENERATED_ALWAYS
   654  
   655  %union {
   656    id    int32
   657    pos   int32
   658    str   string
   659    union sqlSymUnion
   660  }
   661  
   662  %type <tree.Statement> stmt_block
   663  %type <tree.Statement> stmt
   664  
   665  %type <tree.Statement> alter_stmt
   666  %type <tree.Statement> alter_ddl_stmt
   667  %type <tree.Statement> alter_table_stmt
   668  %type <tree.Statement> alter_index_stmt
   669  %type <tree.Statement> alter_view_stmt
   670  %type <tree.Statement> alter_sequence_stmt
   671  %type <tree.Statement> alter_database_stmt
   672  %type <tree.Statement> alter_range_stmt
   673  %type <tree.Statement> alter_partition_stmt
   674  %type <tree.Statement> alter_role_stmt
   675  %type <tree.Statement> alter_type_stmt
   676  
   677  // ALTER RANGE
   678  %type <tree.Statement> alter_zone_range_stmt
   679  
   680  // ALTER TABLE
   681  %type <tree.Statement> alter_onetable_stmt
   682  %type <tree.Statement> alter_split_stmt
   683  %type <tree.Statement> alter_unsplit_stmt
   684  %type <tree.Statement> alter_rename_table_stmt
   685  %type <tree.Statement> alter_scatter_stmt
   686  %type <tree.Statement> alter_relocate_stmt
   687  %type <tree.Statement> alter_relocate_lease_stmt
   688  %type <tree.Statement> alter_zone_table_stmt
   689  
   690  // ALTER PARTITION
   691  %type <tree.Statement> alter_zone_partition_stmt
   692  
   693  // ALTER DATABASE
   694  %type <tree.Statement> alter_rename_database_stmt
   695  %type <tree.Statement> alter_zone_database_stmt
   696  
   697  // ALTER INDEX
   698  %type <tree.Statement> alter_oneindex_stmt
   699  %type <tree.Statement> alter_scatter_index_stmt
   700  %type <tree.Statement> alter_split_index_stmt
   701  %type <tree.Statement> alter_unsplit_index_stmt
   702  %type <tree.Statement> alter_rename_index_stmt
   703  %type <tree.Statement> alter_relocate_index_stmt
   704  %type <tree.Statement> alter_relocate_index_lease_stmt
   705  %type <tree.Statement> alter_zone_index_stmt
   706  
   707  // ALTER VIEW
   708  %type <tree.Statement> alter_rename_view_stmt
   709  
   710  // ALTER SEQUENCE
   711  %type <tree.Statement> alter_rename_sequence_stmt
   712  %type <tree.Statement> alter_sequence_options_stmt
   713  
   714  %type <tree.Statement> backup_stmt
   715  %type <tree.Statement> begin_stmt
   716  
   717  %type <tree.Statement> cancel_stmt
   718  %type <tree.Statement> cancel_jobs_stmt
   719  %type <tree.Statement> cancel_queries_stmt
   720  %type <tree.Statement> cancel_sessions_stmt
   721  
   722  // SCRUB
   723  %type <tree.Statement> scrub_stmt
   724  %type <tree.Statement> scrub_database_stmt
   725  %type <tree.Statement> scrub_table_stmt
   726  %type <tree.ScrubOptions> opt_scrub_options_clause
   727  %type <tree.ScrubOptions> scrub_option_list
   728  %type <tree.ScrubOption> scrub_option
   729  
   730  %type <tree.Statement> comment_stmt
   731  %type <tree.Statement> commit_stmt
   732  %type <tree.Statement> copy_from_stmt
   733  
   734  %type <tree.Statement> create_stmt
   735  %type <tree.Statement> create_changefeed_stmt
   736  %type <tree.Statement> create_ddl_stmt
   737  %type <tree.Statement> create_database_stmt
   738  %type <tree.Statement> create_index_stmt
   739  %type <tree.Statement> create_role_stmt
   740  %type <tree.Statement> create_schema_stmt
   741  %type <tree.Statement> create_table_stmt
   742  %type <tree.Statement> create_table_as_stmt
   743  %type <tree.Statement> create_view_stmt
   744  %type <tree.Statement> create_sequence_stmt
   745  
   746  %type <tree.Statement> create_stats_stmt
   747  %type <*tree.CreateStatsOptions> opt_create_stats_options
   748  %type <*tree.CreateStatsOptions> create_stats_option_list
   749  %type <*tree.CreateStatsOptions> create_stats_option
   750  
   751  %type <tree.Statement> create_type_stmt
   752  %type <tree.Statement> delete_stmt
   753  %type <tree.Statement> discard_stmt
   754  
   755  %type <tree.Statement> drop_stmt
   756  %type <tree.Statement> drop_ddl_stmt
   757  %type <tree.Statement> drop_database_stmt
   758  %type <tree.Statement> drop_index_stmt
   759  %type <tree.Statement> drop_role_stmt
   760  %type <tree.Statement> drop_table_stmt
   761  %type <tree.Statement> drop_type_stmt
   762  %type <tree.Statement> drop_view_stmt
   763  %type <tree.Statement> drop_sequence_stmt
   764  
   765  %type <tree.Statement> explain_stmt
   766  %type <tree.Statement> prepare_stmt
   767  %type <tree.Statement> preparable_stmt
   768  %type <tree.Statement> row_source_extension_stmt
   769  %type <tree.Statement> export_stmt
   770  %type <tree.Statement> execute_stmt
   771  %type <tree.Statement> deallocate_stmt
   772  %type <tree.Statement> grant_stmt
   773  %type <tree.Statement> insert_stmt
   774  %type <tree.Statement> import_stmt
   775  %type <tree.Statement> pause_stmt
   776  %type <tree.Statement> release_stmt
   777  %type <tree.Statement> reset_stmt reset_session_stmt reset_csetting_stmt
   778  %type <tree.Statement> resume_stmt
   779  %type <tree.Statement> restore_stmt
   780  %type <tree.PartitionedBackup> partitioned_backup
   781  %type <[]tree.PartitionedBackup> partitioned_backup_list
   782  %type <tree.Statement> revoke_stmt
   783  %type <*tree.Select> select_stmt
   784  %type <tree.Statement> abort_stmt
   785  %type <tree.Statement> rollback_stmt
   786  %type <tree.Statement> savepoint_stmt
   787  
   788  %type <tree.Statement> preparable_set_stmt nonpreparable_set_stmt
   789  %type <tree.Statement> set_session_stmt
   790  %type <tree.Statement> set_csetting_stmt
   791  %type <tree.Statement> set_transaction_stmt
   792  %type <tree.Statement> set_exprs_internal
   793  %type <tree.Statement> generic_set
   794  %type <tree.Statement> set_rest_more
   795  %type <tree.Statement> set_names
   796  
   797  %type <tree.Statement> show_stmt
   798  %type <tree.Statement> show_backup_stmt
   799  %type <tree.Statement> show_columns_stmt
   800  %type <tree.Statement> show_constraints_stmt
   801  %type <tree.Statement> show_create_stmt
   802  %type <tree.Statement> show_csettings_stmt
   803  %type <tree.Statement> show_databases_stmt
   804  %type <tree.Statement> show_fingerprints_stmt
   805  %type <tree.Statement> show_grants_stmt
   806  %type <tree.Statement> show_histogram_stmt
   807  %type <tree.Statement> show_indexes_stmt
   808  %type <tree.Statement> show_partitions_stmt
   809  %type <tree.Statement> show_jobs_stmt
   810  %type <tree.Statement> show_queries_stmt
   811  %type <tree.Statement> show_ranges_stmt
   812  %type <tree.Statement> show_range_for_row_stmt
   813  %type <tree.Statement> show_roles_stmt
   814  %type <tree.Statement> show_schemas_stmt
   815  %type <tree.Statement> show_sequences_stmt
   816  %type <tree.Statement> show_session_stmt
   817  %type <tree.Statement> show_sessions_stmt
   818  %type <tree.Statement> show_savepoint_stmt
   819  %type <tree.Statement> show_stats_stmt
   820  %type <tree.Statement> show_syntax_stmt
   821  %type <tree.Statement> show_tables_stmt
   822  %type <tree.Statement> show_trace_stmt
   823  %type <tree.Statement> show_transaction_stmt
   824  %type <tree.Statement> show_users_stmt
   825  %type <tree.Statement> show_zone_stmt
   826  
   827  %type <str> session_var
   828  %type <*string> comment_text
   829  
   830  %type <tree.Statement> transaction_stmt
   831  %type <tree.Statement> truncate_stmt
   832  %type <tree.Statement> update_stmt
   833  %type <tree.Statement> upsert_stmt
   834  %type <tree.Statement> use_stmt
   835  
   836  %type <tree.Statement> close_cursor_stmt
   837  %type <tree.Statement> declare_cursor_stmt
   838  %type <tree.Statement> reindex_stmt
   839  
   840  %type <[]string> opt_incremental
   841  %type <tree.KVOption> kv_option
   842  %type <[]tree.KVOption> kv_option_list opt_with_options var_set_list
   843  %type <str> import_format
   844  %type <tree.StorageParam> storage_parameter
   845  %type <[]tree.StorageParam> storage_parameter_list opt_table_with
   846  
   847  %type <*tree.Select> select_no_parens
   848  %type <tree.SelectStatement> select_clause select_with_parens simple_select values_clause table_clause simple_select_clause
   849  %type <tree.LockingClause> for_locking_clause opt_for_locking_clause for_locking_items
   850  %type <*tree.LockingItem> for_locking_item
   851  %type <tree.LockingStrength> for_locking_strength
   852  %type <tree.LockingWaitPolicy> opt_nowait_or_skip
   853  %type <tree.SelectStatement> set_operation
   854  
   855  %type <tree.Expr> alter_column_default
   856  %type <tree.Direction> opt_asc_desc
   857  %type <tree.NullsOrder> opt_nulls_order
   858  
   859  %type <tree.AlterTableCmd> alter_table_cmd
   860  %type <tree.AlterTableCmds> alter_table_cmds
   861  %type <tree.AlterIndexCmd> alter_index_cmd
   862  %type <tree.AlterIndexCmds> alter_index_cmds
   863  
   864  %type <tree.DropBehavior> opt_drop_behavior
   865  %type <tree.DropBehavior> opt_interleave_drop_behavior
   866  
   867  %type <tree.ValidationBehavior> opt_validate_behavior
   868  
   869  %type <str> opt_template_clause opt_encoding_clause opt_lc_collate_clause opt_lc_ctype_clause
   870  
   871  %type <tree.IsolationLevel> transaction_iso_level
   872  %type <tree.UserPriority> transaction_user_priority
   873  %type <tree.ReadWriteMode> transaction_read_mode
   874  
   875  %type <str> name opt_name opt_name_parens
   876  %type <str> privilege savepoint_name
   877  %type <tree.KVOption> role_option password_clause valid_until_clause
   878  %type <tree.Operator> subquery_op
   879  %type <*tree.UnresolvedName> func_name func_name_no_crdb_extra
   880  %type <str> opt_collate
   881  
   882  %type <str> cursor_name database_name index_name opt_index_name column_name insert_column_item statistics_name window_name
   883  %type <str> family_name opt_family_name table_alias_name constraint_name target_name zone_name partition_name collation_name
   884  %type <str> db_object_name_component
   885  %type <*tree.UnresolvedObjectName> table_name standalone_index_name sequence_name type_name view_name db_object_name simple_db_object_name complex_db_object_name
   886  %type <[]*tree.UnresolvedObjectName> type_name_list
   887  %type <str> schema_name
   888  %type <*tree.UnresolvedName> table_pattern complex_table_pattern
   889  %type <*tree.UnresolvedName> column_path prefixed_column_path column_path_with_star
   890  %type <tree.TableExpr> insert_target create_stats_target
   891  
   892  %type <*tree.TableIndexName> table_index_name
   893  %type <tree.TableIndexNames> table_index_name_list
   894  
   895  %type <tree.Operator> math_op
   896  
   897  %type <tree.IsolationLevel> iso_level
   898  %type <tree.UserPriority> user_priority
   899  
   900  %type <tree.TableDefs> opt_table_elem_list table_elem_list create_as_opt_col_list create_as_table_defs
   901  %type <[]tree.LikeTableOption> like_table_option_list
   902  %type <tree.LikeTableOption> like_table_option
   903  %type <tree.CreateTableOnCommitSetting> opt_create_table_on_commit
   904  %type <*tree.InterleaveDef> opt_interleave
   905  %type <*tree.PartitionBy> opt_partition_by partition_by
   906  %type <str> partition opt_partition
   907  %type <tree.ListPartition> list_partition
   908  %type <[]tree.ListPartition> list_partitions
   909  %type <tree.RangePartition> range_partition
   910  %type <[]tree.RangePartition> range_partitions
   911  %type <empty> opt_all_clause
   912  %type <bool> distinct_clause
   913  %type <tree.DistinctOn> distinct_on_clause
   914  %type <tree.NameList> opt_column_list insert_column_list opt_stats_columns
   915  %type <tree.OrderBy> sort_clause single_sort_clause opt_sort_clause
   916  %type <[]*tree.Order> sortby_list
   917  %type <tree.IndexElemList> index_params create_as_params
   918  %type <tree.NameList> name_list privilege_list
   919  %type <[]int32> opt_array_bounds
   920  %type <tree.From> from_clause
   921  %type <tree.TableExprs> from_list rowsfrom_list opt_from_list
   922  %type <tree.TablePatterns> table_pattern_list single_table_pattern_list
   923  %type <tree.TableNames> table_name_list opt_locked_rels
   924  %type <tree.Exprs> expr_list opt_expr_list tuple1_ambiguous_values tuple1_unambiguous_values
   925  %type <*tree.Tuple> expr_tuple1_ambiguous expr_tuple_unambiguous
   926  %type <tree.NameList> attrs
   927  %type <tree.SelectExprs> target_list
   928  %type <tree.UpdateExprs> set_clause_list
   929  %type <*tree.UpdateExpr> set_clause multiple_set_clause
   930  %type <tree.ArraySubscripts> array_subscripts
   931  %type <tree.GroupBy> group_clause
   932  %type <*tree.Limit> select_limit opt_select_limit
   933  %type <tree.TableNames> relation_expr_list
   934  %type <tree.ReturningClause> returning_clause
   935  %type <empty> opt_using_clause
   936  
   937  %type <[]tree.SequenceOption> sequence_option_list opt_sequence_option_list
   938  %type <tree.SequenceOption> sequence_option_elem
   939  
   940  %type <bool> all_or_distinct
   941  %type <bool> with_comment
   942  %type <empty> join_outer
   943  %type <tree.JoinCond> join_qual
   944  %type <str> join_type
   945  %type <str> opt_join_hint
   946  
   947  %type <tree.Exprs> extract_list
   948  %type <tree.Exprs> overlay_list
   949  %type <tree.Exprs> position_list
   950  %type <tree.Exprs> substr_list
   951  %type <tree.Exprs> trim_list
   952  %type <tree.Exprs> execute_param_clause
   953  %type <types.IntervalTypeMetadata> opt_interval_qualifier interval_qualifier interval_second
   954  %type <tree.Expr> overlay_placing
   955  
   956  %type <bool> opt_unique opt_concurrently opt_cluster
   957  %type <bool> opt_using_gin_btree
   958  
   959  %type <*tree.Limit> limit_clause offset_clause opt_limit_clause
   960  %type <tree.Expr> select_fetch_first_value
   961  %type <empty> row_or_rows
   962  %type <empty> first_or_next
   963  
   964  %type <tree.Statement> insert_rest
   965  %type <tree.NameList> opt_conf_expr opt_col_def_list
   966  %type <*tree.OnConflict> on_conflict
   967  
   968  %type <tree.Statement> begin_transaction
   969  %type <tree.TransactionModes> transaction_mode_list transaction_mode
   970  
   971  %type <*tree.ShardedIndexDef> opt_hash_sharded
   972  %type <tree.NameList> opt_storing
   973  %type <*tree.ColumnTableDef> column_def
   974  %type <tree.TableDef> table_elem
   975  %type <tree.Expr> where_clause opt_where_clause
   976  %type <*tree.ArraySubscript> array_subscript
   977  %type <tree.Expr> opt_slice_bound
   978  %type <*tree.IndexFlags> opt_index_flags
   979  %type <*tree.IndexFlags> index_flags_param
   980  %type <*tree.IndexFlags> index_flags_param_list
   981  %type <tree.Expr> a_expr b_expr c_expr d_expr typed_literal
   982  %type <tree.Expr> substr_from substr_for
   983  %type <tree.Expr> in_expr
   984  %type <tree.Expr> having_clause
   985  %type <tree.Expr> array_expr
   986  %type <tree.Expr> interval_value
   987  %type <[]tree.ResolvableTypeReference> type_list prep_type_clause
   988  %type <tree.Exprs> array_expr_list
   989  %type <*tree.Tuple> row labeled_row
   990  %type <tree.Expr> case_expr case_arg case_default
   991  %type <*tree.When> when_clause
   992  %type <[]*tree.When> when_clause_list
   993  %type <tree.ComparisonOperator> sub_type
   994  %type <tree.Expr> numeric_only
   995  %type <tree.AliasClause> alias_clause opt_alias_clause
   996  %type <bool> opt_ordinality opt_compact
   997  %type <*tree.Order> sortby
   998  %type <tree.IndexElem> index_elem create_as_param
   999  %type <tree.TableExpr> table_ref numeric_table_ref func_table
  1000  %type <tree.Exprs> rowsfrom_list
  1001  %type <tree.Expr> rowsfrom_item
  1002  %type <tree.TableExpr> joined_table
  1003  %type <*tree.UnresolvedObjectName> relation_expr
  1004  %type <tree.TableExpr> table_expr_opt_alias_idx table_name_opt_idx
  1005  %type <tree.SelectExpr> target_elem
  1006  %type <*tree.UpdateExpr> single_set_clause
  1007  %type <tree.AsOfClause> as_of_clause opt_as_of_clause
  1008  %type <tree.Expr> opt_changefeed_sink
  1009  
  1010  %type <str> explain_option_name
  1011  %type <[]string> explain_option_list opt_enum_val_list enum_val_list
  1012  
  1013  %type <tree.ResolvableTypeReference> typename simple_typename cast_target
  1014  %type <*types.T> const_typename
  1015  %type <*tree.AlterTypeAddValuePlacement> opt_add_val_placement
  1016  %type <bool> opt_timezone
  1017  %type <*types.T> numeric opt_numeric_modifiers
  1018  %type <*types.T> opt_float
  1019  %type <*types.T> character_with_length character_without_length
  1020  %type <*types.T> const_datetime interval_type
  1021  %type <*types.T> bit_with_length bit_without_length
  1022  %type <*types.T> character_base
  1023  %type <*types.T> geo_shape
  1024  %type <*types.T> const_geo
  1025  %type <str> extract_arg
  1026  %type <bool> opt_varying
  1027  
  1028  %type <*tree.NumVal> signed_iconst only_signed_iconst
  1029  %type <*tree.NumVal> signed_fconst only_signed_fconst
  1030  %type <int32> iconst32
  1031  %type <int64> signed_iconst64
  1032  %type <int64> iconst64
  1033  %type <tree.Expr> var_value
  1034  %type <tree.Exprs> var_list
  1035  %type <tree.NameList> var_name
  1036  %type <str> unrestricted_name type_function_name type_function_name_no_crdb_extra
  1037  %type <str> non_reserved_word
  1038  %type <str> non_reserved_word_or_sconst
  1039  %type <tree.Expr> zone_value
  1040  %type <tree.Expr> string_or_placeholder
  1041  %type <tree.Expr> string_or_placeholder_list
  1042  
  1043  %type <str> unreserved_keyword type_func_name_keyword type_func_name_no_crdb_extra_keyword type_func_name_crdb_extra_keyword
  1044  %type <str> col_name_keyword reserved_keyword cockroachdb_extra_reserved_keyword extra_var_value
  1045  
  1046  %type <tree.ResolvableTypeReference> complex_type_name
  1047  %type <str> general_type_name
  1048  
  1049  %type <tree.ConstraintTableDef> table_constraint constraint_elem create_as_constraint_def create_as_constraint_elem
  1050  %type <tree.TableDef> index_def
  1051  %type <tree.TableDef> family_def
  1052  %type <[]tree.NamedColumnQualification> col_qual_list create_as_col_qual_list
  1053  %type <tree.NamedColumnQualification> col_qualification create_as_col_qualification
  1054  %type <tree.ColumnQualification> col_qualification_elem create_as_col_qualification_elem
  1055  %type <tree.CompositeKeyMatchMethod> key_match
  1056  %type <tree.ReferenceActions> reference_actions
  1057  %type <tree.ReferenceAction> reference_action reference_on_delete reference_on_update
  1058  
  1059  %type <tree.Expr> func_application func_expr_common_subexpr special_function
  1060  %type <tree.Expr> func_expr func_expr_windowless
  1061  %type <empty> opt_with
  1062  %type <*tree.With> with_clause opt_with_clause
  1063  %type <[]*tree.CTE> cte_list
  1064  %type <*tree.CTE> common_table_expr
  1065  %type <bool> materialize_clause
  1066  
  1067  %type <tree.Expr> within_group_clause
  1068  %type <tree.Expr> filter_clause
  1069  %type <tree.Exprs> opt_partition_clause
  1070  %type <tree.Window> window_clause window_definition_list
  1071  %type <*tree.WindowDef> window_definition over_clause window_specification
  1072  %type <str> opt_existing_window_name
  1073  %type <*tree.WindowFrame> opt_frame_clause
  1074  %type <tree.WindowFrameBounds> frame_extent
  1075  %type <*tree.WindowFrameBound> frame_bound
  1076  %type <tree.WindowFrameExclusion> opt_frame_exclusion
  1077  
  1078  %type <[]tree.ColumnID> opt_tableref_col_list tableref_col_list
  1079  
  1080  %type <tree.TargetList> targets targets_roles changefeed_targets
  1081  %type <*tree.TargetList> opt_on_targets_roles
  1082  %type <tree.NameList> for_grantee_clause
  1083  %type <privilege.List> privileges
  1084  %type <[]tree.KVOption> opt_role_options role_options
  1085  %type <tree.AuditMode> audit_mode
  1086  
  1087  %type <str> relocate_kw
  1088  
  1089  %type <*tree.SetZoneConfig> set_zone_config
  1090  
  1091  %type <tree.Expr> opt_alter_column_using
  1092  
  1093  %type <bool> opt_temp
  1094  %type <bool> opt_temp_create_table
  1095  %type <bool> role_or_group_or_user
  1096  
  1097  // Precedence: lowest to highest
  1098  %nonassoc  VALUES              // see value_clause
  1099  %nonassoc  SET                 // see table_expr_opt_alias_idx
  1100  %left      UNION EXCEPT
  1101  %left      INTERSECT
  1102  %left      OR
  1103  %left      AND
  1104  %right     NOT
  1105  %nonassoc  IS ISNULL NOTNULL   // IS sets precedence for IS NULL, etc
  1106  %nonassoc  '<' '>' '=' LESS_EQUALS GREATER_EQUALS NOT_EQUALS
  1107  %nonassoc  '~' BETWEEN IN LIKE ILIKE SIMILAR NOT_REGMATCH REGIMATCH NOT_REGIMATCH NOT_LA
  1108  %nonassoc  ESCAPE              // ESCAPE must be just above LIKE/ILIKE/SIMILAR
  1109  %nonassoc  CONTAINS CONTAINED_BY '?' JSON_SOME_EXISTS JSON_ALL_EXISTS
  1110  %nonassoc  OVERLAPS
  1111  %left      POSTFIXOP           // dummy for postfix OP rules
  1112  // To support target_elem without AS, we must give IDENT an explicit priority
  1113  // between POSTFIXOP and OP. We can safely assign the same priority to various
  1114  // unreserved keywords as needed to resolve ambiguities (this can't have any
  1115  // bad effects since obviously the keywords will still behave the same as if
  1116  // they weren't keywords). We need to do this for PARTITION, RANGE, ROWS,
  1117  // GROUPS to support opt_existing_window_name; and for RANGE, ROWS, GROUPS so
  1118  // that they can follow a_expr without creating postfix-operator problems; and
  1119  // for NULL so that it can follow b_expr in col_qual_list without creating
  1120  // postfix-operator problems.
  1121  //
  1122  // To support CUBE and ROLLUP in GROUP BY without reserving them, we give them
  1123  // an explicit priority lower than '(', so that a rule with CUBE '(' will shift
  1124  // rather than reducing a conflicting rule that takes CUBE as a function name.
  1125  // Using the same precedence as IDENT seems right for the reasons given above.
  1126  //
  1127  // The frame_bound productions UNBOUNDED PRECEDING and UNBOUNDED FOLLOWING are
  1128  // even messier: since UNBOUNDED is an unreserved keyword (per spec!), there is
  1129  // no principled way to distinguish these from the productions a_expr
  1130  // PRECEDING/FOLLOWING. We hack this up by giving UNBOUNDED slightly lower
  1131  // precedence than PRECEDING and FOLLOWING. At present this doesn't appear to
  1132  // cause UNBOUNDED to be treated differently from other unreserved keywords
  1133  // anywhere else in the grammar, but it's definitely risky. We can blame any
  1134  // funny behavior of UNBOUNDED on the SQL standard, though.
  1135  %nonassoc  UNBOUNDED         // ideally should have same precedence as IDENT
  1136  %nonassoc  IDENT NULL PARTITION RANGE ROWS GROUPS PRECEDING FOLLOWING CUBE ROLLUP
  1137  %left      CONCAT FETCHVAL FETCHTEXT FETCHVAL_PATH FETCHTEXT_PATH REMOVE_PATH  // multi-character ops
  1138  %left      '|'
  1139  %left      '#'
  1140  %left      '&'
  1141  %left      LSHIFT RSHIFT INET_CONTAINS_OR_EQUALS INET_CONTAINED_BY_OR_EQUALS AND_AND SQRT CBRT
  1142  %left      '+' '-'
  1143  %left      '*' '/' FLOORDIV '%'
  1144  %left      '^'
  1145  // Unary Operators
  1146  %left      AT                // sets precedence for AT TIME ZONE
  1147  %left      COLLATE
  1148  %right     UMINUS
  1149  %left      '[' ']'
  1150  %left      '(' ')'
  1151  %left      TYPEANNOTATE
  1152  %left      TYPECAST
  1153  %left      '.'
  1154  // These might seem to be low-precedence, but actually they are not part
  1155  // of the arithmetic hierarchy at all in their use as JOIN operators.
  1156  // We make them high-precedence to support their use as function names.
  1157  // They wouldn't be given a precedence at all, were it not that we need
  1158  // left-associativity among the JOIN rules themselves.
  1159  %left      JOIN CROSS LEFT FULL RIGHT INNER NATURAL
  1160  %right     HELPTOKEN
  1161  
  1162  %%
  1163  
  1164  stmt_block:
  1165    stmt
  1166    {
  1167      sqllex.(*lexer).SetStmt($1.stmt())
  1168    }
  1169  
  1170  stmt:
  1171    HELPTOKEN { return helpWith(sqllex, "") }
  1172  | preparable_stmt  // help texts in sub-rule
  1173  | copy_from_stmt
  1174  | comment_stmt
  1175  | execute_stmt      // EXTEND WITH HELP: EXECUTE
  1176  | deallocate_stmt   // EXTEND WITH HELP: DEALLOCATE
  1177  | discard_stmt      // EXTEND WITH HELP: DISCARD
  1178  | grant_stmt        // EXTEND WITH HELP: GRANT
  1179  | prepare_stmt      // EXTEND WITH HELP: PREPARE
  1180  | revoke_stmt       // EXTEND WITH HELP: REVOKE
  1181  | savepoint_stmt    // EXTEND WITH HELP: SAVEPOINT
  1182  | release_stmt      // EXTEND WITH HELP: RELEASE
  1183  | nonpreparable_set_stmt // help texts in sub-rule
  1184  | transaction_stmt  // help texts in sub-rule
  1185  | close_cursor_stmt
  1186  | declare_cursor_stmt
  1187  | reindex_stmt
  1188  | /* EMPTY */
  1189    {
  1190      $$.val = tree.Statement(nil)
  1191    }
  1192  
  1193  // %Help: ALTER
  1194  // %Category: Group
  1195  // %Text: ALTER TABLE, ALTER INDEX, ALTER VIEW, ALTER SEQUENCE, ALTER DATABASE, ALTER USER, ALTER ROLE
  1196  alter_stmt:
  1197    alter_ddl_stmt      // help texts in sub-rule
  1198  | alter_role_stmt     // EXTEND WITH HELP: ALTER ROLE
  1199  | ALTER error         // SHOW HELP: ALTER
  1200  
  1201  alter_ddl_stmt:
  1202    alter_table_stmt     // EXTEND WITH HELP: ALTER TABLE
  1203  | alter_index_stmt     // EXTEND WITH HELP: ALTER INDEX
  1204  | alter_view_stmt      // EXTEND WITH HELP: ALTER VIEW
  1205  | alter_sequence_stmt  // EXTEND WITH HELP: ALTER SEQUENCE
  1206  | alter_database_stmt  // EXTEND WITH HELP: ALTER DATABASE
  1207  | alter_range_stmt     // EXTEND WITH HELP: ALTER RANGE
  1208  | alter_partition_stmt // EXTEND WITH HELP: ALTER PARTITION
  1209  | alter_type_stmt      // EXTEND WITH HELP: ALTER TYPE
  1210  
  1211  // %Help: ALTER TABLE - change the definition of a table
  1212  // %Category: DDL
  1213  // %Text:
  1214  // ALTER TABLE [IF EXISTS] <tablename> <command> [, ...]
  1215  //
  1216  // Commands:
  1217  //   ALTER TABLE ... ADD [COLUMN] [IF NOT EXISTS] <colname> <type> [<qualifiers...>]
  1218  //   ALTER TABLE ... ADD <constraint>
  1219  //   ALTER TABLE ... DROP [COLUMN] [IF EXISTS] <colname> [RESTRICT | CASCADE]
  1220  //   ALTER TABLE ... DROP CONSTRAINT [IF EXISTS] <constraintname> [RESTRICT | CASCADE]
  1221  //   ALTER TABLE ... ALTER [COLUMN] <colname> {SET DEFAULT <expr> | DROP DEFAULT}
  1222  //   ALTER TABLE ... ALTER [COLUMN] <colname> DROP NOT NULL
  1223  //   ALTER TABLE ... ALTER [COLUMN] <colname> DROP STORED
  1224  //   ALTER TABLE ... ALTER [COLUMN] <colname> [SET DATA] TYPE <type> [COLLATE <collation>]
  1225  //   ALTER TABLE ... ALTER PRIMARY KEY USING INDEX <name>
  1226  //   ALTER TABLE ... RENAME TO <newname>
  1227  //   ALTER TABLE ... RENAME [COLUMN] <colname> TO <newname>
  1228  //   ALTER TABLE ... VALIDATE CONSTRAINT <constraintname>
  1229  //   ALTER TABLE ... SPLIT AT <selectclause> [WITH EXPIRATION <expr>]
  1230  //   ALTER TABLE ... UNSPLIT AT <selectclause>
  1231  //   ALTER TABLE ... UNSPLIT ALL
  1232  //   ALTER TABLE ... SCATTER [ FROM ( <exprs...> ) TO ( <exprs...> ) ]
  1233  //   ALTER TABLE ... INJECT STATISTICS ...  (experimental)
  1234  //   ALTER TABLE ... PARTITION BY RANGE ( <name...> ) ( <rangespec> )
  1235  //   ALTER TABLE ... PARTITION BY LIST ( <name...> ) ( <listspec> )
  1236  //   ALTER TABLE ... PARTITION BY NOTHING
  1237  //   ALTER TABLE ... CONFIGURE ZONE <zoneconfig>
  1238  //
  1239  // Column qualifiers:
  1240  //   [CONSTRAINT <constraintname>] {NULL | NOT NULL | UNIQUE | PRIMARY KEY | CHECK (<expr>) | DEFAULT <expr>}
  1241  //   FAMILY <familyname>, CREATE [IF NOT EXISTS] FAMILY [<familyname>]
  1242  //   REFERENCES <tablename> [( <colnames...> )]
  1243  //   COLLATE <collationname>
  1244  //
  1245  // Zone configurations:
  1246  //   DISCARD
  1247  //   USING <var> = <expr> [, ...]
  1248  //   USING <var> = COPY FROM PARENT [, ...]
  1249  //   { TO | = } <expr>
  1250  //
  1251  // %SeeAlso: WEBDOCS/alter-table.html
  1252  alter_table_stmt:
  1253    alter_onetable_stmt
  1254  | alter_relocate_stmt
  1255  | alter_relocate_lease_stmt
  1256  | alter_split_stmt
  1257  | alter_unsplit_stmt
  1258  | alter_scatter_stmt
  1259  | alter_zone_table_stmt
  1260  | alter_rename_table_stmt
  1261  // ALTER TABLE has its error help token here because the ALTER TABLE
  1262  // prefix is spread over multiple non-terminals.
  1263  | ALTER TABLE error     // SHOW HELP: ALTER TABLE
  1264  
  1265  // %Help: ALTER PARTITION - apply zone configurations to a partition
  1266  // %Category: DDL
  1267  // %Text:
  1268  // ALTER PARTITION <name> <command>
  1269  //
  1270  // Commands:
  1271  //   -- Alter a single partition which exists on any of a table's indexes.
  1272  //   ALTER PARTITION <partition> OF TABLE <tablename> CONFIGURE ZONE <zoneconfig>
  1273  //
  1274  //   -- Alter a partition of a specific index.
  1275  //   ALTER PARTITION <partition> OF INDEX <tablename>@<indexname> CONFIGURE ZONE <zoneconfig>
  1276  //
  1277  //   -- Alter all partitions with the same name across a table's indexes.
  1278  //   ALTER PARTITION <partition> OF INDEX <tablename>@* CONFIGURE ZONE <zoneconfig>
  1279  //
  1280  // Zone configurations:
  1281  //   DISCARD
  1282  //   USING <var> = <expr> [, ...]
  1283  //   USING <var> = COPY FROM PARENT [, ...]
  1284  //   { TO | = } <expr>
  1285  //
  1286  // %SeeAlso: WEBDOCS/configure-zone.html
  1287  alter_partition_stmt:
  1288    alter_zone_partition_stmt
  1289  | ALTER PARTITION error // SHOW HELP: ALTER PARTITION
  1290  
  1291  // %Help: ALTER VIEW - change the definition of a view
  1292  // %Category: DDL
  1293  // %Text:
  1294  // ALTER VIEW [IF EXISTS] <name> RENAME TO <newname>
  1295  // %SeeAlso: WEBDOCS/alter-view.html
  1296  alter_view_stmt:
  1297    alter_rename_view_stmt
  1298  // ALTER VIEW has its error help token here because the ALTER VIEW
  1299  // prefix is spread over multiple non-terminals.
  1300  | ALTER VIEW error // SHOW HELP: ALTER VIEW
  1301  
  1302  // %Help: ALTER SEQUENCE - change the definition of a sequence
  1303  // %Category: DDL
  1304  // %Text:
  1305  // ALTER SEQUENCE [IF EXISTS] <name>
  1306  //   [INCREMENT <increment>]
  1307  //   [MINVALUE <minvalue> | NO MINVALUE]
  1308  //   [MAXVALUE <maxvalue> | NO MAXVALUE]
  1309  //   [START <start>]
  1310  //   [[NO] CYCLE]
  1311  // ALTER SEQUENCE [IF EXISTS] <name> RENAME TO <newname>
  1312  alter_sequence_stmt:
  1313    alter_rename_sequence_stmt
  1314  | alter_sequence_options_stmt
  1315  | ALTER SEQUENCE error // SHOW HELP: ALTER SEQUENCE
  1316  
  1317  alter_sequence_options_stmt:
  1318    ALTER SEQUENCE sequence_name sequence_option_list
  1319    {
  1320      $$.val = &tree.AlterSequence{Name: $3.unresolvedObjectName(), Options: $4.seqOpts(), IfExists: false}
  1321    }
  1322  | ALTER SEQUENCE IF EXISTS sequence_name sequence_option_list
  1323    {
  1324      $$.val = &tree.AlterSequence{Name: $5.unresolvedObjectName(), Options: $6.seqOpts(), IfExists: true}
  1325    }
  1326  
  1327  // %Help: ALTER DATABASE - change the definition of a database
  1328  // %Category: DDL
  1329  // %Text:
  1330  // ALTER DATABASE <name> RENAME TO <newname>
  1331  // %SeeAlso: WEBDOCS/alter-database.html
  1332  alter_database_stmt:
  1333    alter_rename_database_stmt
  1334  |  alter_zone_database_stmt
  1335  // ALTER DATABASE has its error help token here because the ALTER DATABASE
  1336  // prefix is spread over multiple non-terminals.
  1337  | ALTER DATABASE error // SHOW HELP: ALTER DATABASE
  1338  
  1339  // %Help: ALTER RANGE - change the parameters of a range
  1340  // %Category: DDL
  1341  // %Text:
  1342  // ALTER RANGE <zonename> <command>
  1343  //
  1344  // Commands:
  1345  //   ALTER RANGE ... CONFIGURE ZONE <zoneconfig>
  1346  //
  1347  // Zone configurations:
  1348  //   DISCARD
  1349  //   USING <var> = <expr> [, ...]
  1350  //   USING <var> = COPY FROM PARENT [, ...]
  1351  //   { TO | = } <expr>
  1352  //
  1353  // %SeeAlso: ALTER TABLE
  1354  alter_range_stmt:
  1355    alter_zone_range_stmt
  1356  | ALTER RANGE error // SHOW HELP: ALTER RANGE
  1357  
  1358  // %Help: ALTER INDEX - change the definition of an index
  1359  // %Category: DDL
  1360  // %Text:
  1361  // ALTER INDEX [IF EXISTS] <idxname> <command>
  1362  //
  1363  // Commands:
  1364  //   ALTER INDEX ... RENAME TO <newname>
  1365  //   ALTER INDEX ... SPLIT AT <selectclause> [WITH EXPIRATION <expr>]
  1366  //   ALTER INDEX ... UNSPLIT AT <selectclause>
  1367  //   ALTER INDEX ... UNSPLIT ALL
  1368  //   ALTER INDEX ... SCATTER [ FROM ( <exprs...> ) TO ( <exprs...> ) ]
  1369  //
  1370  // Zone configurations:
  1371  //   DISCARD
  1372  //   USING <var> = <expr> [, ...]
  1373  //   USING <var> = COPY FROM PARENT [, ...]
  1374  //   { TO | = } <expr>
  1375  //
  1376  // %SeeAlso: WEBDOCS/alter-index.html
  1377  alter_index_stmt:
  1378    alter_oneindex_stmt
  1379  | alter_relocate_index_stmt
  1380  | alter_relocate_index_lease_stmt
  1381  | alter_split_index_stmt
  1382  | alter_unsplit_index_stmt
  1383  | alter_scatter_index_stmt
  1384  | alter_rename_index_stmt
  1385  | alter_zone_index_stmt
  1386  // ALTER INDEX has its error help token here because the ALTER INDEX
  1387  // prefix is spread over multiple non-terminals.
  1388  | ALTER INDEX error // SHOW HELP: ALTER INDEX
  1389  
  1390  alter_onetable_stmt:
  1391    ALTER TABLE relation_expr alter_table_cmds
  1392    {
  1393      $$.val = &tree.AlterTable{Table: $3.unresolvedObjectName(), IfExists: false, Cmds: $4.alterTableCmds()}
  1394    }
  1395  | ALTER TABLE IF EXISTS relation_expr alter_table_cmds
  1396    {
  1397      $$.val = &tree.AlterTable{Table: $5.unresolvedObjectName(), IfExists: true, Cmds: $6.alterTableCmds()}
  1398    }
  1399  
  1400  alter_oneindex_stmt:
  1401    ALTER INDEX table_index_name alter_index_cmds
  1402    {
  1403      $$.val = &tree.AlterIndex{Index: $3.tableIndexName(), IfExists: false, Cmds: $4.alterIndexCmds()}
  1404    }
  1405  | ALTER INDEX IF EXISTS table_index_name alter_index_cmds
  1406    {
  1407      $$.val = &tree.AlterIndex{Index: $5.tableIndexName(), IfExists: true, Cmds: $6.alterIndexCmds()}
  1408    }
  1409  
  1410  alter_split_stmt:
  1411    ALTER TABLE table_name SPLIT AT select_stmt
  1412    {
  1413      name := $3.unresolvedObjectName().ToTableName()
  1414      $$.val = &tree.Split{
  1415        TableOrIndex: tree.TableIndexName{Table: name},
  1416        Rows: $6.slct(),
  1417        ExpireExpr: tree.Expr(nil),
  1418      }
  1419    }
  1420  | ALTER TABLE table_name SPLIT AT select_stmt WITH EXPIRATION a_expr
  1421    {
  1422      name := $3.unresolvedObjectName().ToTableName()
  1423      $$.val = &tree.Split{
  1424        TableOrIndex: tree.TableIndexName{Table: name},
  1425        Rows: $6.slct(),
  1426        ExpireExpr: $9.expr(),
  1427      }
  1428    }
  1429  
  1430  alter_split_index_stmt:
  1431    ALTER INDEX table_index_name SPLIT AT select_stmt
  1432    {
  1433      $$.val = &tree.Split{TableOrIndex: $3.tableIndexName(), Rows: $6.slct(), ExpireExpr: tree.Expr(nil)}
  1434    }
  1435  | ALTER INDEX table_index_name SPLIT AT select_stmt WITH EXPIRATION a_expr
  1436    {
  1437      $$.val = &tree.Split{TableOrIndex: $3.tableIndexName(), Rows: $6.slct(), ExpireExpr: $9.expr()}
  1438    }
  1439  
  1440  alter_unsplit_stmt:
  1441    ALTER TABLE table_name UNSPLIT AT select_stmt
  1442    {
  1443      name := $3.unresolvedObjectName().ToTableName()
  1444      $$.val = &tree.Unsplit{
  1445        TableOrIndex: tree.TableIndexName{Table: name},
  1446        Rows: $6.slct(),
  1447      }
  1448    }
  1449  | ALTER TABLE table_name UNSPLIT ALL
  1450    {
  1451      name := $3.unresolvedObjectName().ToTableName()
  1452      $$.val = &tree.Unsplit {
  1453        TableOrIndex: tree.TableIndexName{Table: name},
  1454        All: true,
  1455      }
  1456    }
  1457  
  1458  alter_unsplit_index_stmt:
  1459    ALTER INDEX table_index_name UNSPLIT AT select_stmt
  1460    {
  1461      $$.val = &tree.Unsplit{TableOrIndex: $3.tableIndexName(), Rows: $6.slct()}
  1462    }
  1463  | ALTER INDEX table_index_name UNSPLIT ALL
  1464    {
  1465      $$.val = &tree.Unsplit{TableOrIndex: $3.tableIndexName(), All: true}
  1466    }
  1467  
  1468  relocate_kw:
  1469    TESTING_RELOCATE
  1470  | EXPERIMENTAL_RELOCATE
  1471  
  1472  alter_relocate_stmt:
  1473    ALTER TABLE table_name relocate_kw select_stmt
  1474    {
  1475      /* SKIP DOC */
  1476      name := $3.unresolvedObjectName().ToTableName()
  1477      $$.val = &tree.Relocate{
  1478        TableOrIndex: tree.TableIndexName{Table: name},
  1479        Rows: $5.slct(),
  1480      }
  1481    }
  1482  
  1483  alter_relocate_index_stmt:
  1484    ALTER INDEX table_index_name relocate_kw select_stmt
  1485    {
  1486      /* SKIP DOC */
  1487      $$.val = &tree.Relocate{TableOrIndex: $3.tableIndexName(), Rows: $5.slct()}
  1488    }
  1489  
  1490  alter_relocate_lease_stmt:
  1491    ALTER TABLE table_name relocate_kw LEASE select_stmt
  1492    {
  1493      /* SKIP DOC */
  1494      name := $3.unresolvedObjectName().ToTableName()
  1495      $$.val = &tree.Relocate{
  1496        TableOrIndex: tree.TableIndexName{Table: name},
  1497        Rows: $6.slct(),
  1498        RelocateLease: true,
  1499      }
  1500    }
  1501  
  1502  alter_relocate_index_lease_stmt:
  1503    ALTER INDEX table_index_name relocate_kw LEASE select_stmt
  1504    {
  1505      /* SKIP DOC */
  1506      $$.val = &tree.Relocate{TableOrIndex: $3.tableIndexName(), Rows: $6.slct(), RelocateLease: true}
  1507    }
  1508  
  1509  alter_zone_range_stmt:
  1510    ALTER RANGE zone_name set_zone_config
  1511    {
  1512       s := $4.setZoneConfig()
  1513       s.ZoneSpecifier = tree.ZoneSpecifier{NamedZone: tree.UnrestrictedName($3)}
  1514       $$.val = s
  1515    }
  1516  
  1517  set_zone_config:
  1518    CONFIGURE ZONE to_or_eq a_expr
  1519    {
  1520      /* SKIP DOC */
  1521      $$.val = &tree.SetZoneConfig{YAMLConfig: $4.expr()}
  1522    }
  1523  | CONFIGURE ZONE USING var_set_list
  1524    {
  1525      $$.val = &tree.SetZoneConfig{Options: $4.kvOptions()}
  1526    }
  1527  | CONFIGURE ZONE USING DEFAULT
  1528    {
  1529      /* SKIP DOC */
  1530      $$.val = &tree.SetZoneConfig{SetDefault: true}
  1531    }
  1532  | CONFIGURE ZONE DISCARD
  1533    {
  1534      $$.val = &tree.SetZoneConfig{YAMLConfig: tree.DNull}
  1535    }
  1536  
  1537  alter_zone_database_stmt:
  1538    ALTER DATABASE database_name set_zone_config
  1539    {
  1540       s := $4.setZoneConfig()
  1541       s.ZoneSpecifier = tree.ZoneSpecifier{Database: tree.Name($3)}
  1542       $$.val = s
  1543    }
  1544  
  1545  alter_zone_table_stmt:
  1546    ALTER TABLE table_name set_zone_config
  1547    {
  1548      name := $3.unresolvedObjectName().ToTableName()
  1549      s := $4.setZoneConfig()
  1550      s.ZoneSpecifier = tree.ZoneSpecifier{
  1551         TableOrIndex: tree.TableIndexName{Table: name},
  1552      }
  1553      $$.val = s
  1554    }
  1555  
  1556  alter_zone_index_stmt:
  1557    ALTER INDEX table_index_name set_zone_config
  1558    {
  1559      s := $4.setZoneConfig()
  1560      s.ZoneSpecifier = tree.ZoneSpecifier{
  1561         TableOrIndex: $3.tableIndexName(),
  1562      }
  1563      $$.val = s
  1564    }
  1565  
  1566  alter_zone_partition_stmt:
  1567    ALTER PARTITION partition_name OF TABLE table_name set_zone_config
  1568    {
  1569      name := $6.unresolvedObjectName().ToTableName()
  1570      s := $7.setZoneConfig()
  1571      s.ZoneSpecifier = tree.ZoneSpecifier{
  1572         TableOrIndex: tree.TableIndexName{Table: name},
  1573         Partition: tree.Name($3),
  1574      }
  1575      $$.val = s
  1576    }
  1577  | ALTER PARTITION partition_name OF INDEX table_index_name set_zone_config
  1578    {
  1579      s := $7.setZoneConfig()
  1580      s.ZoneSpecifier = tree.ZoneSpecifier{
  1581         TableOrIndex: $6.tableIndexName(),
  1582         Partition: tree.Name($3),
  1583      }
  1584      $$.val = s
  1585    }
  1586  | ALTER PARTITION partition_name OF INDEX table_name '@' '*' set_zone_config
  1587    {
  1588      name := $6.unresolvedObjectName().ToTableName()
  1589      s := $9.setZoneConfig()
  1590      s.ZoneSpecifier = tree.ZoneSpecifier{
  1591         TableOrIndex: tree.TableIndexName{Table: name},
  1592         Partition: tree.Name($3),
  1593      }
  1594      s.AllIndexes = true
  1595      $$.val = s
  1596    }
  1597  | ALTER PARTITION partition_name OF TABLE table_name '@' error
  1598    {
  1599      err := errors.New("index name should not be specified in ALTER PARTITION ... OF TABLE")
  1600      err = errors.WithHint(err, "try ALTER PARTITION ... OF INDEX")
  1601      return setErr(sqllex, err)
  1602    }
  1603  | ALTER PARTITION partition_name OF TABLE table_name '@' '*' error
  1604    {
  1605      err := errors.New("index wildcard unsupported in ALTER PARTITION ... OF TABLE")
  1606      err = errors.WithHint(err, "try ALTER PARTITION <partition> OF INDEX <tablename>@*")
  1607      return setErr(sqllex, err)
  1608    }
  1609  
  1610  var_set_list:
  1611    var_name '=' COPY FROM PARENT
  1612    {
  1613      $$.val = []tree.KVOption{tree.KVOption{Key: tree.Name(strings.Join($1.strs(), "."))}}
  1614    }
  1615  | var_name '=' var_value
  1616    {
  1617      $$.val = []tree.KVOption{tree.KVOption{Key: tree.Name(strings.Join($1.strs(), ".")), Value: $3.expr()}}
  1618    }
  1619  | var_set_list ',' var_name '=' var_value
  1620    {
  1621      $$.val = append($1.kvOptions(), tree.KVOption{Key: tree.Name(strings.Join($3.strs(), ".")), Value: $5.expr()})
  1622    }
  1623  | var_set_list ',' var_name '=' COPY FROM PARENT
  1624    {
  1625      $$.val = append($1.kvOptions(), tree.KVOption{Key: tree.Name(strings.Join($3.strs(), "."))})
  1626    }
  1627  
  1628  alter_scatter_stmt:
  1629    ALTER TABLE table_name SCATTER
  1630    {
  1631      name := $3.unresolvedObjectName().ToTableName()
  1632      $$.val = &tree.Scatter{TableOrIndex: tree.TableIndexName{Table: name}}
  1633    }
  1634  | ALTER TABLE table_name SCATTER FROM '(' expr_list ')' TO '(' expr_list ')'
  1635    {
  1636      name := $3.unresolvedObjectName().ToTableName()
  1637      $$.val = &tree.Scatter{
  1638        TableOrIndex: tree.TableIndexName{Table: name},
  1639        From: $7.exprs(),
  1640        To: $11.exprs(),
  1641      }
  1642    }
  1643  
  1644  alter_scatter_index_stmt:
  1645    ALTER INDEX table_index_name SCATTER
  1646    {
  1647      $$.val = &tree.Scatter{TableOrIndex: $3.tableIndexName()}
  1648    }
  1649  | ALTER INDEX table_index_name SCATTER FROM '(' expr_list ')' TO '(' expr_list ')'
  1650    {
  1651      $$.val = &tree.Scatter{TableOrIndex: $3.tableIndexName(), From: $7.exprs(), To: $11.exprs()}
  1652    }
  1653  
  1654  alter_table_cmds:
  1655    alter_table_cmd
  1656    {
  1657      $$.val = tree.AlterTableCmds{$1.alterTableCmd()}
  1658    }
  1659  | alter_table_cmds ',' alter_table_cmd
  1660    {
  1661      $$.val = append($1.alterTableCmds(), $3.alterTableCmd())
  1662    }
  1663  
  1664  alter_table_cmd:
  1665    // ALTER TABLE <name> RENAME [COLUMN] <name> TO <newname>
  1666    RENAME opt_column column_name TO column_name
  1667    {
  1668      $$.val = &tree.AlterTableRenameColumn{Column: tree.Name($3), NewName: tree.Name($5) }
  1669    }
  1670    // ALTER TABLE <name> RENAME CONSTRAINT <name> TO <newname>
  1671  | RENAME CONSTRAINT column_name TO column_name
  1672    {
  1673      $$.val = &tree.AlterTableRenameConstraint{Constraint: tree.Name($3), NewName: tree.Name($5) }
  1674    }
  1675    // ALTER TABLE <name> ADD <coldef>
  1676  | ADD column_def
  1677    {
  1678      $$.val = &tree.AlterTableAddColumn{IfNotExists: false, ColumnDef: $2.colDef()}
  1679    }
  1680    // ALTER TABLE <name> ADD IF NOT EXISTS <coldef>
  1681  | ADD IF NOT EXISTS column_def
  1682    {
  1683      $$.val = &tree.AlterTableAddColumn{IfNotExists: true, ColumnDef: $5.colDef()}
  1684    }
  1685    // ALTER TABLE <name> ADD COLUMN <coldef>
  1686  | ADD COLUMN column_def
  1687    {
  1688      $$.val = &tree.AlterTableAddColumn{IfNotExists: false, ColumnDef: $3.colDef()}
  1689    }
  1690    // ALTER TABLE <name> ADD COLUMN IF NOT EXISTS <coldef>
  1691  | ADD COLUMN IF NOT EXISTS column_def
  1692    {
  1693      $$.val = &tree.AlterTableAddColumn{IfNotExists: true, ColumnDef: $6.colDef()}
  1694    }
  1695    // ALTER TABLE <name> ALTER [COLUMN] <colname> {SET DEFAULT <expr>|DROP DEFAULT}
  1696  | ALTER opt_column column_name alter_column_default
  1697    {
  1698      $$.val = &tree.AlterTableSetDefault{Column: tree.Name($3), Default: $4.expr()}
  1699    }
  1700    // ALTER TABLE <name> ALTER [COLUMN] <colname> DROP NOT NULL
  1701  | ALTER opt_column column_name DROP NOT NULL
  1702    {
  1703      $$.val = &tree.AlterTableDropNotNull{Column: tree.Name($3)}
  1704    }
  1705    // ALTER TABLE <name> ALTER [COLUMN] <colname> DROP STORED
  1706  | ALTER opt_column column_name DROP STORED
  1707    {
  1708      $$.val = &tree.AlterTableDropStored{Column: tree.Name($3)}
  1709    }
  1710    // ALTER TABLE <name> ALTER [COLUMN] <colname> SET NOT NULL
  1711  | ALTER opt_column column_name SET NOT NULL
  1712    {
  1713      $$.val = &tree.AlterTableSetNotNull{Column: tree.Name($3)}
  1714    }
  1715    // ALTER TABLE <name> DROP [COLUMN] IF EXISTS <colname> [RESTRICT|CASCADE]
  1716  | DROP opt_column IF EXISTS column_name opt_drop_behavior
  1717    {
  1718      $$.val = &tree.AlterTableDropColumn{
  1719        IfExists: true,
  1720        Column: tree.Name($5),
  1721        DropBehavior: $6.dropBehavior(),
  1722      }
  1723    }
  1724    // ALTER TABLE <name> DROP [COLUMN] <colname> [RESTRICT|CASCADE]
  1725  | DROP opt_column column_name opt_drop_behavior
  1726    {
  1727      $$.val = &tree.AlterTableDropColumn{
  1728        IfExists: false,
  1729        Column: tree.Name($3),
  1730        DropBehavior: $4.dropBehavior(),
  1731      }
  1732    }
  1733    // ALTER TABLE <name> ALTER [COLUMN] <colname>
  1734    //     [SET DATA] TYPE <typename>
  1735    //     [ COLLATE collation ]
  1736    //     [ USING <expression> ]
  1737  | ALTER opt_column column_name opt_set_data TYPE typename opt_collate opt_alter_column_using
  1738    {
  1739      $$.val = &tree.AlterTableAlterColumnType{
  1740        Column: tree.Name($3),
  1741        ToType: $6.typeReference(),
  1742        Collation: $7,
  1743        Using: $8.expr(),
  1744      }
  1745    }
  1746    // ALTER TABLE <name> ADD CONSTRAINT ...
  1747  | ADD table_constraint opt_validate_behavior
  1748    {
  1749      $$.val = &tree.AlterTableAddConstraint{
  1750        ConstraintDef: $2.constraintDef(),
  1751        ValidationBehavior: $3.validationBehavior(),
  1752      }
  1753    }
  1754    // ALTER TABLE <name> ALTER CONSTRAINT ...
  1755  | ALTER CONSTRAINT constraint_name error { return unimplementedWithIssueDetail(sqllex, 31632, "alter constraint") }
  1756    // ALTER TABLE <name> VALIDATE CONSTRAINT ...
  1757    // ALTER TABLE <name> ALTER PRIMARY KEY USING INDEX <name>
  1758  | ALTER PRIMARY KEY USING COLUMNS '(' index_params ')' opt_hash_sharded opt_interleave
  1759    {
  1760      $$.val = &tree.AlterTableAlterPrimaryKey{
  1761        Columns: $7.idxElems(),
  1762        Sharded: $9.shardedIndexDef(),
  1763        Interleave: $10.interleave(),
  1764      }
  1765    }
  1766  | VALIDATE CONSTRAINT constraint_name
  1767    {
  1768      $$.val = &tree.AlterTableValidateConstraint{
  1769        Constraint: tree.Name($3),
  1770      }
  1771    }
  1772    // ALTER TABLE <name> DROP CONSTRAINT IF EXISTS <name> [RESTRICT|CASCADE]
  1773  | DROP CONSTRAINT IF EXISTS constraint_name opt_drop_behavior
  1774    {
  1775      $$.val = &tree.AlterTableDropConstraint{
  1776        IfExists: true,
  1777        Constraint: tree.Name($5),
  1778        DropBehavior: $6.dropBehavior(),
  1779      }
  1780    }
  1781    // ALTER TABLE <name> DROP CONSTRAINT <name> [RESTRICT|CASCADE]
  1782  | DROP CONSTRAINT constraint_name opt_drop_behavior
  1783    {
  1784      $$.val = &tree.AlterTableDropConstraint{
  1785        IfExists: false,
  1786        Constraint: tree.Name($3),
  1787        DropBehavior: $4.dropBehavior(),
  1788      }
  1789    }
  1790    // ALTER TABLE <name> EXPERIMENTAL_AUDIT SET <mode>
  1791  | EXPERIMENTAL_AUDIT SET audit_mode
  1792    {
  1793      $$.val = &tree.AlterTableSetAudit{Mode: $3.auditMode()}
  1794    }
  1795    // ALTER TABLE <name> PARTITION BY ...
  1796  | partition_by
  1797    {
  1798      $$.val = &tree.AlterTablePartitionBy{
  1799        PartitionBy: $1.partitionBy(),
  1800      }
  1801    }
  1802    // ALTER TABLE <name> INJECT STATISTICS <json>
  1803  | INJECT STATISTICS a_expr
  1804    {
  1805      /* SKIP DOC */
  1806      $$.val = &tree.AlterTableInjectStats{
  1807        Stats: $3.expr(),
  1808      }
  1809    }
  1810  
  1811  audit_mode:
  1812    READ WRITE { $$.val = tree.AuditModeReadWrite }
  1813  | OFF        { $$.val = tree.AuditModeDisable }
  1814  
  1815  alter_index_cmds:
  1816    alter_index_cmd
  1817    {
  1818      $$.val = tree.AlterIndexCmds{$1.alterIndexCmd()}
  1819    }
  1820  | alter_index_cmds ',' alter_index_cmd
  1821    {
  1822      $$.val = append($1.alterIndexCmds(), $3.alterIndexCmd())
  1823    }
  1824  
  1825  alter_index_cmd:
  1826    partition_by
  1827    {
  1828      $$.val = &tree.AlterIndexPartitionBy{
  1829        PartitionBy: $1.partitionBy(),
  1830      }
  1831    }
  1832  
  1833  alter_column_default:
  1834    SET DEFAULT a_expr
  1835    {
  1836      $$.val = $3.expr()
  1837    }
  1838  | DROP DEFAULT
  1839    {
  1840      $$.val = nil
  1841    }
  1842  
  1843  opt_alter_column_using:
  1844    USING a_expr
  1845    {
  1846       $$.val = $2.expr()
  1847    }
  1848  | /* EMPTY */
  1849    {
  1850       $$.val = nil
  1851    }
  1852  
  1853  
  1854  opt_drop_behavior:
  1855    CASCADE
  1856    {
  1857      $$.val = tree.DropCascade
  1858    }
  1859  | RESTRICT
  1860    {
  1861      $$.val = tree.DropRestrict
  1862    }
  1863  | /* EMPTY */
  1864    {
  1865      $$.val = tree.DropDefault
  1866    }
  1867  
  1868  opt_validate_behavior:
  1869    NOT VALID
  1870    {
  1871      $$.val = tree.ValidationSkip
  1872    }
  1873  | /* EMPTY */
  1874    {
  1875      $$.val = tree.ValidationDefault
  1876    }
  1877  
  1878  // %Help: ALTER TYPE - change the definition of a type.
  1879  // %Category: DDL
  1880  // %Text: ALTER TYPE <typename> <command>
  1881  //
  1882  // Commands:
  1883  //   ALTER TYPE ... ADD VALUE [IF NOT EXISTS] <value> [ { BEFORE | AFTER } <value> ]
  1884  //   ALTER TYPE ... RENAME VALUE <oldname> TO <newname>
  1885  //   ALTER TYPE ... RENAME TO <newname>
  1886  //   ALTER TYPE ... SET SCHEMA <newschemaname>
  1887  //   ALTER TYPE ... OWNER TO {<newowner> | CURRENT_USER | SESSION_USER }
  1888  //   ALTER TYPE ... RENAME ATTRIBUTE <oldname> TO <newname> [ CASCADE | RESTRICT ]
  1889  //   ALTER TYPE ... <attributeaction> [, ... ]
  1890  //
  1891  // Attribute action:
  1892  //   ADD ATTRIBUTE <name> <type> [ COLLATE <collation> ] [ CASCADE | RESTRICT ]
  1893  //   DROP ATTRIBUTE [IF EXISTS] <name> [ CASCADE | RESTRICT ]
  1894  //   ALTER ATTRIBUTE <name> [ SET DATA ] TYPE <type> [ COLLATE <collation> ] [ CASCADE | RESTRICT ]
  1895  //
  1896  // %SeeAlso: WEBDOCS/alter-type.html
  1897  alter_type_stmt:
  1898    ALTER TYPE type_name ADD VALUE SCONST opt_add_val_placement
  1899    {
  1900      $$.val = &tree.AlterType{
  1901        Type: $3.unresolvedObjectName(),
  1902        Cmd: &tree.AlterTypeAddValue{
  1903          NewVal: $6,
  1904          IfNotExists: false,
  1905          Placement: $7.alterTypeAddValuePlacement(),
  1906        },
  1907      }
  1908    }
  1909  | ALTER TYPE type_name ADD VALUE IF NOT EXISTS SCONST opt_add_val_placement
  1910    {
  1911      $$.val = &tree.AlterType{
  1912        Type: $3.unresolvedObjectName(),
  1913        Cmd: &tree.AlterTypeAddValue{
  1914          NewVal: $9,
  1915          IfNotExists: true,
  1916          Placement: $10.alterTypeAddValuePlacement(),
  1917        },
  1918      }
  1919    }
  1920  | ALTER TYPE type_name RENAME VALUE SCONST TO SCONST
  1921    {
  1922      $$.val = &tree.AlterType{
  1923        Type: $3.unresolvedObjectName(),
  1924        Cmd: &tree.AlterTypeRenameValue{
  1925          OldVal: $6,
  1926          NewVal: $8,
  1927        },
  1928      }
  1929    }
  1930  | ALTER TYPE type_name RENAME TO type_name
  1931    {
  1932      $$.val = &tree.AlterType{
  1933        Type: $3.unresolvedObjectName(),
  1934        Cmd: &tree.AlterTypeRename{
  1935          NewName: $6.unresolvedObjectName(),
  1936        },
  1937      }
  1938    }
  1939  | ALTER TYPE type_name SET SCHEMA schema_name
  1940    {
  1941      $$.val = &tree.AlterType{
  1942        Type: $3.unresolvedObjectName(),
  1943        Cmd: &tree.AlterTypeSetSchema{
  1944          Schema: $6,
  1945        },
  1946      }
  1947    }
  1948  | ALTER TYPE type_name OWNER TO role_spec
  1949    {
  1950      return unimplementedWithIssueDetail(sqllex, 48700, "ALTER TYPE OWNER TO")
  1951    }
  1952  | ALTER TYPE type_name RENAME ATTRIBUTE column_name TO column_name opt_drop_behavior
  1953    {
  1954      return unimplementedWithIssueDetail(sqllex, 48701, "ALTER TYPE ATTRIBUTE")
  1955    }
  1956  | ALTER TYPE type_name alter_attribute_action_list
  1957    {
  1958      return unimplementedWithIssueDetail(sqllex, 48701, "ALTER TYPE ATTRIBUTE")
  1959    }
  1960  | ALTER TYPE error // SHOW HELP: ALTER TYPE
  1961  
  1962  opt_add_val_placement:
  1963    BEFORE SCONST
  1964    {
  1965      $$.val = &tree.AlterTypeAddValuePlacement{
  1966         Before: true,
  1967         ExistingVal: $2,
  1968      }
  1969    }
  1970  | AFTER SCONST
  1971    {
  1972      $$.val = &tree.AlterTypeAddValuePlacement{
  1973         Before: false,
  1974         ExistingVal: $2,
  1975      }
  1976    }
  1977  | /* EMPTY */
  1978    {
  1979      $$.val = (*tree.AlterTypeAddValuePlacement)(nil)
  1980    }
  1981  
  1982  role_spec:
  1983    non_reserved_word_or_sconst
  1984  | CURRENT_USER
  1985  | SESSION_USER
  1986  
  1987  alter_attribute_action_list:
  1988    alter_attribute_action
  1989  | alter_attribute_action_list ',' alter_attribute_action
  1990  
  1991  alter_attribute_action:
  1992    ADD ATTRIBUTE column_name type_name opt_collate opt_drop_behavior
  1993  | DROP ATTRIBUTE column_name opt_drop_behavior
  1994  | DROP ATTRIBUTE IF EXISTS column_name opt_drop_behavior
  1995  | ALTER ATTRIBUTE column_name TYPE type_name opt_collate opt_drop_behavior
  1996  | ALTER ATTRIBUTE column_name SET DATA TYPE type_name opt_collate opt_drop_behavior
  1997  
  1998  // %Help: BACKUP - back up data to external storage
  1999  // %Category: CCL
  2000  // %Text:
  2001  // BACKUP <targets...> TO <location...>
  2002  //        [ AS OF SYSTEM TIME <expr> ]
  2003  //        [ INCREMENTAL FROM <location...> ]
  2004  //        [ WITH <option> [= <value>] [, ...] ]
  2005  //
  2006  // Targets:
  2007  //    TABLE <pattern> [, ...]
  2008  //    DATABASE <databasename> [, ...]
  2009  //
  2010  // Location:
  2011  //    "[scheme]://[host]/[path to backup]?[parameters]"
  2012  //
  2013  // Options:
  2014  //    INTO_DB
  2015  //    SKIP_MISSING_FOREIGN_KEYS
  2016  //
  2017  // %SeeAlso: RESTORE, WEBDOCS/backup.html
  2018  backup_stmt:
  2019    BACKUP TO partitioned_backup opt_as_of_clause opt_incremental opt_with_options
  2020    {
  2021      $$.val = &tree.Backup{DescriptorCoverage: tree.AllDescriptors, To: $3.partitionedBackup(), IncrementalFrom: $5.exprs(), AsOf: $4.asOfClause(), Options: $6.kvOptions()}
  2022    }
  2023  | BACKUP targets TO partitioned_backup opt_as_of_clause opt_incremental opt_with_options
  2024    {
  2025      $$.val = &tree.Backup{Targets: $2.targetList(), To: $4.partitionedBackup(), IncrementalFrom: $6.exprs(), AsOf: $5.asOfClause(), Options: $7.kvOptions()}
  2026    }
  2027  | BACKUP error // SHOW HELP: BACKUP
  2028  
  2029  // %Help: RESTORE - restore data from external storage
  2030  // %Category: CCL
  2031  // %Text:
  2032  // RESTORE <targets...> FROM <location...>
  2033  //         [ AS OF SYSTEM TIME <expr> ]
  2034  //         [ WITH <option> [= <value>] [, ...] ]
  2035  //
  2036  // Targets:
  2037  //    TABLE <pattern> [, ...]
  2038  //    DATABASE <databasename> [, ...]
  2039  //
  2040  // Locations:
  2041  //    "[scheme]://[host]/[path to backup]?[parameters]"
  2042  //
  2043  // Options:
  2044  //    INTO_DB
  2045  //    SKIP_MISSING_FOREIGN_KEYS
  2046  //
  2047  // %SeeAlso: BACKUP, WEBDOCS/restore.html
  2048  restore_stmt:
  2049    RESTORE FROM partitioned_backup_list opt_as_of_clause opt_with_options
  2050    {
  2051      $$.val = &tree.Restore{DescriptorCoverage: tree.AllDescriptors, From: $3.partitionedBackups(), AsOf: $4.asOfClause(), Options: $5.kvOptions()}
  2052    }
  2053  | RESTORE targets FROM partitioned_backup_list opt_as_of_clause opt_with_options
  2054    {
  2055      $$.val = &tree.Restore{Targets: $2.targetList(), From: $4.partitionedBackups(), AsOf: $5.asOfClause(), Options: $6.kvOptions()}
  2056    }
  2057  | RESTORE error // SHOW HELP: RESTORE
  2058  
  2059  partitioned_backup:
  2060    string_or_placeholder
  2061    {
  2062      $$.val = tree.PartitionedBackup{$1.expr()}
  2063    }
  2064  | '(' string_or_placeholder_list ')'
  2065    {
  2066      $$.val = tree.PartitionedBackup($2.exprs())
  2067    }
  2068  
  2069  partitioned_backup_list:
  2070    partitioned_backup
  2071    {
  2072      $$.val = []tree.PartitionedBackup{$1.partitionedBackup()}
  2073    }
  2074  | partitioned_backup_list ',' partitioned_backup
  2075    {
  2076      $$.val = append($1.partitionedBackups(), $3.partitionedBackup())
  2077    }
  2078  
  2079  import_format:
  2080    name
  2081    {
  2082      $$ = strings.ToUpper($1)
  2083    }
  2084  
  2085  // %Help: IMPORT - load data from file in a distributed manner
  2086  // %Category: CCL
  2087  // %Text:
  2088  // -- Import both schema and table data:
  2089  // IMPORT [ TABLE <tablename> FROM ]
  2090  //        <format> <datafile>
  2091  //        [ WITH <option> [= <value>] [, ...] ]
  2092  //
  2093  // -- Import using specific schema, use only table data from external file:
  2094  // IMPORT TABLE <tablename>
  2095  //        { ( <elements> ) | CREATE USING <schemafile> }
  2096  //        <format>
  2097  //        DATA ( <datafile> [, ...] )
  2098  //        [ WITH <option> [= <value>] [, ...] ]
  2099  //
  2100  // Formats:
  2101  //    CSV
  2102  //    DELIMITED
  2103  //    MYSQLDUMP
  2104  //    PGCOPY
  2105  //    PGDUMP
  2106  //
  2107  // Options:
  2108  //    distributed = '...'
  2109  //    sstsize = '...'
  2110  //    temp = '...'
  2111  //    delimiter = '...'      [CSV, PGCOPY-specific]
  2112  //    nullif = '...'         [CSV, PGCOPY-specific]
  2113  //    comment = '...'        [CSV-specific]
  2114  //
  2115  // %SeeAlso: CREATE TABLE
  2116  import_stmt:
  2117   IMPORT import_format '(' string_or_placeholder ')' opt_with_options
  2118    {
  2119      /* SKIP DOC */
  2120      $$.val = &tree.Import{Bundle: true, FileFormat: $2, Files: tree.Exprs{$4.expr()}, Options: $6.kvOptions()}
  2121    }
  2122  | IMPORT import_format string_or_placeholder opt_with_options
  2123    {
  2124      $$.val = &tree.Import{Bundle: true, FileFormat: $2, Files: tree.Exprs{$3.expr()}, Options: $4.kvOptions()}
  2125    }
  2126  | IMPORT TABLE table_name FROM import_format '(' string_or_placeholder ')' opt_with_options
  2127    {
  2128      /* SKIP DOC */
  2129      name := $3.unresolvedObjectName().ToTableName()
  2130      $$.val = &tree.Import{Bundle: true, Table: &name, FileFormat: $5, Files: tree.Exprs{$7.expr()}, Options: $9.kvOptions()}
  2131    }
  2132  | IMPORT TABLE table_name FROM import_format string_or_placeholder opt_with_options
  2133    {
  2134      name := $3.unresolvedObjectName().ToTableName()
  2135      $$.val = &tree.Import{Bundle: true, Table: &name, FileFormat: $5, Files: tree.Exprs{$6.expr()}, Options: $7.kvOptions()}
  2136    }
  2137  | IMPORT TABLE table_name CREATE USING string_or_placeholder import_format DATA '(' string_or_placeholder_list ')' opt_with_options
  2138    {
  2139      name := $3.unresolvedObjectName().ToTableName()
  2140      $$.val = &tree.Import{Table: &name, CreateFile: $6.expr(), FileFormat: $7, Files: $10.exprs(), Options: $12.kvOptions()}
  2141    }
  2142  | IMPORT TABLE table_name '(' table_elem_list ')' import_format DATA '(' string_or_placeholder_list ')' opt_with_options
  2143    {
  2144      name := $3.unresolvedObjectName().ToTableName()
  2145      $$.val = &tree.Import{Table: &name, CreateDefs: $5.tblDefs(), FileFormat: $7, Files: $10.exprs(), Options: $12.kvOptions()}
  2146    }
  2147  | IMPORT INTO table_name '(' insert_column_list ')' import_format DATA '(' string_or_placeholder_list ')' opt_with_options
  2148    {
  2149      name := $3.unresolvedObjectName().ToTableName()
  2150      $$.val = &tree.Import{Table: &name, Into: true, IntoCols: $5.nameList(), FileFormat: $7, Files: $10.exprs(), Options: $12.kvOptions()}
  2151    }
  2152  | IMPORT INTO table_name import_format DATA '(' string_or_placeholder_list ')' opt_with_options
  2153    {
  2154      name := $3.unresolvedObjectName().ToTableName()
  2155      $$.val = &tree.Import{Table: &name, Into: true, IntoCols: nil, FileFormat: $4, Files: $7.exprs(), Options: $9.kvOptions()}
  2156    }
  2157  | IMPORT error // SHOW HELP: IMPORT
  2158  
  2159  // %Help: EXPORT - export data to file in a distributed manner
  2160  // %Category: CCL
  2161  // %Text:
  2162  // EXPORT INTO <format> <datafile> [WITH <option> [= value] [,...]] FROM <query>
  2163  //
  2164  // Formats:
  2165  //    CSV
  2166  //
  2167  // Options:
  2168  //    delimiter = '...'   [CSV-specific]
  2169  //
  2170  // %SeeAlso: SELECT
  2171  export_stmt:
  2172    EXPORT INTO import_format string_or_placeholder opt_with_options FROM select_stmt
  2173    {
  2174      $$.val = &tree.Export{Query: $7.slct(), FileFormat: $3, File: $4.expr(), Options: $5.kvOptions()}
  2175    }
  2176  | EXPORT error // SHOW HELP: EXPORT
  2177  
  2178  string_or_placeholder:
  2179    non_reserved_word_or_sconst
  2180    {
  2181      $$.val = tree.NewStrVal($1)
  2182    }
  2183  | PLACEHOLDER
  2184    {
  2185      p := $1.placeholder()
  2186      sqllex.(*lexer).UpdateNumPlaceholders(p)
  2187      $$.val = p
  2188    }
  2189  
  2190  string_or_placeholder_list:
  2191    string_or_placeholder
  2192    {
  2193      $$.val = tree.Exprs{$1.expr()}
  2194    }
  2195  | string_or_placeholder_list ',' string_or_placeholder
  2196    {
  2197      $$.val = append($1.exprs(), $3.expr())
  2198    }
  2199  
  2200  opt_incremental:
  2201    INCREMENTAL FROM string_or_placeholder_list
  2202    {
  2203      $$.val = $3.exprs()
  2204    }
  2205  | /* EMPTY */
  2206    {
  2207      $$.val = tree.Exprs(nil)
  2208    }
  2209  
  2210  kv_option:
  2211    name '=' string_or_placeholder
  2212    {
  2213      $$.val = tree.KVOption{Key: tree.Name($1), Value: $3.expr()}
  2214    }
  2215  |  name
  2216    {
  2217      $$.val = tree.KVOption{Key: tree.Name($1)}
  2218    }
  2219  |  SCONST '=' string_or_placeholder
  2220    {
  2221      $$.val = tree.KVOption{Key: tree.Name($1), Value: $3.expr()}
  2222    }
  2223  |  SCONST
  2224    {
  2225      $$.val = tree.KVOption{Key: tree.Name($1)}
  2226    }
  2227  
  2228  kv_option_list:
  2229    kv_option
  2230    {
  2231      $$.val = []tree.KVOption{$1.kvOption()}
  2232    }
  2233  |  kv_option_list ',' kv_option
  2234    {
  2235      $$.val = append($1.kvOptions(), $3.kvOption())
  2236    }
  2237  
  2238  opt_with_options:
  2239    WITH kv_option_list
  2240    {
  2241      $$.val = $2.kvOptions()
  2242    }
  2243  | WITH OPTIONS '(' kv_option_list ')'
  2244    {
  2245      $$.val = $4.kvOptions()
  2246    }
  2247  | /* EMPTY */
  2248    {
  2249      $$.val = nil
  2250    }
  2251  
  2252  copy_from_stmt:
  2253    COPY table_name opt_column_list FROM STDIN opt_with_options
  2254    {
  2255      name := $2.unresolvedObjectName().ToTableName()
  2256      $$.val = &tree.CopyFrom{
  2257         Table: name,
  2258         Columns: $3.nameList(),
  2259         Stdin: true,
  2260         Options: $6.kvOptions(),
  2261      }
  2262    }
  2263  
  2264  // %Help: CANCEL
  2265  // %Category: Group
  2266  // %Text: CANCEL JOBS, CANCEL QUERIES, CANCEL SESSIONS
  2267  cancel_stmt:
  2268    cancel_jobs_stmt     // EXTEND WITH HELP: CANCEL JOBS
  2269  | cancel_queries_stmt  // EXTEND WITH HELP: CANCEL QUERIES
  2270  | cancel_sessions_stmt // EXTEND WITH HELP: CANCEL SESSIONS
  2271  | CANCEL error         // SHOW HELP: CANCEL
  2272  
  2273  // %Help: CANCEL JOBS - cancel background jobs
  2274  // %Category: Misc
  2275  // %Text:
  2276  // CANCEL JOBS <selectclause>
  2277  // CANCEL JOB <jobid>
  2278  // %SeeAlso: SHOW JOBS, PAUSE JOBS, RESUME JOBS
  2279  cancel_jobs_stmt:
  2280    CANCEL JOB a_expr
  2281    {
  2282      $$.val = &tree.ControlJobs{
  2283        Jobs: &tree.Select{
  2284          Select: &tree.ValuesClause{Rows: []tree.Exprs{tree.Exprs{$3.expr()}}},
  2285        },
  2286        Command: tree.CancelJob,
  2287      }
  2288    }
  2289  | CANCEL JOB error // SHOW HELP: CANCEL JOBS
  2290  | CANCEL JOBS select_stmt
  2291    {
  2292      $$.val = &tree.ControlJobs{Jobs: $3.slct(), Command: tree.CancelJob}
  2293    }
  2294  | CANCEL JOBS error // SHOW HELP: CANCEL JOBS
  2295  
  2296  // %Help: CANCEL QUERIES - cancel running queries
  2297  // %Category: Misc
  2298  // %Text:
  2299  // CANCEL QUERIES [IF EXISTS] <selectclause>
  2300  // CANCEL QUERY [IF EXISTS] <expr>
  2301  // %SeeAlso: SHOW QUERIES
  2302  cancel_queries_stmt:
  2303    CANCEL QUERY a_expr
  2304    {
  2305      $$.val = &tree.CancelQueries{
  2306        Queries: &tree.Select{
  2307          Select: &tree.ValuesClause{Rows: []tree.Exprs{tree.Exprs{$3.expr()}}},
  2308        },
  2309        IfExists: false,
  2310      }
  2311    }
  2312  | CANCEL QUERY IF EXISTS a_expr
  2313    {
  2314      $$.val = &tree.CancelQueries{
  2315        Queries: &tree.Select{
  2316          Select: &tree.ValuesClause{Rows: []tree.Exprs{tree.Exprs{$5.expr()}}},
  2317        },
  2318        IfExists: true,
  2319      }
  2320    }
  2321  | CANCEL QUERY error // SHOW HELP: CANCEL QUERIES
  2322  | CANCEL QUERIES select_stmt
  2323    {
  2324      $$.val = &tree.CancelQueries{Queries: $3.slct(), IfExists: false}
  2325    }
  2326  | CANCEL QUERIES IF EXISTS select_stmt
  2327    {
  2328      $$.val = &tree.CancelQueries{Queries: $5.slct(), IfExists: true}
  2329    }
  2330  | CANCEL QUERIES error // SHOW HELP: CANCEL QUERIES
  2331  
  2332  // %Help: CANCEL SESSIONS - cancel open sessions
  2333  // %Category: Misc
  2334  // %Text:
  2335  // CANCEL SESSIONS [IF EXISTS] <selectclause>
  2336  // CANCEL SESSION [IF EXISTS] <sessionid>
  2337  // %SeeAlso: SHOW SESSIONS
  2338  cancel_sessions_stmt:
  2339    CANCEL SESSION a_expr
  2340    {
  2341     $$.val = &tree.CancelSessions{
  2342        Sessions: &tree.Select{
  2343          Select: &tree.ValuesClause{Rows: []tree.Exprs{tree.Exprs{$3.expr()}}},
  2344        },
  2345        IfExists: false,
  2346      }
  2347    }
  2348  | CANCEL SESSION IF EXISTS a_expr
  2349    {
  2350     $$.val = &tree.CancelSessions{
  2351        Sessions: &tree.Select{
  2352          Select: &tree.ValuesClause{Rows: []tree.Exprs{tree.Exprs{$5.expr()}}},
  2353        },
  2354        IfExists: true,
  2355      }
  2356    }
  2357  | CANCEL SESSION error // SHOW HELP: CANCEL SESSIONS
  2358  | CANCEL SESSIONS select_stmt
  2359    {
  2360      $$.val = &tree.CancelSessions{Sessions: $3.slct(), IfExists: false}
  2361    }
  2362  | CANCEL SESSIONS IF EXISTS select_stmt
  2363    {
  2364      $$.val = &tree.CancelSessions{Sessions: $5.slct(), IfExists: true}
  2365    }
  2366  | CANCEL SESSIONS error // SHOW HELP: CANCEL SESSIONS
  2367  
  2368  comment_stmt:
  2369    COMMENT ON DATABASE database_name IS comment_text
  2370    {
  2371      $$.val = &tree.CommentOnDatabase{Name: tree.Name($4), Comment: $6.strPtr()}
  2372    }
  2373  | COMMENT ON TABLE table_name IS comment_text
  2374    {
  2375      $$.val = &tree.CommentOnTable{Table: $4.unresolvedObjectName(), Comment: $6.strPtr()}
  2376    }
  2377  | COMMENT ON COLUMN column_path IS comment_text
  2378    {
  2379      varName, err := $4.unresolvedName().NormalizeVarName()
  2380      if err != nil {
  2381        return setErr(sqllex, err)
  2382      }
  2383      columnItem, ok := varName.(*tree.ColumnItem)
  2384      if !ok {
  2385        sqllex.Error(fmt.Sprintf("invalid column name: %q", tree.ErrString($4.unresolvedName())))
  2386              return 1
  2387      }
  2388      $$.val = &tree.CommentOnColumn{ColumnItem: columnItem, Comment: $6.strPtr()}
  2389    }
  2390  | COMMENT ON INDEX table_index_name IS comment_text
  2391    {
  2392      $$.val = &tree.CommentOnIndex{Index: $4.tableIndexName(), Comment: $6.strPtr()}
  2393    }
  2394  
  2395  comment_text:
  2396    SCONST
  2397    {
  2398      t := $1
  2399      $$.val = &t
  2400    }
  2401  | NULL
  2402    {
  2403      var str *string
  2404      $$.val = str
  2405    }
  2406  
  2407  // %Help: CREATE
  2408  // %Category: Group
  2409  // %Text:
  2410  // CREATE DATABASE, CREATE TABLE, CREATE INDEX, CREATE TABLE AS,
  2411  // CREATE USER, CREATE VIEW, CREATE SEQUENCE, CREATE STATISTICS,
  2412  // CREATE ROLE, CREATE TYPE
  2413  create_stmt:
  2414    create_role_stmt     // EXTEND WITH HELP: CREATE ROLE
  2415  | create_ddl_stmt      // help texts in sub-rule
  2416  | create_stats_stmt    // EXTEND WITH HELP: CREATE STATISTICS
  2417  | create_unsupported   {}
  2418  | CREATE error         // SHOW HELP: CREATE
  2419  
  2420  create_unsupported:
  2421    CREATE AGGREGATE error { return unimplemented(sqllex, "create aggregate") }
  2422  | CREATE CAST error { return unimplemented(sqllex, "create cast") }
  2423  | CREATE CONSTRAINT TRIGGER error { return unimplementedWithIssueDetail(sqllex, 28296, "create constraint") }
  2424  | CREATE CONVERSION error { return unimplemented(sqllex, "create conversion") }
  2425  | CREATE DEFAULT CONVERSION error { return unimplemented(sqllex, "create def conv") }
  2426  | CREATE EXTENSION IF NOT EXISTS name error { return unimplemented(sqllex, "create extension " + $6) }
  2427  | CREATE EXTENSION name error { return unimplemented(sqllex, "create extension " + $3) }
  2428  | CREATE FOREIGN TABLE error { return unimplemented(sqllex, "create foreign table") }
  2429  | CREATE FOREIGN DATA error { return unimplemented(sqllex, "create fdw") }
  2430  | CREATE FUNCTION error { return unimplementedWithIssueDetail(sqllex, 17511, "create function") }
  2431  | CREATE OR REPLACE FUNCTION error { return unimplementedWithIssueDetail(sqllex, 17511, "create function") }
  2432  | CREATE opt_or_replace opt_trusted opt_procedural LANGUAGE name error { return unimplementedWithIssueDetail(sqllex, 17511, "create language " + $6) }
  2433  | CREATE MATERIALIZED VIEW error { return unimplementedWithIssue(sqllex, 41649) }
  2434  | CREATE OPERATOR error { return unimplemented(sqllex, "create operator") }
  2435  | CREATE PUBLICATION error { return unimplemented(sqllex, "create publication") }
  2436  | CREATE opt_or_replace RULE error { return unimplemented(sqllex, "create rule") }
  2437  | CREATE SERVER error { return unimplemented(sqllex, "create server") }
  2438  | CREATE SUBSCRIPTION error { return unimplemented(sqllex, "create subscription") }
  2439  | CREATE TEXT error { return unimplementedWithIssueDetail(sqllex, 7821, "create text") }
  2440  | CREATE TRIGGER error { return unimplementedWithIssueDetail(sqllex, 28296, "create") }
  2441  
  2442  opt_or_replace:
  2443    OR REPLACE {}
  2444  | /* EMPTY */ {}
  2445  
  2446  opt_trusted:
  2447    TRUSTED {}
  2448  | /* EMPTY */ {}
  2449  
  2450  opt_procedural:
  2451    PROCEDURAL {}
  2452  | /* EMPTY */ {}
  2453  
  2454  drop_unsupported:
  2455    DROP AGGREGATE error { return unimplemented(sqllex, "drop aggregate") }
  2456  | DROP CAST error { return unimplemented(sqllex, "drop cast") }
  2457  | DROP COLLATION error { return unimplemented(sqllex, "drop collation") }
  2458  | DROP CONVERSION error { return unimplemented(sqllex, "drop conversion") }
  2459  | DROP DOMAIN error { return unimplementedWithIssueDetail(sqllex, 27796, "drop") }
  2460  | DROP EXTENSION IF EXISTS name error { return unimplemented(sqllex, "drop extension " + $5) }
  2461  | DROP EXTENSION name error { return unimplemented(sqllex, "drop extension " + $3) }
  2462  | DROP FOREIGN TABLE error { return unimplemented(sqllex, "drop foreign table") }
  2463  | DROP FOREIGN DATA error { return unimplemented(sqllex, "drop fdw") }
  2464  | DROP FUNCTION error { return unimplementedWithIssueDetail(sqllex, 17511, "drop function") }
  2465  | DROP opt_procedural LANGUAGE name error { return unimplementedWithIssueDetail(sqllex, 17511, "drop language " + $4) }
  2466  | DROP OPERATOR error { return unimplemented(sqllex, "drop operator") }
  2467  | DROP PUBLICATION error { return unimplemented(sqllex, "drop publication") }
  2468  | DROP RULE error { return unimplemented(sqllex, "drop rule") }
  2469  | DROP SCHEMA error { return unimplementedWithIssueDetail(sqllex, 26443, "drop") }
  2470  | DROP SERVER error { return unimplemented(sqllex, "drop server") }
  2471  | DROP SUBSCRIPTION error { return unimplemented(sqllex, "drop subscription") }
  2472  | DROP TEXT error { return unimplementedWithIssueDetail(sqllex, 7821, "drop text") }
  2473  | DROP TRIGGER error { return unimplementedWithIssueDetail(sqllex, 28296, "drop") }
  2474  
  2475  create_ddl_stmt:
  2476    create_changefeed_stmt
  2477  | create_database_stmt // EXTEND WITH HELP: CREATE DATABASE
  2478  | create_index_stmt    // EXTEND WITH HELP: CREATE INDEX
  2479  | create_schema_stmt   // EXTEND WITH HELP: CREATE SCHEMA
  2480  | create_table_stmt    // EXTEND WITH HELP: CREATE TABLE
  2481  | create_table_as_stmt // EXTEND WITH HELP: CREATE TABLE
  2482  // Error case for both CREATE TABLE and CREATE TABLE ... AS in one
  2483  | CREATE opt_temp_create_table TABLE error   // SHOW HELP: CREATE TABLE
  2484  | create_type_stmt     // EXTEND WITH HELP: CREATE TYPE
  2485  | create_view_stmt     // EXTEND WITH HELP: CREATE VIEW
  2486  | create_sequence_stmt // EXTEND WITH HELP: CREATE SEQUENCE
  2487  
  2488  // %Help: CREATE STATISTICS - create a new table statistic
  2489  // %Category: Misc
  2490  // %Text:
  2491  // CREATE STATISTICS <statisticname>
  2492  //   [ON <colname> [, ...]]
  2493  //   FROM <tablename> [AS OF SYSTEM TIME <expr>]
  2494  create_stats_stmt:
  2495    CREATE STATISTICS statistics_name opt_stats_columns FROM create_stats_target opt_create_stats_options
  2496    {
  2497      $$.val = &tree.CreateStats{
  2498        Name: tree.Name($3),
  2499        ColumnNames: $4.nameList(),
  2500        Table: $6.tblExpr(),
  2501        Options: *$7.createStatsOptions(),
  2502      }
  2503    }
  2504  | CREATE STATISTICS error // SHOW HELP: CREATE STATISTICS
  2505  
  2506  opt_stats_columns:
  2507    ON name_list
  2508    {
  2509      $$.val = $2.nameList()
  2510    }
  2511  | /* EMPTY */
  2512    {
  2513      $$.val = tree.NameList(nil)
  2514    }
  2515  
  2516  create_stats_target:
  2517    table_name
  2518    {
  2519      $$.val = $1.unresolvedObjectName()
  2520    }
  2521  | '[' iconst64 ']'
  2522    {
  2523      /* SKIP DOC */
  2524      $$.val = &tree.TableRef{
  2525        TableID: $2.int64(),
  2526      }
  2527    }
  2528  
  2529  opt_create_stats_options:
  2530    WITH OPTIONS create_stats_option_list
  2531    {
  2532      /* SKIP DOC */
  2533      $$.val = $3.createStatsOptions()
  2534    }
  2535  // Allow AS OF SYSTEM TIME without WITH OPTIONS, for consistency with other
  2536  // statements.
  2537  | as_of_clause
  2538    {
  2539      $$.val = &tree.CreateStatsOptions{
  2540        AsOf: $1.asOfClause(),
  2541      }
  2542    }
  2543  | /* EMPTY */
  2544    {
  2545      $$.val = &tree.CreateStatsOptions{}
  2546    }
  2547  
  2548  create_stats_option_list:
  2549    create_stats_option
  2550    {
  2551      $$.val = $1.createStatsOptions()
  2552    }
  2553  | create_stats_option_list create_stats_option
  2554    {
  2555      a := $1.createStatsOptions()
  2556      b := $2.createStatsOptions()
  2557      if err := a.CombineWith(b); err != nil {
  2558        return setErr(sqllex, err)
  2559      }
  2560      $$.val = a
  2561    }
  2562  
  2563  create_stats_option:
  2564    THROTTLING FCONST
  2565    {
  2566      /* SKIP DOC */
  2567      value, _ := constant.Float64Val($2.numVal().AsConstantValue())
  2568      if value < 0.0 || value >= 1.0 {
  2569        sqllex.Error("THROTTLING fraction must be between 0 and 1")
  2570        return 1
  2571      }
  2572      $$.val = &tree.CreateStatsOptions{
  2573        Throttling: value,
  2574      }
  2575    }
  2576  | as_of_clause
  2577    {
  2578      $$.val = &tree.CreateStatsOptions{
  2579        AsOf: $1.asOfClause(),
  2580      }
  2581    }
  2582  
  2583  create_changefeed_stmt:
  2584    CREATE CHANGEFEED FOR changefeed_targets opt_changefeed_sink opt_with_options
  2585    {
  2586      $$.val = &tree.CreateChangefeed{
  2587        Targets: $4.targetList(),
  2588        SinkURI: $5.expr(),
  2589        Options: $6.kvOptions(),
  2590      }
  2591    }
  2592  | EXPERIMENTAL CHANGEFEED FOR changefeed_targets opt_with_options
  2593    {
  2594      /* SKIP DOC */
  2595      $$.val = &tree.CreateChangefeed{
  2596        Targets: $4.targetList(),
  2597        Options: $5.kvOptions(),
  2598      }
  2599    }
  2600  
  2601  changefeed_targets:
  2602    single_table_pattern_list
  2603    {
  2604      $$.val = tree.TargetList{Tables: $1.tablePatterns()}
  2605    }
  2606  | TABLE single_table_pattern_list
  2607    {
  2608      $$.val = tree.TargetList{Tables: $2.tablePatterns()}
  2609    }
  2610  
  2611  single_table_pattern_list:
  2612    table_name
  2613    {
  2614      $$.val = tree.TablePatterns{$1.unresolvedObjectName().ToUnresolvedName()}
  2615    }
  2616  | single_table_pattern_list ',' table_name
  2617    {
  2618      $$.val = append($1.tablePatterns(), $3.unresolvedObjectName().ToUnresolvedName())
  2619    }
  2620  
  2621  
  2622  opt_changefeed_sink:
  2623    INTO string_or_placeholder
  2624    {
  2625      $$.val = $2.expr()
  2626    }
  2627  | /* EMPTY */
  2628    {
  2629      /* SKIP DOC */
  2630      $$.val = nil
  2631    }
  2632  
  2633  // %Help: DELETE - delete rows from a table
  2634  // %Category: DML
  2635  // %Text: DELETE FROM <tablename> [WHERE <expr>]
  2636  //               [ORDER BY <exprs...>]
  2637  //               [LIMIT <expr>]
  2638  //               [RETURNING <exprs...>]
  2639  // %SeeAlso: WEBDOCS/delete.html
  2640  delete_stmt:
  2641    opt_with_clause DELETE FROM table_expr_opt_alias_idx opt_using_clause opt_where_clause opt_sort_clause opt_limit_clause returning_clause
  2642    {
  2643      $$.val = &tree.Delete{
  2644        With: $1.with(),
  2645        Table: $4.tblExpr(),
  2646        Where: tree.NewWhere(tree.AstWhere, $6.expr()),
  2647        OrderBy: $7.orderBy(),
  2648        Limit: $8.limit(),
  2649        Returning: $9.retClause(),
  2650      }
  2651    }
  2652  | opt_with_clause DELETE error // SHOW HELP: DELETE
  2653  
  2654  opt_using_clause:
  2655    USING from_list { return unimplementedWithIssueDetail(sqllex, 40963, "delete using") }
  2656  | /* EMPTY */ { }
  2657  
  2658  
  2659  // %Help: DISCARD - reset the session to its initial state
  2660  // %Category: Cfg
  2661  // %Text: DISCARD ALL
  2662  discard_stmt:
  2663    DISCARD ALL
  2664    {
  2665      $$.val = &tree.Discard{Mode: tree.DiscardModeAll}
  2666    }
  2667  | DISCARD PLANS { return unimplemented(sqllex, "discard plans") }
  2668  | DISCARD SEQUENCES { return unimplemented(sqllex, "discard sequences") }
  2669  | DISCARD TEMP { return unimplemented(sqllex, "discard temp") }
  2670  | DISCARD TEMPORARY { return unimplemented(sqllex, "discard temp") }
  2671  | DISCARD error // SHOW HELP: DISCARD
  2672  
  2673  // %Help: DROP
  2674  // %Category: Group
  2675  // %Text:
  2676  // DROP DATABASE, DROP INDEX, DROP TABLE, DROP VIEW, DROP SEQUENCE,
  2677  // DROP USER, DROP ROLE, DROP TYPE
  2678  drop_stmt:
  2679    drop_ddl_stmt      // help texts in sub-rule
  2680  | drop_role_stmt     // EXTEND WITH HELP: DROP ROLE
  2681  | drop_unsupported   {}
  2682  | DROP error         // SHOW HELP: DROP
  2683  
  2684  drop_ddl_stmt:
  2685    drop_database_stmt // EXTEND WITH HELP: DROP DATABASE
  2686  | drop_index_stmt    // EXTEND WITH HELP: DROP INDEX
  2687  | drop_table_stmt    // EXTEND WITH HELP: DROP TABLE
  2688  | drop_view_stmt     // EXTEND WITH HELP: DROP VIEW
  2689  | drop_sequence_stmt // EXTEND WITH HELP: DROP SEQUENCE
  2690  | drop_type_stmt     // EXTEND WITH HELP: DROP TYPE
  2691  
  2692  // %Help: DROP VIEW - remove a view
  2693  // %Category: DDL
  2694  // %Text: DROP VIEW [IF EXISTS] <tablename> [, ...] [CASCADE | RESTRICT]
  2695  // %SeeAlso: WEBDOCS/drop-index.html
  2696  drop_view_stmt:
  2697    DROP VIEW table_name_list opt_drop_behavior
  2698    {
  2699      $$.val = &tree.DropView{Names: $3.tableNames(), IfExists: false, DropBehavior: $4.dropBehavior()}
  2700    }
  2701  | DROP VIEW IF EXISTS table_name_list opt_drop_behavior
  2702    {
  2703      $$.val = &tree.DropView{Names: $5.tableNames(), IfExists: true, DropBehavior: $6.dropBehavior()}
  2704    }
  2705  | DROP VIEW error // SHOW HELP: DROP VIEW
  2706  
  2707  // %Help: DROP SEQUENCE - remove a sequence
  2708  // %Category: DDL
  2709  // %Text: DROP SEQUENCE [IF EXISTS] <sequenceName> [, ...] [CASCADE | RESTRICT]
  2710  // %SeeAlso: DROP
  2711  drop_sequence_stmt:
  2712    DROP SEQUENCE table_name_list opt_drop_behavior
  2713    {
  2714      $$.val = &tree.DropSequence{Names: $3.tableNames(), IfExists: false, DropBehavior: $4.dropBehavior()}
  2715    }
  2716  | DROP SEQUENCE IF EXISTS table_name_list opt_drop_behavior
  2717    {
  2718      $$.val = &tree.DropSequence{Names: $5.tableNames(), IfExists: true, DropBehavior: $6.dropBehavior()}
  2719    }
  2720  | DROP SEQUENCE error // SHOW HELP: DROP VIEW
  2721  
  2722  // %Help: DROP TABLE - remove a table
  2723  // %Category: DDL
  2724  // %Text: DROP TABLE [IF EXISTS] <tablename> [, ...] [CASCADE | RESTRICT]
  2725  // %SeeAlso: WEBDOCS/drop-table.html
  2726  drop_table_stmt:
  2727    DROP TABLE table_name_list opt_drop_behavior
  2728    {
  2729      $$.val = &tree.DropTable{Names: $3.tableNames(), IfExists: false, DropBehavior: $4.dropBehavior()}
  2730    }
  2731  | DROP TABLE IF EXISTS table_name_list opt_drop_behavior
  2732    {
  2733      $$.val = &tree.DropTable{Names: $5.tableNames(), IfExists: true, DropBehavior: $6.dropBehavior()}
  2734    }
  2735  | DROP TABLE error // SHOW HELP: DROP TABLE
  2736  
  2737  // %Help: DROP INDEX - remove an index
  2738  // %Category: DDL
  2739  // %Text: DROP INDEX [CONCURRENTLY] [IF EXISTS] <idxname> [, ...] [CASCADE | RESTRICT]
  2740  // %SeeAlso: WEBDOCS/drop-index.html
  2741  drop_index_stmt:
  2742    DROP INDEX opt_concurrently table_index_name_list opt_drop_behavior
  2743    {
  2744      $$.val = &tree.DropIndex{
  2745        IndexList: $4.newTableIndexNames(),
  2746        IfExists: false,
  2747        DropBehavior: $5.dropBehavior(),
  2748        Concurrently: $3.bool(),
  2749      }
  2750    }
  2751  | DROP INDEX opt_concurrently IF EXISTS table_index_name_list opt_drop_behavior
  2752    {
  2753      $$.val = &tree.DropIndex{
  2754        IndexList: $6.newTableIndexNames(),
  2755        IfExists: true,
  2756        DropBehavior: $7.dropBehavior(),
  2757        Concurrently: $3.bool(),
  2758      }
  2759    }
  2760  | DROP INDEX error // SHOW HELP: DROP INDEX
  2761  
  2762  // %Help: DROP DATABASE - remove a database
  2763  // %Category: DDL
  2764  // %Text: DROP DATABASE [IF EXISTS] <databasename> [CASCADE | RESTRICT]
  2765  // %SeeAlso: WEBDOCS/drop-database.html
  2766  drop_database_stmt:
  2767    DROP DATABASE database_name opt_drop_behavior
  2768    {
  2769      $$.val = &tree.DropDatabase{
  2770        Name: tree.Name($3),
  2771        IfExists: false,
  2772        DropBehavior: $4.dropBehavior(),
  2773      }
  2774    }
  2775  | DROP DATABASE IF EXISTS database_name opt_drop_behavior
  2776    {
  2777      $$.val = &tree.DropDatabase{
  2778        Name: tree.Name($5),
  2779        IfExists: true,
  2780        DropBehavior: $6.dropBehavior(),
  2781      }
  2782    }
  2783  | DROP DATABASE error // SHOW HELP: DROP DATABASE
  2784  
  2785  // %Help: DROP TYPE - remove a type
  2786  // %Category: DDL
  2787  // %Text: DROP TYPE [IF EXISTS] <type_name> [, ...] [CASCASE | RESTRICT]
  2788  // %SeeAlso: WEBDOCS/drop-type.html
  2789  drop_type_stmt:
  2790    DROP TYPE type_name_list opt_drop_behavior
  2791    {
  2792      $$.val = &tree.DropType{
  2793        Names: $3.unresolvedObjectNames(),
  2794        IfExists: false,
  2795        DropBehavior: $4.dropBehavior(),
  2796      }
  2797    }
  2798  | DROP TYPE IF EXISTS type_name_list opt_drop_behavior
  2799    {
  2800      $$.val = &tree.DropType{
  2801        Names: $5.unresolvedObjectNames(),
  2802        IfExists: true,
  2803        DropBehavior: $6.dropBehavior(),
  2804      }
  2805    }
  2806  | DROP TYPE error // SHOW HELP: DROP TYPE
  2807  
  2808  
  2809  type_name_list:
  2810    type_name
  2811    {
  2812      $$.val = []*tree.UnresolvedObjectName{$1.unresolvedObjectName()}
  2813    }
  2814  | type_name_list ',' type_name
  2815    {
  2816      $$.val = append($1.unresolvedObjectNames(), $3.unresolvedObjectName())
  2817    }
  2818  
  2819  
  2820  // %Help: DROP ROLE - remove a user
  2821  // %Category: Priv
  2822  // %Text: DROP ROLE [IF EXISTS] <user> [, ...]
  2823  // %SeeAlso: CREATE ROLE, SHOW ROLE
  2824  drop_role_stmt:
  2825    DROP role_or_group_or_user string_or_placeholder_list
  2826    {
  2827      $$.val = &tree.DropRole{Names: $3.exprs(), IfExists: false, IsRole: $2.bool()}
  2828    }
  2829  | DROP role_or_group_or_user IF EXISTS string_or_placeholder_list
  2830    {
  2831      $$.val = &tree.DropRole{Names: $5.exprs(), IfExists: true, IsRole: $2.bool()}
  2832    }
  2833  | DROP role_or_group_or_user error // SHOW HELP: DROP ROLE
  2834  
  2835  table_name_list:
  2836    table_name
  2837    {
  2838      name := $1.unresolvedObjectName().ToTableName()
  2839      $$.val = tree.TableNames{name}
  2840    }
  2841  | table_name_list ',' table_name
  2842    {
  2843      name := $3.unresolvedObjectName().ToTableName()
  2844      $$.val = append($1.tableNames(), name)
  2845    }
  2846  
  2847  // %Help: EXPLAIN - show the logical plan of a query
  2848  // %Category: Misc
  2849  // %Text:
  2850  // EXPLAIN <statement>
  2851  // EXPLAIN ([PLAN ,] <planoptions...> ) <statement>
  2852  // EXPLAIN [ANALYZE] (DISTSQL) <statement>
  2853  // EXPLAIN ANALYZE [(DISTSQL)] <statement>
  2854  //
  2855  // Explainable statements:
  2856  //     SELECT, CREATE, DROP, ALTER, INSERT, UPSERT, UPDATE, DELETE,
  2857  //     SHOW, EXPLAIN
  2858  //
  2859  // Plan options:
  2860  //     TYPES, VERBOSE, OPT
  2861  //
  2862  // %SeeAlso: WEBDOCS/explain.html
  2863  explain_stmt:
  2864    EXPLAIN preparable_stmt
  2865    {
  2866      var err error
  2867      $$.val, err = tree.MakeExplain(nil /* options */, $2.stmt())
  2868      if err != nil {
  2869        return setErr(sqllex, err)
  2870      }
  2871    }
  2872  | EXPLAIN error // SHOW HELP: EXPLAIN
  2873  | EXPLAIN '(' explain_option_list ')' preparable_stmt
  2874    {
  2875      var err error
  2876      $$.val, err = tree.MakeExplain($3.strs(), $5.stmt())
  2877      if err != nil {
  2878        return setErr(sqllex, err)
  2879      }
  2880    }
  2881  | EXPLAIN ANALYZE preparable_stmt
  2882    {
  2883      var err error
  2884      $$.val, err = tree.MakeExplain([]string{"DISTSQL", "ANALYZE"}, $3.stmt())
  2885      if err != nil {
  2886        return setErr(sqllex, err)
  2887      }
  2888    }
  2889  | EXPLAIN ANALYSE preparable_stmt
  2890    {
  2891      var err error
  2892      $$.val, err = tree.MakeExplain([]string{"DISTSQL", "ANALYZE"}, $3.stmt())
  2893      if err != nil {
  2894        return setErr(sqllex, err)
  2895      }
  2896    }
  2897  | EXPLAIN ANALYZE '(' explain_option_list ')' preparable_stmt
  2898    {
  2899      var err error
  2900      $$.val, err = tree.MakeExplain(append($4.strs(), "ANALYZE"), $6.stmt())
  2901      if err != nil {
  2902        return setErr(sqllex, err)
  2903      }
  2904    }
  2905  | EXPLAIN ANALYSE '(' explain_option_list ')' preparable_stmt
  2906    {
  2907      var err error
  2908      $$.val, err = tree.MakeExplain(append($4.strs(), "ANALYZE"), $6.stmt())
  2909      if err != nil {
  2910        return setErr(sqllex, err)
  2911      }
  2912    }
  2913  // This second error rule is necessary, because otherwise
  2914  // preparable_stmt also provides "selectclause := '(' error ..." and
  2915  // cause a help text for the select clause, which will be confusing in
  2916  // the context of EXPLAIN.
  2917  | EXPLAIN '(' error // SHOW HELP: EXPLAIN
  2918  
  2919  preparable_stmt:
  2920    alter_stmt        // help texts in sub-rule
  2921  | backup_stmt       // EXTEND WITH HELP: BACKUP
  2922  | cancel_stmt       // help texts in sub-rule
  2923  | create_stmt       // help texts in sub-rule
  2924  | delete_stmt       // EXTEND WITH HELP: DELETE
  2925  | drop_stmt         // help texts in sub-rule
  2926  | explain_stmt      // EXTEND WITH HELP: EXPLAIN
  2927  | import_stmt       // EXTEND WITH HELP: IMPORT
  2928  | insert_stmt       // EXTEND WITH HELP: INSERT
  2929  | pause_stmt        // EXTEND WITH HELP: PAUSE JOBS
  2930  | reset_stmt        // help texts in sub-rule
  2931  | restore_stmt      // EXTEND WITH HELP: RESTORE
  2932  | resume_stmt       // EXTEND WITH HELP: RESUME JOBS
  2933  | export_stmt       // EXTEND WITH HELP: EXPORT
  2934  | scrub_stmt        // help texts in sub-rule
  2935  | select_stmt       // help texts in sub-rule
  2936    {
  2937      $$.val = $1.slct()
  2938    }
  2939  | preparable_set_stmt // help texts in sub-rule
  2940  | show_stmt         // help texts in sub-rule
  2941  | truncate_stmt     // EXTEND WITH HELP: TRUNCATE
  2942  | update_stmt       // EXTEND WITH HELP: UPDATE
  2943  | upsert_stmt       // EXTEND WITH HELP: UPSERT
  2944  
  2945  // These are statements that can be used as a data source using the special
  2946  // syntax with brackets. These are a subset of preparable_stmt.
  2947  row_source_extension_stmt:
  2948    delete_stmt       // EXTEND WITH HELP: DELETE
  2949  | explain_stmt      // EXTEND WITH HELP: EXPLAIN
  2950  | insert_stmt       // EXTEND WITH HELP: INSERT
  2951  | select_stmt       // help texts in sub-rule
  2952    {
  2953      $$.val = $1.slct()
  2954    }
  2955  | show_stmt         // help texts in sub-rule
  2956  | update_stmt       // EXTEND WITH HELP: UPDATE
  2957  | upsert_stmt       // EXTEND WITH HELP: UPSERT
  2958  
  2959  explain_option_list:
  2960    explain_option_name
  2961    {
  2962      $$.val = []string{$1}
  2963    }
  2964  | explain_option_list ',' explain_option_name
  2965    {
  2966      $$.val = append($1.strs(), $3)
  2967    }
  2968  
  2969  // %Help: PREPARE - prepare a statement for later execution
  2970  // %Category: Misc
  2971  // %Text: PREPARE <name> [ ( <types...> ) ] AS <query>
  2972  // %SeeAlso: EXECUTE, DEALLOCATE, DISCARD
  2973  prepare_stmt:
  2974    PREPARE table_alias_name prep_type_clause AS preparable_stmt
  2975    {
  2976      $$.val = &tree.Prepare{
  2977        Name: tree.Name($2),
  2978        Types: $3.typeReferences(),
  2979        Statement: $5.stmt(),
  2980      }
  2981    }
  2982  | PREPARE table_alias_name prep_type_clause AS OPT PLAN SCONST
  2983    {
  2984      /* SKIP DOC */
  2985      $$.val = &tree.Prepare{
  2986        Name: tree.Name($2),
  2987        Types: $3.typeReferences(),
  2988        Statement: &tree.CannedOptPlan{Plan: $7},
  2989      }
  2990    }
  2991  | PREPARE error // SHOW HELP: PREPARE
  2992  
  2993  prep_type_clause:
  2994    '(' type_list ')'
  2995    {
  2996      $$.val = $2.typeReferences();
  2997    }
  2998  | /* EMPTY */
  2999    {
  3000      $$.val = []tree.ResolvableTypeReference(nil)
  3001    }
  3002  
  3003  // %Help: EXECUTE - execute a statement prepared previously
  3004  // %Category: Misc
  3005  // %Text: EXECUTE <name> [ ( <exprs...> ) ]
  3006  // %SeeAlso: PREPARE, DEALLOCATE, DISCARD
  3007  execute_stmt:
  3008    EXECUTE table_alias_name execute_param_clause
  3009    {
  3010      $$.val = &tree.Execute{
  3011        Name: tree.Name($2),
  3012        Params: $3.exprs(),
  3013      }
  3014    }
  3015  | EXECUTE table_alias_name execute_param_clause DISCARD ROWS
  3016    {
  3017      /* SKIP DOC */
  3018      $$.val = &tree.Execute{
  3019        Name: tree.Name($2),
  3020        Params: $3.exprs(),
  3021        DiscardRows: true,
  3022      }
  3023    }
  3024  | EXECUTE error // SHOW HELP: EXECUTE
  3025  
  3026  execute_param_clause:
  3027    '(' expr_list ')'
  3028    {
  3029      $$.val = $2.exprs()
  3030    }
  3031  | /* EMPTY */
  3032    {
  3033      $$.val = tree.Exprs(nil)
  3034    }
  3035  
  3036  // %Help: DEALLOCATE - remove a prepared statement
  3037  // %Category: Misc
  3038  // %Text: DEALLOCATE [PREPARE] { <name> | ALL }
  3039  // %SeeAlso: PREPARE, EXECUTE, DISCARD
  3040  deallocate_stmt:
  3041    DEALLOCATE name
  3042    {
  3043      $$.val = &tree.Deallocate{Name: tree.Name($2)}
  3044    }
  3045  | DEALLOCATE PREPARE name
  3046    {
  3047      $$.val = &tree.Deallocate{Name: tree.Name($3)}
  3048    }
  3049  | DEALLOCATE ALL
  3050    {
  3051      $$.val = &tree.Deallocate{}
  3052    }
  3053  | DEALLOCATE PREPARE ALL
  3054    {
  3055      $$.val = &tree.Deallocate{}
  3056    }
  3057  | DEALLOCATE error // SHOW HELP: DEALLOCATE
  3058  
  3059  // %Help: GRANT - define access privileges and role memberships
  3060  // %Category: Priv
  3061  // %Text:
  3062  // Grant privileges:
  3063  //   GRANT {ALL | <privileges...> } ON <targets...> TO <grantees...>
  3064  // Grant role membership (CCL only):
  3065  //   GRANT <roles...> TO <grantees...> [WITH ADMIN OPTION]
  3066  //
  3067  // Privileges:
  3068  //   CREATE, DROP, GRANT, SELECT, INSERT, DELETE, UPDATE
  3069  //
  3070  // Targets:
  3071  //   DATABASE <databasename> [, ...]
  3072  //   [TABLE] [<databasename> .] { <tablename> | * } [, ...]
  3073  //
  3074  // %SeeAlso: REVOKE, WEBDOCS/grant.html
  3075  grant_stmt:
  3076    GRANT privileges ON targets TO name_list
  3077    {
  3078      $$.val = &tree.Grant{Privileges: $2.privilegeList(), Grantees: $6.nameList(), Targets: $4.targetList()}
  3079    }
  3080  | GRANT privilege_list TO name_list
  3081    {
  3082      $$.val = &tree.GrantRole{Roles: $2.nameList(), Members: $4.nameList(), AdminOption: false}
  3083    }
  3084  | GRANT privilege_list TO name_list WITH ADMIN OPTION
  3085    {
  3086      $$.val = &tree.GrantRole{Roles: $2.nameList(), Members: $4.nameList(), AdminOption: true}
  3087    }
  3088  | GRANT error // SHOW HELP: GRANT
  3089  
  3090  // %Help: REVOKE - remove access privileges and role memberships
  3091  // %Category: Priv
  3092  // %Text:
  3093  // Revoke privileges:
  3094  //   REVOKE {ALL | <privileges...> } ON <targets...> FROM <grantees...>
  3095  // Revoke role membership (CCL only):
  3096  //   REVOKE [ADMIN OPTION FOR] <roles...> FROM <grantees...>
  3097  //
  3098  // Privileges:
  3099  //   CREATE, DROP, GRANT, SELECT, INSERT, DELETE, UPDATE
  3100  //
  3101  // Targets:
  3102  //   DATABASE <databasename> [, <databasename>]...
  3103  //   [TABLE] [<databasename> .] { <tablename> | * } [, ...]
  3104  //
  3105  // %SeeAlso: GRANT, WEBDOCS/revoke.html
  3106  revoke_stmt:
  3107    REVOKE privileges ON targets FROM name_list
  3108    {
  3109      $$.val = &tree.Revoke{Privileges: $2.privilegeList(), Grantees: $6.nameList(), Targets: $4.targetList()}
  3110    }
  3111  | REVOKE privilege_list FROM name_list
  3112    {
  3113      $$.val = &tree.RevokeRole{Roles: $2.nameList(), Members: $4.nameList(), AdminOption: false }
  3114    }
  3115  | REVOKE ADMIN OPTION FOR privilege_list FROM name_list
  3116    {
  3117      $$.val = &tree.RevokeRole{Roles: $5.nameList(), Members: $7.nameList(), AdminOption: true }
  3118    }
  3119  | REVOKE error // SHOW HELP: REVOKE
  3120  
  3121  // ALL is always by itself.
  3122  privileges:
  3123    ALL
  3124    {
  3125      $$.val = privilege.List{privilege.ALL}
  3126    }
  3127    | privilege_list
  3128    {
  3129       privList, err := privilege.ListFromStrings($1.nameList().ToStrings())
  3130       if err != nil {
  3131         return setErr(sqllex, err)
  3132       }
  3133       $$.val = privList
  3134    }
  3135  
  3136  privilege_list:
  3137    privilege
  3138    {
  3139      $$.val = tree.NameList{tree.Name($1)}
  3140    }
  3141  | privilege_list ',' privilege
  3142    {
  3143      $$.val = append($1.nameList(), tree.Name($3))
  3144    }
  3145  
  3146  // Privileges are parsed at execution time to avoid having to make them reserved.
  3147  // Any privileges above `col_name_keyword` should be listed here.
  3148  // The full list is in sql/privilege/privilege.go.
  3149  privilege:
  3150    name
  3151  | CREATE
  3152  | GRANT
  3153  | SELECT
  3154  
  3155  reset_stmt:
  3156    reset_session_stmt  // EXTEND WITH HELP: RESET
  3157  | reset_csetting_stmt // EXTEND WITH HELP: RESET CLUSTER SETTING
  3158  
  3159  // %Help: RESET - reset a session variable to its default value
  3160  // %Category: Cfg
  3161  // %Text: RESET [SESSION] <var>
  3162  // %SeeAlso: RESET CLUSTER SETTING, WEBDOCS/set-vars.html
  3163  reset_session_stmt:
  3164    RESET session_var
  3165    {
  3166      $$.val = &tree.SetVar{Name: $2, Values:tree.Exprs{tree.DefaultVal{}}}
  3167    }
  3168  | RESET SESSION session_var
  3169    {
  3170      $$.val = &tree.SetVar{Name: $3, Values:tree.Exprs{tree.DefaultVal{}}}
  3171    }
  3172  | RESET error // SHOW HELP: RESET
  3173  
  3174  // %Help: RESET CLUSTER SETTING - reset a cluster setting to its default value
  3175  // %Category: Cfg
  3176  // %Text: RESET CLUSTER SETTING <var>
  3177  // %SeeAlso: SET CLUSTER SETTING, RESET
  3178  reset_csetting_stmt:
  3179    RESET CLUSTER SETTING var_name
  3180    {
  3181      $$.val = &tree.SetClusterSetting{Name: strings.Join($4.strs(), "."), Value:tree.DefaultVal{}}
  3182    }
  3183  | RESET CLUSTER error // SHOW HELP: RESET CLUSTER SETTING
  3184  
  3185  // USE is the MSSQL/MySQL equivalent of SET DATABASE. Alias it for convenience.
  3186  // %Help: USE - set the current database
  3187  // %Category: Cfg
  3188  // %Text: USE <dbname>
  3189  //
  3190  // "USE <dbname>" is an alias for "SET [SESSION] database = <dbname>".
  3191  // %SeeAlso: SET SESSION, WEBDOCS/set-vars.html
  3192  use_stmt:
  3193    USE var_value
  3194    {
  3195      $$.val = &tree.SetVar{Name: "database", Values: tree.Exprs{$2.expr()}}
  3196    }
  3197  | USE error // SHOW HELP: USE
  3198  
  3199  // SET remainder, e.g. SET TRANSACTION
  3200  nonpreparable_set_stmt:
  3201    set_transaction_stmt // EXTEND WITH HELP: SET TRANSACTION
  3202  | set_exprs_internal   { /* SKIP DOC */ }
  3203  | SET CONSTRAINTS error { return unimplemented(sqllex, "set constraints") }
  3204  | SET LOCAL error { return unimplementedWithIssue(sqllex, 32562) }
  3205  
  3206  // SET SESSION / SET CLUSTER SETTING
  3207  preparable_set_stmt:
  3208    set_session_stmt     // EXTEND WITH HELP: SET SESSION
  3209  | set_csetting_stmt    // EXTEND WITH HELP: SET CLUSTER SETTING
  3210  | use_stmt             // EXTEND WITH HELP: USE
  3211  
  3212  // %Help: SCRUB - run checks against databases or tables
  3213  // %Category: Experimental
  3214  // %Text:
  3215  // EXPERIMENTAL SCRUB TABLE <table> ...
  3216  // EXPERIMENTAL SCRUB DATABASE <database>
  3217  //
  3218  // The various checks that ca be run with SCRUB includes:
  3219  //   - Physical table data (encoding)
  3220  //   - Secondary index integrity
  3221  //   - Constraint integrity (NOT NULL, CHECK, FOREIGN KEY, UNIQUE)
  3222  // %SeeAlso: SCRUB TABLE, SCRUB DATABASE
  3223  scrub_stmt:
  3224    scrub_table_stmt
  3225  | scrub_database_stmt
  3226  | EXPERIMENTAL SCRUB error // SHOW HELP: SCRUB
  3227  
  3228  // %Help: SCRUB DATABASE - run scrub checks on a database
  3229  // %Category: Experimental
  3230  // %Text:
  3231  // EXPERIMENTAL SCRUB DATABASE <database>
  3232  //                             [AS OF SYSTEM TIME <expr>]
  3233  //
  3234  // All scrub checks will be run on the database. This includes:
  3235  //   - Physical table data (encoding)
  3236  //   - Secondary index integrity
  3237  //   - Constraint integrity (NOT NULL, CHECK, FOREIGN KEY, UNIQUE)
  3238  // %SeeAlso: SCRUB TABLE, SCRUB
  3239  scrub_database_stmt:
  3240    EXPERIMENTAL SCRUB DATABASE database_name opt_as_of_clause
  3241    {
  3242      $$.val = &tree.Scrub{Typ: tree.ScrubDatabase, Database: tree.Name($4), AsOf: $5.asOfClause()}
  3243    }
  3244  | EXPERIMENTAL SCRUB DATABASE error // SHOW HELP: SCRUB DATABASE
  3245  
  3246  // %Help: SCRUB TABLE - run scrub checks on a table
  3247  // %Category: Experimental
  3248  // %Text:
  3249  // SCRUB TABLE <tablename>
  3250  //             [AS OF SYSTEM TIME <expr>]
  3251  //             [WITH OPTIONS <option> [, ...]]
  3252  //
  3253  // Options:
  3254  //   EXPERIMENTAL SCRUB TABLE ... WITH OPTIONS INDEX ALL
  3255  //   EXPERIMENTAL SCRUB TABLE ... WITH OPTIONS INDEX (<index>...)
  3256  //   EXPERIMENTAL SCRUB TABLE ... WITH OPTIONS CONSTRAINT ALL
  3257  //   EXPERIMENTAL SCRUB TABLE ... WITH OPTIONS CONSTRAINT (<constraint>...)
  3258  //   EXPERIMENTAL SCRUB TABLE ... WITH OPTIONS PHYSICAL
  3259  // %SeeAlso: SCRUB DATABASE, SRUB
  3260  scrub_table_stmt:
  3261    EXPERIMENTAL SCRUB TABLE table_name opt_as_of_clause opt_scrub_options_clause
  3262    {
  3263      $$.val = &tree.Scrub{
  3264        Typ: tree.ScrubTable,
  3265        Table: $4.unresolvedObjectName(),
  3266        AsOf: $5.asOfClause(),
  3267        Options: $6.scrubOptions(),
  3268      }
  3269    }
  3270  | EXPERIMENTAL SCRUB TABLE error // SHOW HELP: SCRUB TABLE
  3271  
  3272  opt_scrub_options_clause:
  3273    WITH OPTIONS scrub_option_list
  3274    {
  3275      $$.val = $3.scrubOptions()
  3276    }
  3277  | /* EMPTY */
  3278    {
  3279      $$.val = tree.ScrubOptions{}
  3280    }
  3281  
  3282  scrub_option_list:
  3283    scrub_option
  3284    {
  3285      $$.val = tree.ScrubOptions{$1.scrubOption()}
  3286    }
  3287  | scrub_option_list ',' scrub_option
  3288    {
  3289      $$.val = append($1.scrubOptions(), $3.scrubOption())
  3290    }
  3291  
  3292  scrub_option:
  3293    INDEX ALL
  3294    {
  3295      $$.val = &tree.ScrubOptionIndex{}
  3296    }
  3297  | INDEX '(' name_list ')'
  3298    {
  3299      $$.val = &tree.ScrubOptionIndex{IndexNames: $3.nameList()}
  3300    }
  3301  | CONSTRAINT ALL
  3302    {
  3303      $$.val = &tree.ScrubOptionConstraint{}
  3304    }
  3305  | CONSTRAINT '(' name_list ')'
  3306    {
  3307      $$.val = &tree.ScrubOptionConstraint{ConstraintNames: $3.nameList()}
  3308    }
  3309  | PHYSICAL
  3310    {
  3311      $$.val = &tree.ScrubOptionPhysical{}
  3312    }
  3313  
  3314  // %Help: SET CLUSTER SETTING - change a cluster setting
  3315  // %Category: Cfg
  3316  // %Text: SET CLUSTER SETTING <var> { TO | = } <value>
  3317  // %SeeAlso: SHOW CLUSTER SETTING, RESET CLUSTER SETTING, SET SESSION,
  3318  // WEBDOCS/cluster-settings.html
  3319  set_csetting_stmt:
  3320    SET CLUSTER SETTING var_name to_or_eq var_value
  3321    {
  3322      $$.val = &tree.SetClusterSetting{Name: strings.Join($4.strs(), "."), Value: $6.expr()}
  3323    }
  3324  | SET CLUSTER error // SHOW HELP: SET CLUSTER SETTING
  3325  
  3326  to_or_eq:
  3327    '='
  3328  | TO
  3329  
  3330  set_exprs_internal:
  3331    /* SET ROW serves to accelerate parser.parseExprs().
  3332       It cannot be used by clients. */
  3333    SET ROW '(' expr_list ')'
  3334    {
  3335      $$.val = &tree.SetVar{Values: $4.exprs()}
  3336    }
  3337  
  3338  // %Help: SET SESSION - change a session variable
  3339  // %Category: Cfg
  3340  // %Text:
  3341  // SET [SESSION] <var> { TO | = } <values...>
  3342  // SET [SESSION] TIME ZONE <tz>
  3343  // SET [SESSION] CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL { SNAPSHOT | SERIALIZABLE }
  3344  // SET [SESSION] TRACING { TO | = } { on | off | cluster | local | kv | results } [,...]
  3345  //
  3346  // %SeeAlso: SHOW SESSION, RESET, DISCARD, SHOW, SET CLUSTER SETTING, SET TRANSACTION,
  3347  // WEBDOCS/set-vars.html
  3348  set_session_stmt:
  3349    SET SESSION set_rest_more
  3350    {
  3351      $$.val = $3.stmt()
  3352    }
  3353  | SET set_rest_more
  3354    {
  3355      $$.val = $2.stmt()
  3356    }
  3357  // Special form for pg compatibility:
  3358  | SET SESSION CHARACTERISTICS AS TRANSACTION transaction_mode_list
  3359    {
  3360      $$.val = &tree.SetSessionCharacteristics{Modes: $6.transactionModes()}
  3361    }
  3362  
  3363  // %Help: SET TRANSACTION - configure the transaction settings
  3364  // %Category: Txn
  3365  // %Text:
  3366  // SET [SESSION] TRANSACTION <txnparameters...>
  3367  //
  3368  // Transaction parameters:
  3369  //    ISOLATION LEVEL { SNAPSHOT | SERIALIZABLE }
  3370  //    PRIORITY { LOW | NORMAL | HIGH }
  3371  //
  3372  // %SeeAlso: SHOW TRANSACTION, SET SESSION,
  3373  // WEBDOCS/set-transaction.html
  3374  set_transaction_stmt:
  3375    SET TRANSACTION transaction_mode_list
  3376    {
  3377      $$.val = &tree.SetTransaction{Modes: $3.transactionModes()}
  3378    }
  3379  | SET TRANSACTION error // SHOW HELP: SET TRANSACTION
  3380  | SET SESSION TRANSACTION transaction_mode_list
  3381    {
  3382      $$.val = &tree.SetTransaction{Modes: $4.transactionModes()}
  3383    }
  3384  | SET SESSION TRANSACTION error // SHOW HELP: SET TRANSACTION
  3385  
  3386  generic_set:
  3387    var_name to_or_eq var_list
  3388    {
  3389      // We need to recognize the "set tracing" specially here; couldn't make "set
  3390      // tracing" a different grammar rule because of ambiguity.
  3391      varName := $1.strs()
  3392      if len(varName) == 1 && varName[0] == "tracing" {
  3393        $$.val = &tree.SetTracing{Values: $3.exprs()}
  3394      } else {
  3395        $$.val = &tree.SetVar{Name: strings.Join($1.strs(), "."), Values: $3.exprs()}
  3396      }
  3397    }
  3398  
  3399  set_rest_more:
  3400  // Generic SET syntaxes:
  3401     generic_set
  3402  // Special SET syntax forms in addition to the generic form.
  3403  // See: https://www.postgresql.org/docs/10/static/sql-set.html
  3404  //
  3405  // "SET TIME ZONE value is an alias for SET timezone TO value."
  3406  | TIME ZONE zone_value
  3407    {
  3408      /* SKIP DOC */
  3409      $$.val = &tree.SetVar{Name: "timezone", Values: tree.Exprs{$3.expr()}}
  3410    }
  3411  // "SET SCHEMA 'value' is an alias for SET search_path TO value. Only
  3412  // one schema can be specified using this syntax."
  3413  | SCHEMA var_value
  3414    {
  3415      /* SKIP DOC */
  3416      $$.val = &tree.SetVar{Name: "search_path", Values: tree.Exprs{$2.expr()}}
  3417    }
  3418  | SESSION AUTHORIZATION DEFAULT
  3419    {
  3420      /* SKIP DOC */
  3421      $$.val = &tree.SetSessionAuthorizationDefault{}
  3422    }
  3423  | SESSION AUTHORIZATION non_reserved_word_or_sconst
  3424    {
  3425      return unimplementedWithIssue(sqllex, 40283)
  3426    }
  3427  // See comment for the non-terminal for SET NAMES below.
  3428  | set_names
  3429  | var_name FROM CURRENT { return unimplemented(sqllex, "set from current") }
  3430  | error // SHOW HELP: SET SESSION
  3431  
  3432  // SET NAMES is the SQL standard syntax for SET client_encoding.
  3433  // "SET NAMES value is an alias for SET client_encoding TO value."
  3434  // See https://www.postgresql.org/docs/10/static/sql-set.html
  3435  // Also see https://www.postgresql.org/docs/9.6/static/multibyte.html#AEN39236
  3436  set_names:
  3437    NAMES var_value
  3438    {
  3439      /* SKIP DOC */
  3440      $$.val = &tree.SetVar{Name: "client_encoding", Values: tree.Exprs{$2.expr()}}
  3441    }
  3442  | NAMES
  3443    {
  3444      /* SKIP DOC */
  3445      $$.val = &tree.SetVar{Name: "client_encoding", Values: tree.Exprs{tree.DefaultVal{}}}
  3446    }
  3447  
  3448  var_name:
  3449    name
  3450    {
  3451      $$.val = []string{$1}
  3452    }
  3453  | name attrs
  3454    {
  3455      $$.val = append([]string{$1}, $2.strs()...)
  3456    }
  3457  
  3458  attrs:
  3459    '.' unrestricted_name
  3460    {
  3461      $$.val = []string{$2}
  3462    }
  3463  | attrs '.' unrestricted_name
  3464    {
  3465      $$.val = append($1.strs(), $3)
  3466    }
  3467  
  3468  var_value:
  3469    a_expr
  3470  | extra_var_value
  3471    {
  3472      $$.val = tree.Expr(&tree.UnresolvedName{NumParts: 1, Parts: tree.NameParts{$1}})
  3473    }
  3474  
  3475  // The RHS of a SET statement can contain any valid expression, which
  3476  // themselves can contain identifiers like TRUE, FALSE. These are parsed
  3477  // as column names (via a_expr) and later during semantic analysis
  3478  // assigned their special value.
  3479  //
  3480  // In addition, for compatibility with CockroachDB we need to support
  3481  // the reserved keyword ON (to go along OFF, which is a valid column name).
  3482  //
  3483  // Finally, in PostgreSQL the CockroachDB-reserved words "index",
  3484  // "nothing", etc. are not special and are valid in SET. These need to
  3485  // be allowed here too.
  3486  extra_var_value:
  3487    ON
  3488  | cockroachdb_extra_reserved_keyword
  3489  
  3490  var_list:
  3491    var_value
  3492    {
  3493      $$.val = tree.Exprs{$1.expr()}
  3494    }
  3495  | var_list ',' var_value
  3496    {
  3497      $$.val = append($1.exprs(), $3.expr())
  3498    }
  3499  
  3500  iso_level:
  3501    READ UNCOMMITTED
  3502    {
  3503      $$.val = tree.SerializableIsolation
  3504    }
  3505  | READ COMMITTED
  3506    {
  3507      $$.val = tree.SerializableIsolation
  3508    }
  3509  | SNAPSHOT
  3510    {
  3511      $$.val = tree.SerializableIsolation
  3512    }
  3513  | REPEATABLE READ
  3514    {
  3515      $$.val = tree.SerializableIsolation
  3516    }
  3517  | SERIALIZABLE
  3518    {
  3519      $$.val = tree.SerializableIsolation
  3520    }
  3521  
  3522  user_priority:
  3523    LOW
  3524    {
  3525      $$.val = tree.Low
  3526    }
  3527  | NORMAL
  3528    {
  3529      $$.val = tree.Normal
  3530    }
  3531  | HIGH
  3532    {
  3533      $$.val = tree.High
  3534    }
  3535  
  3536  // Timezone values can be:
  3537  // - a string such as 'pst8pdt'
  3538  // - an identifier such as "pst8pdt"
  3539  // - an integer or floating point number
  3540  // - a time interval per SQL99
  3541  zone_value:
  3542    SCONST
  3543    {
  3544      $$.val = tree.NewStrVal($1)
  3545    }
  3546  | IDENT
  3547    {
  3548      $$.val = tree.NewStrVal($1)
  3549    }
  3550  | interval_value
  3551    {
  3552      $$.val = $1.expr()
  3553    }
  3554  | numeric_only
  3555  | DEFAULT
  3556    {
  3557      $$.val = tree.DefaultVal{}
  3558    }
  3559  | LOCAL
  3560    {
  3561      $$.val = tree.NewStrVal($1)
  3562    }
  3563  
  3564  // %Help: SHOW
  3565  // %Category: Group
  3566  // %Text:
  3567  // SHOW BACKUP, SHOW CLUSTER SETTING, SHOW COLUMNS, SHOW CONSTRAINTS,
  3568  // SHOW CREATE, SHOW DATABASES, SHOW HISTOGRAM, SHOW INDEXES, SHOW
  3569  // PARTITIONS, SHOW JOBS, SHOW QUERIES, SHOW RANGE, SHOW RANGES,
  3570  // SHOW ROLES, SHOW SCHEMAS, SHOW SEQUENCES, SHOW SESSION, SHOW SESSIONS,
  3571  // SHOW STATISTICS, SHOW SYNTAX, SHOW TABLES, SHOW TRACE SHOW TRANSACTION, SHOW USERS
  3572  show_stmt:
  3573    show_backup_stmt          // EXTEND WITH HELP: SHOW BACKUP
  3574  | show_columns_stmt         // EXTEND WITH HELP: SHOW COLUMNS
  3575  | show_constraints_stmt     // EXTEND WITH HELP: SHOW CONSTRAINTS
  3576  | show_create_stmt          // EXTEND WITH HELP: SHOW CREATE
  3577  | show_csettings_stmt       // EXTEND WITH HELP: SHOW CLUSTER SETTING
  3578  | show_databases_stmt       // EXTEND WITH HELP: SHOW DATABASES
  3579  | show_fingerprints_stmt
  3580  | show_grants_stmt          // EXTEND WITH HELP: SHOW GRANTS
  3581  | show_histogram_stmt       // EXTEND WITH HELP: SHOW HISTOGRAM
  3582  | show_indexes_stmt         // EXTEND WITH HELP: SHOW INDEXES
  3583  | show_partitions_stmt      // EXTEND WITH HELP: SHOW PARTITIONS
  3584  | show_jobs_stmt            // EXTEND WITH HELP: SHOW JOBS
  3585  | show_queries_stmt         // EXTEND WITH HELP: SHOW QUERIES
  3586  | show_ranges_stmt          // EXTEND WITH HELP: SHOW RANGES
  3587  | show_range_for_row_stmt
  3588  | show_roles_stmt           // EXTEND WITH HELP: SHOW ROLES
  3589  | show_savepoint_stmt       // EXTEND WITH HELP: SHOW SAVEPOINT
  3590  | show_schemas_stmt         // EXTEND WITH HELP: SHOW SCHEMAS
  3591  | show_sequences_stmt       // EXTEND WITH HELP: SHOW SEQUENCES
  3592  | show_session_stmt         // EXTEND WITH HELP: SHOW SESSION
  3593  | show_sessions_stmt        // EXTEND WITH HELP: SHOW SESSIONS
  3594  | show_stats_stmt           // EXTEND WITH HELP: SHOW STATISTICS
  3595  | show_syntax_stmt          // EXTEND WITH HELP: SHOW SYNTAX
  3596  | show_tables_stmt          // EXTEND WITH HELP: SHOW TABLES
  3597  | show_trace_stmt           // EXTEND WITH HELP: SHOW TRACE
  3598  | show_transaction_stmt     // EXTEND WITH HELP: SHOW TRANSACTION
  3599  | show_users_stmt           // EXTEND WITH HELP: SHOW USERS
  3600  | show_zone_stmt
  3601  | SHOW error                // SHOW HELP: SHOW
  3602  
  3603  // Cursors are not yet supported by CockroachDB. CLOSE ALL is safe to no-op
  3604  // since there will be no open cursors.
  3605  close_cursor_stmt:
  3606  	CLOSE ALL { }
  3607  | CLOSE cursor_name { return unimplementedWithIssue(sqllex, 41412) }
  3608  
  3609  declare_cursor_stmt:
  3610  	DECLARE { return unimplementedWithIssue(sqllex, 41412) }
  3611  
  3612  reindex_stmt:
  3613    REINDEX TABLE error
  3614    {
  3615      /* SKIP DOC */
  3616      return purposelyUnimplemented(sqllex, "reindex table", "CockroachDB does not require reindexing.")
  3617    }
  3618  | REINDEX INDEX error
  3619    {
  3620      /* SKIP DOC */
  3621      return purposelyUnimplemented(sqllex, "reindex index", "CockroachDB does not require reindexing.")
  3622    }
  3623  | REINDEX DATABASE error
  3624    {
  3625      /* SKIP DOC */
  3626      return purposelyUnimplemented(sqllex, "reindex database", "CockroachDB does not require reindexing.")
  3627    }
  3628  | REINDEX SYSTEM error
  3629    {
  3630      /* SKIP DOC */
  3631      return purposelyUnimplemented(sqllex, "reindex system", "CockroachDB does not require reindexing.")
  3632    }
  3633  
  3634  // %Help: SHOW SESSION - display session variables
  3635  // %Category: Cfg
  3636  // %Text: SHOW [SESSION] { <var> | ALL }
  3637  // %SeeAlso: WEBDOCS/show-vars.html
  3638  show_session_stmt:
  3639    SHOW session_var         { $$.val = &tree.ShowVar{Name: $2} }
  3640  | SHOW SESSION session_var { $$.val = &tree.ShowVar{Name: $3} }
  3641  | SHOW SESSION error // SHOW HELP: SHOW SESSION
  3642  
  3643  session_var:
  3644    IDENT
  3645  // Although ALL, SESSION_USER and DATABASE are identifiers for the
  3646  // purpose of SHOW, they lex as separate token types, so they need
  3647  // separate rules.
  3648  | ALL
  3649  | DATABASE
  3650  // SET NAMES is standard SQL for SET client_encoding.
  3651  // See https://www.postgresql.org/docs/9.6/static/multibyte.html#AEN39236
  3652  | NAMES { $$ = "client_encoding" }
  3653  | SESSION_USER
  3654  // TIME ZONE is special: it is two tokens, but is really the identifier "TIME ZONE".
  3655  | TIME ZONE { $$ = "timezone" }
  3656  | TIME error // SHOW HELP: SHOW SESSION
  3657  
  3658  // %Help: SHOW STATISTICS - display table statistics (experimental)
  3659  // %Category: Experimental
  3660  // %Text: SHOW STATISTICS [USING JSON] FOR TABLE <table_name>
  3661  //
  3662  // Returns the available statistics for a table.
  3663  // The statistics can include a histogram ID, which can
  3664  // be used with SHOW HISTOGRAM.
  3665  // If USING JSON is specified, the statistics and histograms
  3666  // are encoded in JSON format.
  3667  // %SeeAlso: SHOW HISTOGRAM
  3668  show_stats_stmt:
  3669    SHOW STATISTICS FOR TABLE table_name
  3670    {
  3671      $$.val = &tree.ShowTableStats{Table: $5.unresolvedObjectName()}
  3672    }
  3673  | SHOW STATISTICS USING JSON FOR TABLE table_name
  3674    {
  3675      /* SKIP DOC */
  3676      $$.val = &tree.ShowTableStats{Table: $7.unresolvedObjectName(), UsingJSON: true}
  3677    }
  3678  | SHOW STATISTICS error // SHOW HELP: SHOW STATISTICS
  3679  
  3680  // %Help: SHOW HISTOGRAM - display histogram (experimental)
  3681  // %Category: Experimental
  3682  // %Text: SHOW HISTOGRAM <histogram_id>
  3683  //
  3684  // Returns the data in the histogram with the
  3685  // given ID (as returned by SHOW STATISTICS).
  3686  // %SeeAlso: SHOW STATISTICS
  3687  show_histogram_stmt:
  3688    SHOW HISTOGRAM ICONST
  3689    {
  3690      /* SKIP DOC */
  3691      id, err := $3.numVal().AsInt64()
  3692      if err != nil {
  3693        return setErr(sqllex, err)
  3694      }
  3695      $$.val = &tree.ShowHistogram{HistogramID: id}
  3696    }
  3697  | SHOW HISTOGRAM error // SHOW HELP: SHOW HISTOGRAM
  3698  
  3699  // %Help: SHOW BACKUP - list backup contents
  3700  // %Category: CCL
  3701  // %Text: SHOW BACKUP [SCHEMAS|FILES|RANGES] <location>
  3702  // %SeeAlso: WEBDOCS/show-backup.html
  3703  show_backup_stmt:
  3704    SHOW BACKUP string_or_placeholder opt_with_options
  3705    {
  3706      $$.val = &tree.ShowBackup{
  3707        Details: tree.BackupDefaultDetails,
  3708        Path:    $3.expr(),
  3709        Options: $4.kvOptions(),
  3710      }
  3711    }
  3712  | SHOW BACKUP SCHEMAS string_or_placeholder opt_with_options
  3713    {
  3714      $$.val = &tree.ShowBackup{
  3715        Details: tree.BackupDefaultDetails,
  3716        ShouldIncludeSchemas: true,
  3717        Path:    $4.expr(),
  3718        Options: $5.kvOptions(),
  3719      }
  3720    }
  3721  | SHOW BACKUP RANGES string_or_placeholder opt_with_options
  3722    {
  3723      /* SKIP DOC */
  3724      $$.val = &tree.ShowBackup{
  3725        Details: tree.BackupRangeDetails,
  3726        Path:    $4.expr(),
  3727        Options: $5.kvOptions(),
  3728      }
  3729    }
  3730  | SHOW BACKUP FILES string_or_placeholder opt_with_options
  3731    {
  3732      /* SKIP DOC */
  3733      $$.val = &tree.ShowBackup{
  3734        Details: tree.BackupFileDetails,
  3735        Path:    $4.expr(),
  3736        Options: $5.kvOptions(),
  3737      }
  3738    }
  3739  | SHOW BACKUP error // SHOW HELP: SHOW BACKUP
  3740  
  3741  // %Help: SHOW CLUSTER SETTING - display cluster settings
  3742  // %Category: Cfg
  3743  // %Text:
  3744  // SHOW CLUSTER SETTING <var>
  3745  // SHOW [ PUBLIC | ALL ] CLUSTER SETTINGS
  3746  // %SeeAlso: WEBDOCS/cluster-settings.html
  3747  show_csettings_stmt:
  3748    SHOW CLUSTER SETTING var_name
  3749    {
  3750      $$.val = &tree.ShowClusterSetting{Name: strings.Join($4.strs(), ".")}
  3751    }
  3752  | SHOW CLUSTER SETTING ALL
  3753    {
  3754      $$.val = &tree.ShowClusterSettingList{All: true}
  3755    }
  3756  | SHOW CLUSTER error // SHOW HELP: SHOW CLUSTER SETTING
  3757  | SHOW ALL CLUSTER SETTINGS
  3758    {
  3759      $$.val = &tree.ShowClusterSettingList{All: true}
  3760    }
  3761  | SHOW ALL CLUSTER error // SHOW HELP: SHOW CLUSTER SETTING
  3762  | SHOW CLUSTER SETTINGS
  3763    {
  3764      $$.val = &tree.ShowClusterSettingList{}
  3765    }
  3766  | SHOW PUBLIC CLUSTER SETTINGS
  3767    {
  3768      $$.val = &tree.ShowClusterSettingList{}
  3769    }
  3770  | SHOW PUBLIC CLUSTER error // SHOW HELP: SHOW CLUSTER SETTING
  3771  
  3772  // %Help: SHOW COLUMNS - list columns in relation
  3773  // %Category: DDL
  3774  // %Text: SHOW COLUMNS FROM <tablename>
  3775  // %SeeAlso: WEBDOCS/show-columns.html
  3776  show_columns_stmt:
  3777    SHOW COLUMNS FROM table_name with_comment
  3778    {
  3779      $$.val = &tree.ShowColumns{Table: $4.unresolvedObjectName(), WithComment: $5.bool()}
  3780    }
  3781  | SHOW COLUMNS error // SHOW HELP: SHOW COLUMNS
  3782  
  3783  // %Help: SHOW PARTITIONS - list partition information
  3784  // %Category: DDL
  3785  // %Text: SHOW PARTITIONS FROM { TABLE <table> | INDEX <index> | DATABASE <database> }
  3786  // %SeeAlso: WEBDOCS/show-partitions.html
  3787  show_partitions_stmt:
  3788    SHOW PARTITIONS FROM TABLE table_name
  3789    {
  3790      $$.val = &tree.ShowPartitions{IsTable: true, Table: $5.unresolvedObjectName()}
  3791    }
  3792  | SHOW PARTITIONS FROM DATABASE database_name
  3793    {
  3794      $$.val = &tree.ShowPartitions{IsDB: true, Database: tree.Name($5)}
  3795    }
  3796  | SHOW PARTITIONS FROM INDEX table_index_name
  3797    {
  3798      $$.val = &tree.ShowPartitions{IsIndex: true, Index: $5.tableIndexName()}
  3799    }
  3800  | SHOW PARTITIONS FROM INDEX table_name '@' '*'
  3801    {
  3802      $$.val = &tree.ShowPartitions{IsTable: true, Table: $5.unresolvedObjectName()}
  3803    }
  3804  | SHOW PARTITIONS error // SHOW HELP: SHOW PARTITIONS
  3805  
  3806  // %Help: SHOW DATABASES - list databases
  3807  // %Category: DDL
  3808  // %Text: SHOW DATABASES
  3809  // %SeeAlso: WEBDOCS/show-databases.html
  3810  show_databases_stmt:
  3811    SHOW DATABASES with_comment
  3812    {
  3813      $$.val = &tree.ShowDatabases{WithComment: $3.bool()}
  3814    }
  3815  | SHOW DATABASES error // SHOW HELP: SHOW DATABASES
  3816  
  3817  // %Help: SHOW GRANTS - list grants
  3818  // %Category: Priv
  3819  // %Text:
  3820  // Show privilege grants:
  3821  //   SHOW GRANTS [ON <targets...>] [FOR <users...>]
  3822  // Show role grants:
  3823  //   SHOW GRANTS ON ROLE [<roles...>] [FOR <grantees...>]
  3824  //
  3825  // %SeeAlso: WEBDOCS/show-grants.html
  3826  show_grants_stmt:
  3827    SHOW GRANTS opt_on_targets_roles for_grantee_clause
  3828    {
  3829      lst := $3.targetListPtr()
  3830      if lst != nil && lst.ForRoles {
  3831        $$.val = &tree.ShowRoleGrants{Roles: lst.Roles, Grantees: $4.nameList()}
  3832      } else {
  3833        $$.val = &tree.ShowGrants{Targets: lst, Grantees: $4.nameList()}
  3834      }
  3835    }
  3836  | SHOW GRANTS error // SHOW HELP: SHOW GRANTS
  3837  
  3838  // %Help: SHOW INDEXES - list indexes
  3839  // %Category: DDL
  3840  // %Text: SHOW INDEXES FROM { <tablename> | DATABASE <database_name> } [WITH COMMENT]
  3841  // %SeeAlso: WEBDOCS/show-index.html
  3842  show_indexes_stmt:
  3843    SHOW INDEX FROM table_name with_comment
  3844    {
  3845      $$.val = &tree.ShowIndexes{Table: $4.unresolvedObjectName(), WithComment: $5.bool()}
  3846    }
  3847  | SHOW INDEX error // SHOW HELP: SHOW INDEXES
  3848  | SHOW INDEX FROM DATABASE database_name with_comment
  3849    {
  3850      $$.val = &tree.ShowDatabaseIndexes{Database: tree.Name($5), WithComment: $6.bool()}
  3851    }
  3852  | SHOW INDEXES FROM table_name with_comment
  3853    {
  3854      $$.val = &tree.ShowIndexes{Table: $4.unresolvedObjectName(), WithComment: $5.bool()}
  3855    }
  3856  | SHOW INDEXES FROM DATABASE database_name with_comment
  3857    {
  3858      $$.val = &tree.ShowDatabaseIndexes{Database: tree.Name($5), WithComment: $6.bool()}
  3859    }
  3860  | SHOW INDEXES error // SHOW HELP: SHOW INDEXES
  3861  | SHOW KEYS FROM table_name with_comment
  3862    {
  3863      $$.val = &tree.ShowIndexes{Table: $4.unresolvedObjectName(), WithComment: $5.bool()}
  3864    }
  3865  | SHOW KEYS FROM DATABASE database_name with_comment
  3866    {
  3867      $$.val = &tree.ShowDatabaseIndexes{Database: tree.Name($5), WithComment: $6.bool()}
  3868    }
  3869  | SHOW KEYS error // SHOW HELP: SHOW INDEXES
  3870  
  3871  // %Help: SHOW CONSTRAINTS - list constraints
  3872  // %Category: DDL
  3873  // %Text: SHOW CONSTRAINTS FROM <tablename>
  3874  // %SeeAlso: WEBDOCS/show-constraints.html
  3875  show_constraints_stmt:
  3876    SHOW CONSTRAINT FROM table_name
  3877    {
  3878      $$.val = &tree.ShowConstraints{Table: $4.unresolvedObjectName()}
  3879    }
  3880  | SHOW CONSTRAINT error // SHOW HELP: SHOW CONSTRAINTS
  3881  | SHOW CONSTRAINTS FROM table_name
  3882    {
  3883      $$.val = &tree.ShowConstraints{Table: $4.unresolvedObjectName()}
  3884    }
  3885  | SHOW CONSTRAINTS error // SHOW HELP: SHOW CONSTRAINTS
  3886  
  3887  // %Help: SHOW QUERIES - list running queries
  3888  // %Category: Misc
  3889  // %Text: SHOW [ALL] [CLUSTER | LOCAL] QUERIES
  3890  // %SeeAlso: CANCEL QUERIES
  3891  show_queries_stmt:
  3892    SHOW opt_cluster QUERIES
  3893    {
  3894      $$.val = &tree.ShowQueries{All: false, Cluster: $2.bool()}
  3895    }
  3896  | SHOW opt_cluster QUERIES error // SHOW HELP: SHOW QUERIES
  3897  | SHOW ALL opt_cluster QUERIES
  3898    {
  3899      $$.val = &tree.ShowQueries{All: true, Cluster: $3.bool()}
  3900    }
  3901  | SHOW ALL opt_cluster QUERIES error // SHOW HELP: SHOW QUERIES
  3902  
  3903  opt_cluster:
  3904    /* EMPTY */
  3905    { $$.val = true }
  3906  | CLUSTER
  3907    { $$.val = true }
  3908  | LOCAL
  3909    { $$.val = false }
  3910  
  3911  // %Help: SHOW JOBS - list background jobs
  3912  // %Category: Misc
  3913  // %Text:
  3914  // SHOW [AUTOMATIC] JOBS
  3915  // SHOW JOB <jobid>
  3916  // %SeeAlso: CANCEL JOBS, PAUSE JOBS, RESUME JOBS
  3917  show_jobs_stmt:
  3918    SHOW AUTOMATIC JOBS
  3919    {
  3920      $$.val = &tree.ShowJobs{Automatic: true}
  3921    }
  3922  | SHOW JOBS
  3923    {
  3924      $$.val = &tree.ShowJobs{Automatic: false}
  3925    }
  3926  | SHOW AUTOMATIC JOBS error // SHOW HELP: SHOW JOBS
  3927  | SHOW JOBS error // SHOW HELP: SHOW JOBS
  3928  | SHOW JOBS select_stmt
  3929    {
  3930      $$.val = &tree.ShowJobs{Jobs: $3.slct()}
  3931    }
  3932  | SHOW JOBS WHEN COMPLETE select_stmt
  3933    {
  3934      $$.val = &tree.ShowJobs{Jobs: $5.slct(), Block: true}
  3935    }
  3936  | SHOW JOBS select_stmt error // SHOW HELP: SHOW JOBS
  3937  | SHOW JOB a_expr
  3938    {
  3939      $$.val = &tree.ShowJobs{
  3940        Jobs: &tree.Select{
  3941          Select: &tree.ValuesClause{Rows: []tree.Exprs{tree.Exprs{$3.expr()}}},
  3942        },
  3943      }
  3944    }
  3945  | SHOW JOB WHEN COMPLETE a_expr
  3946    {
  3947      $$.val = &tree.ShowJobs{
  3948        Jobs: &tree.Select{
  3949          Select: &tree.ValuesClause{Rows: []tree.Exprs{tree.Exprs{$5.expr()}}},
  3950        },
  3951        Block: true,
  3952      }
  3953    }
  3954  | SHOW JOB error // SHOW HELP: SHOW JOBS
  3955  
  3956  // %Help: SHOW TRACE - display an execution trace
  3957  // %Category: Misc
  3958  // %Text:
  3959  // SHOW [COMPACT] [KV] TRACE FOR SESSION
  3960  // %SeeAlso: EXPLAIN
  3961  show_trace_stmt:
  3962    SHOW opt_compact TRACE FOR SESSION
  3963    {
  3964      $$.val = &tree.ShowTraceForSession{TraceType: tree.ShowTraceRaw, Compact: $2.bool()}
  3965    }
  3966  | SHOW opt_compact TRACE error // SHOW HELP: SHOW TRACE
  3967  | SHOW opt_compact KV TRACE FOR SESSION
  3968    {
  3969      $$.val = &tree.ShowTraceForSession{TraceType: tree.ShowTraceKV, Compact: $2.bool()}
  3970    }
  3971  | SHOW opt_compact KV error // SHOW HELP: SHOW TRACE
  3972  | SHOW opt_compact EXPERIMENTAL_REPLICA TRACE FOR SESSION
  3973    {
  3974      /* SKIP DOC */
  3975      $$.val = &tree.ShowTraceForSession{TraceType: tree.ShowTraceReplica, Compact: $2.bool()}
  3976    }
  3977  | SHOW opt_compact EXPERIMENTAL_REPLICA error // SHOW HELP: SHOW TRACE
  3978  
  3979  opt_compact:
  3980    COMPACT { $$.val = true }
  3981  | /* EMPTY */ { $$.val = false }
  3982  
  3983  // %Help: SHOW SESSIONS - list open client sessions
  3984  // %Category: Misc
  3985  // %Text: SHOW [ALL] [CLUSTER | LOCAL] SESSIONS
  3986  // %SeeAlso: CANCEL SESSIONS
  3987  show_sessions_stmt:
  3988    SHOW opt_cluster SESSIONS
  3989    {
  3990      $$.val = &tree.ShowSessions{Cluster: $2.bool()}
  3991    }
  3992  | SHOW opt_cluster SESSIONS error // SHOW HELP: SHOW SESSIONS
  3993  | SHOW ALL opt_cluster SESSIONS
  3994    {
  3995      $$.val = &tree.ShowSessions{All: true, Cluster: $3.bool()}
  3996    }
  3997  | SHOW ALL opt_cluster SESSIONS error // SHOW HELP: SHOW SESSIONS
  3998  
  3999  // %Help: SHOW TABLES - list tables
  4000  // %Category: DDL
  4001  // %Text: SHOW TABLES [FROM <databasename> [ . <schemaname> ] ] [WITH COMMENT]
  4002  // %SeeAlso: WEBDOCS/show-tables.html
  4003  show_tables_stmt:
  4004    SHOW TABLES FROM name '.' name with_comment
  4005    {
  4006      $$.val = &tree.ShowTables{ObjectNamePrefix:tree.ObjectNamePrefix{
  4007          CatalogName: tree.Name($4),
  4008          ExplicitCatalog: true,
  4009          SchemaName: tree.Name($6),
  4010          ExplicitSchema: true,
  4011      },
  4012      WithComment: $7.bool()}
  4013    }
  4014  | SHOW TABLES FROM name with_comment
  4015    {
  4016      $$.val = &tree.ShowTables{ObjectNamePrefix:tree.ObjectNamePrefix{
  4017          // Note: the schema name may be interpreted as database name,
  4018          // see name_resolution.go.
  4019          SchemaName: tree.Name($4),
  4020          ExplicitSchema: true,
  4021      },
  4022      WithComment: $5.bool()}
  4023    }
  4024  | SHOW TABLES with_comment
  4025    {
  4026      $$.val = &tree.ShowTables{WithComment: $3.bool()}
  4027    }
  4028  | SHOW TABLES error // SHOW HELP: SHOW TABLES
  4029  
  4030  with_comment:
  4031    WITH COMMENT { $$.val = true }
  4032  | /* EMPTY */  { $$.val = false }
  4033  
  4034  // %Help: SHOW SCHEMAS - list schemas
  4035  // %Category: DDL
  4036  // %Text: SHOW SCHEMAS [FROM <databasename> ]
  4037  show_schemas_stmt:
  4038    SHOW SCHEMAS FROM name
  4039    {
  4040      $$.val = &tree.ShowSchemas{Database: tree.Name($4)}
  4041    }
  4042  | SHOW SCHEMAS
  4043    {
  4044      $$.val = &tree.ShowSchemas{}
  4045    }
  4046  | SHOW SCHEMAS error // SHOW HELP: SHOW SCHEMAS
  4047  
  4048  // %Help: SHOW SEQUENCES - list sequences
  4049  // %Category: DDL
  4050  // %Text: SHOW SEQUENCES [FROM <databasename> ]
  4051  show_sequences_stmt:
  4052    SHOW SEQUENCES FROM name
  4053    {
  4054      $$.val = &tree.ShowSequences{Database: tree.Name($4)}
  4055    }
  4056  | SHOW SEQUENCES
  4057    {
  4058      $$.val = &tree.ShowSequences{}
  4059    }
  4060  | SHOW SEQUENCES error // SHOW HELP: SHOW SEQUENCES
  4061  
  4062  // %Help: SHOW SYNTAX - analyze SQL syntax
  4063  // %Category: Misc
  4064  // %Text: SHOW SYNTAX <string>
  4065  show_syntax_stmt:
  4066    SHOW SYNTAX SCONST
  4067    {
  4068      /* SKIP DOC */
  4069      $$.val = &tree.ShowSyntax{Statement: $3}
  4070    }
  4071  | SHOW SYNTAX error // SHOW HELP: SHOW SYNTAX
  4072  
  4073  // %Help: SHOW SAVEPOINT - display current savepoint properties
  4074  // %Category: Cfg
  4075  // %Text: SHOW SAVEPOINT STATUS
  4076  show_savepoint_stmt:
  4077    SHOW SAVEPOINT STATUS
  4078    {
  4079      $$.val = &tree.ShowSavepointStatus{}
  4080    }
  4081  | SHOW SAVEPOINT error // SHOW HELP: SHOW SAVEPOINT
  4082  
  4083  // %Help: SHOW TRANSACTION - display current transaction properties
  4084  // %Category: Cfg
  4085  // %Text: SHOW TRANSACTION {ISOLATION LEVEL | PRIORITY | STATUS}
  4086  // %SeeAlso: WEBDOCS/show-transaction.html
  4087  show_transaction_stmt:
  4088    SHOW TRANSACTION ISOLATION LEVEL
  4089    {
  4090      /* SKIP DOC */
  4091      $$.val = &tree.ShowVar{Name: "transaction_isolation"}
  4092    }
  4093  | SHOW TRANSACTION PRIORITY
  4094    {
  4095      /* SKIP DOC */
  4096      $$.val = &tree.ShowVar{Name: "transaction_priority"}
  4097    }
  4098  | SHOW TRANSACTION STATUS
  4099    {
  4100      /* SKIP DOC */
  4101      $$.val = &tree.ShowTransactionStatus{}
  4102    }
  4103  | SHOW TRANSACTION error // SHOW HELP: SHOW TRANSACTION
  4104  
  4105  // %Help: SHOW CREATE - display the CREATE statement for a table, sequence or view
  4106  // %Category: DDL
  4107  // %Text: SHOW CREATE [ TABLE | SEQUENCE | VIEW ] <tablename>
  4108  // %SeeAlso: WEBDOCS/show-create-table.html
  4109  show_create_stmt:
  4110    SHOW CREATE table_name
  4111    {
  4112      $$.val = &tree.ShowCreate{Name: $3.unresolvedObjectName()}
  4113    }
  4114  | SHOW CREATE create_kw table_name
  4115    {
  4116      /* SKIP DOC */
  4117      $$.val = &tree.ShowCreate{Name: $4.unresolvedObjectName()}
  4118    }
  4119  | SHOW CREATE error // SHOW HELP: SHOW CREATE
  4120  
  4121  create_kw:
  4122    TABLE
  4123  | VIEW
  4124  | SEQUENCE
  4125  
  4126  // %Help: SHOW USERS - list defined users
  4127  // %Category: Priv
  4128  // %Text: SHOW USERS
  4129  // %SeeAlso: CREATE USER, DROP USER, WEBDOCS/show-users.html
  4130  show_users_stmt:
  4131    SHOW USERS
  4132    {
  4133      $$.val = &tree.ShowUsers{}
  4134    }
  4135  | SHOW USERS error // SHOW HELP: SHOW USERS
  4136  
  4137  // %Help: SHOW ROLES - list defined roles
  4138  // %Category: Priv
  4139  // %Text: SHOW ROLES
  4140  // %SeeAlso: CREATE ROLE, ALTER ROLE, DROP ROLE
  4141  show_roles_stmt:
  4142    SHOW ROLES
  4143    {
  4144      $$.val = &tree.ShowRoles{}
  4145    }
  4146  | SHOW ROLES error // SHOW HELP: SHOW ROLES
  4147  
  4148  show_zone_stmt:
  4149    SHOW ZONE CONFIGURATION FOR RANGE zone_name
  4150    {
  4151      $$.val = &tree.ShowZoneConfig{ZoneSpecifier: tree.ZoneSpecifier{NamedZone: tree.UnrestrictedName($6)}}
  4152    }
  4153  | SHOW ZONE CONFIGURATION FOR DATABASE database_name
  4154    {
  4155      $$.val = &tree.ShowZoneConfig{ZoneSpecifier: tree.ZoneSpecifier{Database: tree.Name($6)}}
  4156    }
  4157  | SHOW ZONE CONFIGURATION FOR TABLE table_name opt_partition
  4158    {
  4159      name := $6.unresolvedObjectName().ToTableName()
  4160      $$.val = &tree.ShowZoneConfig{ZoneSpecifier: tree.ZoneSpecifier{
  4161          TableOrIndex: tree.TableIndexName{Table: name},
  4162          Partition: tree.Name($7),
  4163      }}
  4164    }
  4165  | SHOW ZONE CONFIGURATION FOR PARTITION partition_name OF TABLE table_name
  4166    {
  4167      name := $9.unresolvedObjectName().ToTableName()
  4168      $$.val = &tree.ShowZoneConfig{ZoneSpecifier: tree.ZoneSpecifier{
  4169        TableOrIndex: tree.TableIndexName{Table: name},
  4170        Partition: tree.Name($6),
  4171      }}
  4172    }
  4173  | SHOW ZONE CONFIGURATION FOR INDEX table_index_name opt_partition
  4174    {
  4175      $$.val = &tree.ShowZoneConfig{ZoneSpecifier: tree.ZoneSpecifier{
  4176        TableOrIndex: $6.tableIndexName(),
  4177        Partition: tree.Name($7),
  4178      }}
  4179    }
  4180  | SHOW ZONE CONFIGURATION FOR PARTITION partition_name OF INDEX table_index_name
  4181    {
  4182      $$.val = &tree.ShowZoneConfig{ZoneSpecifier: tree.ZoneSpecifier{
  4183        TableOrIndex: $9.tableIndexName(),
  4184        Partition: tree.Name($6),
  4185      }}
  4186    }
  4187  | SHOW ZONE CONFIGURATIONS
  4188    {
  4189      $$.val = &tree.ShowZoneConfig{}
  4190    }
  4191  | SHOW ALL ZONE CONFIGURATIONS
  4192    {
  4193      $$.val = &tree.ShowZoneConfig{}
  4194    }
  4195  
  4196  // %Help: SHOW RANGE - show range information for a row
  4197  // %Category: Misc
  4198  // %Text:
  4199  // SHOW RANGE FROM TABLE <tablename> FOR ROW (row, value, ...)
  4200  // SHOW RANGE FROM INDEX [ <tablename> @ ] <indexname> FOR ROW (row, value, ...)
  4201  show_range_for_row_stmt:
  4202    SHOW RANGE FROM TABLE table_name FOR ROW '(' expr_list ')'
  4203    {
  4204      name := $5.unresolvedObjectName().ToTableName()
  4205      $$.val = &tree.ShowRangeForRow{
  4206        Row: $9.exprs(),
  4207        TableOrIndex: tree.TableIndexName{Table: name},
  4208      }
  4209    }
  4210  | SHOW RANGE FROM INDEX table_index_name FOR ROW '(' expr_list ')'
  4211    {
  4212      $$.val = &tree.ShowRangeForRow{
  4213        Row: $9.exprs(),
  4214        TableOrIndex: $5.tableIndexName(),
  4215      }
  4216    }
  4217  | SHOW RANGE error // SHOW HELP: SHOW RANGE
  4218  
  4219  // %Help: SHOW RANGES - list ranges
  4220  // %Category: Misc
  4221  // %Text:
  4222  // SHOW RANGES FROM TABLE <tablename>
  4223  // SHOW RANGES FROM INDEX [ <tablename> @ ] <indexname>
  4224  show_ranges_stmt:
  4225    SHOW RANGES FROM TABLE table_name
  4226    {
  4227      name := $5.unresolvedObjectName().ToTableName()
  4228      $$.val = &tree.ShowRanges{TableOrIndex: tree.TableIndexName{Table: name}}
  4229    }
  4230  | SHOW RANGES FROM INDEX table_index_name
  4231    {
  4232      $$.val = &tree.ShowRanges{TableOrIndex: $5.tableIndexName()}
  4233    }
  4234  | SHOW RANGES FROM DATABASE database_name
  4235    {
  4236      $$.val = &tree.ShowRanges{DatabaseName: tree.Name($5)}
  4237    }
  4238  | SHOW RANGES error // SHOW HELP: SHOW RANGES
  4239  
  4240  show_fingerprints_stmt:
  4241    SHOW EXPERIMENTAL_FINGERPRINTS FROM TABLE table_name
  4242    {
  4243      /* SKIP DOC */
  4244      $$.val = &tree.ShowFingerprints{Table: $5.unresolvedObjectName()}
  4245    }
  4246  
  4247  opt_on_targets_roles:
  4248    ON targets_roles
  4249    {
  4250      tmp := $2.targetList()
  4251      $$.val = &tmp
  4252    }
  4253  | /* EMPTY */
  4254    {
  4255      $$.val = (*tree.TargetList)(nil)
  4256    }
  4257  
  4258  // targets is a non-terminal for a list of privilege targets, either a
  4259  // list of databases or a list of tables.
  4260  //
  4261  // This rule is complex and cannot be decomposed as a tree of
  4262  // non-terminals because it must resolve syntax ambiguities in the
  4263  // SHOW GRANTS ON ROLE statement. It was constructed as follows.
  4264  //
  4265  // 1. Start with the desired definition of targets:
  4266  //
  4267  //    targets ::=
  4268  //        table_pattern_list
  4269  //        TABLE table_pattern_list
  4270  //        DATABASE name_list
  4271  //
  4272  // 2. Now we must disambiguate the first rule "table_pattern_list"
  4273  //    between one that recognizes ROLE and one that recognizes
  4274  //    "<some table pattern list>". So first, inline the definition of
  4275  //    table_pattern_list.
  4276  //
  4277  //    targets ::=
  4278  //        table_pattern                          # <- here
  4279  //        table_pattern_list ',' table_pattern   # <- here
  4280  //        TABLE table_pattern_list
  4281  //        DATABASE name_list
  4282  //
  4283  // 3. We now must disambiguate the "ROLE" inside the prefix "table_pattern".
  4284  //    However having "table_pattern_list" as prefix is cumbersome, so swap it.
  4285  //
  4286  //    targets ::=
  4287  //        table_pattern
  4288  //        table_pattern ',' table_pattern_list   # <- here
  4289  //        TABLE table_pattern_list
  4290  //        DATABASE name_list
  4291  //
  4292  // 4. The rule that has table_pattern followed by a comma is now
  4293  //    non-problematic, because it will never match "ROLE" followed
  4294  //    by an optional name list (neither "ROLE;" nor "ROLE <ident>"
  4295  //    would match). We just need to focus on the first one "table_pattern".
  4296  //    This needs to tweak "table_pattern".
  4297  //
  4298  //    Here we could inline table_pattern but now we do not have to any
  4299  //    more, we just need to create a variant of it which is
  4300  //    unambiguous with a single ROLE keyword. That is, we need a
  4301  //    table_pattern which cannot contain a single name. We do
  4302  //    this as follows.
  4303  //
  4304  //    targets ::=
  4305  //        complex_table_pattern                  # <- here
  4306  //        table_pattern ',' table_pattern_list
  4307  //        TABLE table_pattern_list
  4308  //        DATABASE name_list
  4309  //    complex_table_pattern ::=
  4310  //        name '.' unrestricted_name
  4311  //        name '.' unrestricted_name '.' unrestricted_name
  4312  //        name '.' unrestricted_name '.' '*'
  4313  //        name '.' '*'
  4314  //        '*'
  4315  //
  4316  // 5. At this point the rule cannot start with a simple identifier any
  4317  //    more, keyword or not. But more importantly, any token sequence
  4318  //    that starts with ROLE cannot be matched by any of these remaining
  4319  //    rules. This means that the prefix is now free to use, without
  4320  //    ambiguity. We do this as follows, to gain a syntax rule for "ROLE
  4321  //    <namelist>". (We will handle a ROLE with no name list below.)
  4322  //
  4323  //    targets ::=
  4324  //        ROLE name_list                        # <- here
  4325  //        complex_table_pattern
  4326  //        table_pattern ',' table_pattern_list
  4327  //        TABLE table_pattern_list
  4328  //        DATABASE name_list
  4329  //
  4330  // 6. Now on to the finishing touches. First we would like to regain the
  4331  //    ability to use "<tablename>" when the table name is a simple
  4332  //    identifier. This is done as follows:
  4333  //
  4334  //    targets ::=
  4335  //        ROLE name_list
  4336  //        name                                  # <- here
  4337  //        complex_table_pattern
  4338  //        table_pattern ',' table_pattern_list
  4339  //        TABLE table_pattern_list
  4340  //        DATABASE name_list
  4341  //
  4342  // 7. Then, we want to recognize "ROLE" without any subsequent name
  4343  //    list. This requires some care: we can not add "ROLE" to the set of
  4344  //    rules above, because "name" would then overlap. To disambiguate,
  4345  //    we must first inline "name" as follows:
  4346  //
  4347  //    targets ::=
  4348  //        ROLE name_list
  4349  //        IDENT                    # <- here, always <table>
  4350  //        col_name_keyword         # <- here, always <table>
  4351  //        unreserved_keyword       # <- here, either ROLE or <table>
  4352  //        complex_table_pattern
  4353  //        table_pattern ',' table_pattern_list
  4354  //        TABLE table_pattern_list
  4355  //        DATABASE name_list
  4356  //
  4357  // 8. And now the rule is sufficiently simple that we can disambiguate
  4358  //    in the action, like this:
  4359  //
  4360  //    targets ::=
  4361  //        ...
  4362  //        unreserved_keyword {
  4363  //             if $1 == "role" { /* handle ROLE */ }
  4364  //             else { /* handle ON <tablename> */ }
  4365  //        }
  4366  //        ...
  4367  //
  4368  //   (but see the comment on the action of this sub-rule below for
  4369  //   more nuance.)
  4370  //
  4371  // Tada!
  4372  targets:
  4373    IDENT
  4374    {
  4375      $$.val = tree.TargetList{Tables: tree.TablePatterns{&tree.UnresolvedName{NumParts:1, Parts: tree.NameParts{$1}}}}
  4376    }
  4377  | col_name_keyword
  4378    {
  4379      $$.val = tree.TargetList{Tables: tree.TablePatterns{&tree.UnresolvedName{NumParts:1, Parts: tree.NameParts{$1}}}}
  4380    }
  4381  | unreserved_keyword
  4382    {
  4383      // This sub-rule is meant to support both ROLE and other keywords
  4384      // used as table name without the TABLE prefix. The keyword ROLE
  4385      // here can have two meanings:
  4386      //
  4387      // - for all statements except SHOW GRANTS, it must be interpreted
  4388      //   as a plain table name.
  4389      // - for SHOW GRANTS specifically, it must be handled as an ON ROLE
  4390      //   specifier without a name list (the rule with a name list is separate,
  4391      //   see above).
  4392      //
  4393      // Yet we want to use a single "targets" non-terminal for all
  4394      // statements that use targets, to share the code. This action
  4395      // achieves this as follows:
  4396      //
  4397      // - for all statements (including SHOW GRANTS), it populates the
  4398      //   Tables list in TargetList{} with the given name. This will
  4399      //   include the given keyword as table pattern in all cases,
  4400      //   including when the keyword was ROLE.
  4401      //
  4402      // - if ROLE was specified, it remembers this fact in the ForRoles
  4403      //   field. This distinguishes `ON ROLE` (where "role" is
  4404      //   specified as keyword), which triggers the special case in
  4405      //   SHOW GRANTS, from `ON "role"` (where "role" is specified as
  4406      //   identifier), which is always handled as a table name.
  4407      //
  4408      //   Both `ON ROLE` and `ON "role"` populate the Tables list in the same way,
  4409      //   so that other statements than SHOW GRANTS don't observe any difference.
  4410      //
  4411      // Arguably this code is a bit too clever. Future work should aim
  4412      // to remove the special casing of SHOW GRANTS altogether instead
  4413      // of increasing (or attempting to modify) the grey magic occurring
  4414      // here.
  4415      $$.val = tree.TargetList{
  4416        Tables: tree.TablePatterns{&tree.UnresolvedName{NumParts:1, Parts: tree.NameParts{$1}}},
  4417        ForRoles: $1 == "role", // backdoor for "SHOW GRANTS ON ROLE" (no name list)
  4418      }
  4419    }
  4420  | complex_table_pattern
  4421    {
  4422      $$.val = tree.TargetList{Tables: tree.TablePatterns{$1.unresolvedName()}}
  4423    }
  4424  | table_pattern ',' table_pattern_list
  4425    {
  4426      remainderPats := $3.tablePatterns()
  4427      $$.val = tree.TargetList{Tables: append(tree.TablePatterns{$1.unresolvedName()}, remainderPats...)}
  4428    }
  4429  | TABLE table_pattern_list
  4430    {
  4431      $$.val = tree.TargetList{Tables: $2.tablePatterns()}
  4432    }
  4433  | DATABASE name_list
  4434    {
  4435      $$.val = tree.TargetList{Databases: $2.nameList()}
  4436    }
  4437  
  4438  // target_roles is the variant of targets which recognizes ON ROLES
  4439  // with a name list. This cannot be included in targets directly
  4440  // because some statements must not recognize this syntax.
  4441  targets_roles:
  4442    ROLE name_list
  4443    {
  4444       $$.val = tree.TargetList{ForRoles: true, Roles: $2.nameList()}
  4445    }
  4446  | targets
  4447  
  4448  for_grantee_clause:
  4449    FOR name_list
  4450    {
  4451      $$.val = $2.nameList()
  4452    }
  4453  | /* EMPTY */
  4454    {
  4455      $$.val = tree.NameList(nil)
  4456    }
  4457  
  4458  // %Help: PAUSE JOBS - pause background jobs
  4459  // %Category: Misc
  4460  // %Text:
  4461  // PAUSE JOBS <selectclause>
  4462  // PAUSE JOB <jobid>
  4463  // %SeeAlso: SHOW JOBS, CANCEL JOBS, RESUME JOBS
  4464  pause_stmt:
  4465    PAUSE JOB a_expr
  4466    {
  4467      $$.val = &tree.ControlJobs{
  4468        Jobs: &tree.Select{
  4469          Select: &tree.ValuesClause{Rows: []tree.Exprs{tree.Exprs{$3.expr()}}},
  4470        },
  4471        Command: tree.PauseJob,
  4472      }
  4473    }
  4474  | PAUSE JOBS select_stmt
  4475    {
  4476      $$.val = &tree.ControlJobs{Jobs: $3.slct(), Command: tree.PauseJob}
  4477    }
  4478  | PAUSE error // SHOW HELP: PAUSE JOBS
  4479  
  4480  // %Help: CREATE SCHEMA - create a new schema (not yet supported)
  4481  // %Category: DDL
  4482  // %Text:
  4483  // CREATE SCHEMA [IF NOT EXISTS] <schemaname>
  4484  create_schema_stmt:
  4485    CREATE SCHEMA schema_name
  4486    {
  4487      $$.val = &tree.CreateSchema{
  4488        Schema: $3,
  4489      }
  4490    }
  4491  | CREATE SCHEMA IF NOT EXISTS schema_name
  4492    {
  4493      $$.val = &tree.CreateSchema{
  4494        Schema: $6,
  4495        IfNotExists: true,
  4496      }
  4497    }
  4498  | CREATE SCHEMA error // SHOW HELP: CREATE SCHEMA
  4499  
  4500  // %Help: CREATE TABLE - create a new table
  4501  // %Category: DDL
  4502  // %Text:
  4503  // CREATE [[GLOBAL | LOCAL] {TEMPORARY | TEMP}] TABLE [IF NOT EXISTS] <tablename> ( <elements...> ) [<interleave>] [<on_commit>]
  4504  // CREATE [[GLOBAL | LOCAL] {TEMPORARY | TEMP}] TABLE [IF NOT EXISTS] <tablename> [( <colnames...> )] AS <source> [<interleave>] [<on commit>]
  4505  //
  4506  // Table elements:
  4507  //    <name> <type> [<qualifiers...>]
  4508  //    [UNIQUE | INVERTED] INDEX [<name>] ( <colname> [ASC | DESC] [, ...] )
  4509  //                            [USING HASH WITH BUCKET_COUNT = <shard_buckets>] [{STORING | INCLUDE | COVERING} ( <colnames...> )] [<interleave>]
  4510  //    FAMILY [<name>] ( <colnames...> )
  4511  //    [CONSTRAINT <name>] <constraint>
  4512  //
  4513  // Table constraints:
  4514  //    PRIMARY KEY ( <colnames...> ) [USING HASH WITH BUCKET_COUNT = <shard_buckets>]
  4515  //    FOREIGN KEY ( <colnames...> ) REFERENCES <tablename> [( <colnames...> )] [ON DELETE {NO ACTION | RESTRICT}] [ON UPDATE {NO ACTION | RESTRICT}]
  4516  //    UNIQUE ( <colnames... ) [{STORING | INCLUDE | COVERING} ( <colnames...> )] [<interleave>]
  4517  //    CHECK ( <expr> )
  4518  //
  4519  // Column qualifiers:
  4520  //   [CONSTRAINT <constraintname>] {NULL | NOT NULL | UNIQUE | PRIMARY KEY | CHECK (<expr>) | DEFAULT <expr>}
  4521  //   FAMILY <familyname>, CREATE [IF NOT EXISTS] FAMILY [<familyname>]
  4522  //   REFERENCES <tablename> [( <colnames...> )] [ON DELETE {NO ACTION | RESTRICT}] [ON UPDATE {NO ACTION | RESTRICT}]
  4523  //   COLLATE <collationname>
  4524  //   AS ( <expr> ) STORED
  4525  //
  4526  // Interleave clause:
  4527  //    INTERLEAVE IN PARENT <tablename> ( <colnames...> ) [CASCADE | RESTRICT]
  4528  //
  4529  // On commit clause:
  4530  //    ON COMMIT {PRESERVE ROWS | DROP | DELETE ROWS}
  4531  //
  4532  // %SeeAlso: SHOW TABLES, CREATE VIEW, SHOW CREATE,
  4533  // WEBDOCS/create-table.html
  4534  // WEBDOCS/create-table-as.html
  4535  create_table_stmt:
  4536    CREATE opt_temp_create_table TABLE table_name '(' opt_table_elem_list ')' opt_interleave opt_partition_by opt_table_with opt_create_table_on_commit
  4537    {
  4538      name := $4.unresolvedObjectName().ToTableName()
  4539      $$.val = &tree.CreateTable{
  4540        Table: name,
  4541        IfNotExists: false,
  4542        Interleave: $8.interleave(),
  4543        Defs: $6.tblDefs(),
  4544        AsSource: nil,
  4545        PartitionBy: $9.partitionBy(),
  4546        Temporary: $2.persistenceType(),
  4547        StorageParams: $10.storageParams(),
  4548        OnCommit: $11.createTableOnCommitSetting(),
  4549      }
  4550    }
  4551  | CREATE opt_temp_create_table TABLE IF NOT EXISTS table_name '(' opt_table_elem_list ')' opt_interleave opt_partition_by opt_table_with opt_create_table_on_commit
  4552    {
  4553      name := $7.unresolvedObjectName().ToTableName()
  4554      $$.val = &tree.CreateTable{
  4555        Table: name,
  4556        IfNotExists: true,
  4557        Interleave: $11.interleave(),
  4558        Defs: $9.tblDefs(),
  4559        AsSource: nil,
  4560        PartitionBy: $12.partitionBy(),
  4561        Temporary: $2.persistenceType(),
  4562        StorageParams: $13.storageParams(),
  4563        OnCommit: $14.createTableOnCommitSetting(),
  4564      }
  4565    }
  4566  
  4567  opt_table_with:
  4568    /* EMPTY */
  4569    {
  4570      $$.val = nil
  4571    }
  4572  | WITHOUT OIDS
  4573    {
  4574      /* SKIP DOC */
  4575      /* this is also the default in CockroachDB */
  4576      $$.val = nil
  4577    }
  4578  | WITH '(' storage_parameter_list ')'
  4579    {
  4580      /* SKIP DOC */
  4581      $$.val = $3.storageParams()
  4582    }
  4583  | WITH OIDS error
  4584    {
  4585      return unimplemented(sqllex, "create table with oids")
  4586    }
  4587  
  4588  opt_create_table_on_commit:
  4589    /* EMPTY */
  4590    {
  4591      $$.val = tree.CreateTableOnCommitUnset
  4592    }
  4593  | ON COMMIT PRESERVE ROWS
  4594    {
  4595      /* SKIP DOC */
  4596      $$.val = tree.CreateTableOnCommitPreserveRows
  4597    }
  4598  | ON COMMIT DELETE ROWS error
  4599    {
  4600      /* SKIP DOC */
  4601      return unimplementedWithIssueDetail(sqllex, 46556, "delete rows")
  4602    }
  4603  | ON COMMIT DROP error
  4604    {
  4605      /* SKIP DOC */
  4606      return unimplementedWithIssueDetail(sqllex, 46556, "drop")
  4607    }
  4608  
  4609  storage_parameter:
  4610    name '=' d_expr
  4611    {
  4612      $$.val = tree.StorageParam{Key: tree.Name($1), Value: $3.expr()}
  4613    }
  4614  |  SCONST '=' d_expr
  4615    {
  4616      $$.val = tree.StorageParam{Key: tree.Name($1), Value: $3.expr()}
  4617    }
  4618  
  4619  storage_parameter_list:
  4620    storage_parameter
  4621    {
  4622      $$.val = []tree.StorageParam{$1.storageParam()}
  4623    }
  4624  |  storage_parameter_list ',' storage_parameter
  4625    {
  4626      $$.val = append($1.storageParams(), $3.storageParam())
  4627    }
  4628  
  4629  create_table_as_stmt:
  4630    CREATE opt_temp_create_table TABLE table_name create_as_opt_col_list opt_table_with AS select_stmt opt_create_as_data opt_create_table_on_commit
  4631    {
  4632      name := $4.unresolvedObjectName().ToTableName()
  4633      $$.val = &tree.CreateTable{
  4634        Table: name,
  4635        IfNotExists: false,
  4636        Interleave: nil,
  4637        Defs: $5.tblDefs(),
  4638        AsSource: $8.slct(),
  4639        StorageParams: $6.storageParams(),
  4640        OnCommit: $10.createTableOnCommitSetting(),
  4641      }
  4642    }
  4643  | CREATE opt_temp_create_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
  4644    {
  4645      name := $7.unresolvedObjectName().ToTableName()
  4646      $$.val = &tree.CreateTable{
  4647        Table: name,
  4648        IfNotExists: true,
  4649        Interleave: nil,
  4650        Defs: $8.tblDefs(),
  4651        AsSource: $11.slct(),
  4652        StorageParams: $9.storageParams(),
  4653        OnCommit: $13.createTableOnCommitSetting(),
  4654      }
  4655    }
  4656  
  4657  opt_create_as_data:
  4658    /* EMPTY */  { /* no error */ }
  4659  | WITH DATA    { /* SKIP DOC */ /* This is the default */ }
  4660  | WITH NO DATA { return unimplemented(sqllex, "create table as with no data") }
  4661  
  4662  /*
  4663   * Redundancy here is needed to avoid shift/reduce conflicts,
  4664   * since TEMP is not a reserved word.  See also OptTempTableName.
  4665   *
  4666   * NOTE: we accept both GLOBAL and LOCAL options.  They currently do nothing,
  4667   * but future versions might consider GLOBAL to request SQL-spec-compliant
  4668   * temp table behavior.  Since we have no modules the
  4669   * LOCAL keyword is really meaningless; furthermore, some other products
  4670   * implement LOCAL as meaning the same as our default temp table behavior,
  4671   * so we'll probably continue to treat LOCAL as a noise word.
  4672   *
  4673   * NOTE: PG only accepts GLOBAL/LOCAL keywords for temp tables -- not sequences
  4674   * and views. These keywords are no-ops in PG. This behavior is replicated by
  4675   * making the distinction between opt_temp and opt_temp_create_table.
  4676   */
  4677   opt_temp:
  4678    TEMPORARY         { $$.val = true }
  4679  | TEMP              { $$.val = true }
  4680  | /*EMPTY*/         { $$.val = false }
  4681  
  4682  opt_temp_create_table:
  4683     opt_temp
  4684  |  LOCAL TEMPORARY   { $$.val = true }
  4685  | LOCAL TEMP        { $$.val = true }
  4686  | GLOBAL TEMPORARY  { $$.val = true }
  4687  | GLOBAL TEMP       { $$.val = true }
  4688  | UNLOGGED          { return unimplemented(sqllex, "create unlogged") }
  4689  
  4690  opt_table_elem_list:
  4691    table_elem_list
  4692  | /* EMPTY */
  4693    {
  4694      $$.val = tree.TableDefs(nil)
  4695    }
  4696  
  4697  table_elem_list:
  4698    table_elem
  4699    {
  4700      $$.val = tree.TableDefs{$1.tblDef()}
  4701    }
  4702  | table_elem_list ',' table_elem
  4703    {
  4704      $$.val = append($1.tblDefs(), $3.tblDef())
  4705    }
  4706  
  4707  table_elem:
  4708    column_def
  4709    {
  4710      $$.val = $1.colDef()
  4711    }
  4712  | index_def
  4713  | family_def
  4714  | table_constraint
  4715    {
  4716      $$.val = $1.constraintDef()
  4717    }
  4718  | LIKE table_name like_table_option_list
  4719    {
  4720      $$.val = &tree.LikeTableDef{
  4721        Name: $2.unresolvedObjectName().ToTableName(),
  4722        Options: $3.likeTableOptionList(),
  4723      }
  4724    }
  4725  
  4726  like_table_option_list:
  4727    like_table_option_list INCLUDING like_table_option
  4728    {
  4729      $$.val = append($1.likeTableOptionList(), $3.likeTableOption())
  4730    }
  4731  | like_table_option_list EXCLUDING like_table_option
  4732    {
  4733      opt := $3.likeTableOption()
  4734      opt.Excluded = true
  4735      $$.val = append($1.likeTableOptionList(), opt)
  4736    }
  4737  | /* EMPTY */
  4738    {
  4739      $$.val = []tree.LikeTableOption(nil)
  4740    }
  4741  
  4742  like_table_option:
  4743    COMMENTS			{ return unimplementedWithIssueDetail(sqllex, 47071, "like table in/excluding comments") }
  4744  | CONSTRAINTS		{ $$.val = tree.LikeTableOption{Opt: tree.LikeTableOptConstraints} }
  4745  | DEFAULTS			{ $$.val = tree.LikeTableOption{Opt: tree.LikeTableOptDefaults} }
  4746  | IDENTITY	  	{ return unimplementedWithIssueDetail(sqllex, 47071, "like table in/excluding identity") }
  4747  | GENERATED			{ $$.val = tree.LikeTableOption{Opt: tree.LikeTableOptGenerated} }
  4748  | INDEXES			{ $$.val = tree.LikeTableOption{Opt: tree.LikeTableOptIndexes} }
  4749  | STATISTICS		{ return unimplementedWithIssueDetail(sqllex, 47071, "like table in/excluding statistics") }
  4750  | STORAGE			{ return unimplementedWithIssueDetail(sqllex, 47071, "like table in/excluding storage") }
  4751  | ALL				{ $$.val = tree.LikeTableOption{Opt: tree.LikeTableOptAll} }
  4752  
  4753  
  4754  opt_interleave:
  4755    INTERLEAVE IN PARENT table_name '(' name_list ')' opt_interleave_drop_behavior
  4756    {
  4757      name := $4.unresolvedObjectName().ToTableName()
  4758      $$.val = &tree.InterleaveDef{
  4759        Parent: name,
  4760        Fields: $6.nameList(),
  4761        DropBehavior: $8.dropBehavior(),
  4762      }
  4763    }
  4764  | /* EMPTY */
  4765    {
  4766      $$.val = (*tree.InterleaveDef)(nil)
  4767    }
  4768  
  4769  // TODO(dan): This can be removed in favor of opt_drop_behavior when #7854 is fixed.
  4770  opt_interleave_drop_behavior:
  4771    CASCADE
  4772    {
  4773      /* SKIP DOC */
  4774      $$.val = tree.DropCascade
  4775    }
  4776  | RESTRICT
  4777    {
  4778      /* SKIP DOC */
  4779      $$.val = tree.DropRestrict
  4780    }
  4781  | /* EMPTY */
  4782    {
  4783      $$.val = tree.DropDefault
  4784    }
  4785  
  4786  partition:
  4787    PARTITION partition_name
  4788    {
  4789      $$ = $2
  4790    }
  4791  
  4792  opt_partition:
  4793    partition
  4794  | /* EMPTY */
  4795    {
  4796      $$ = ""
  4797    }
  4798  
  4799  opt_partition_by:
  4800    partition_by
  4801  | /* EMPTY */
  4802    {
  4803      $$.val = (*tree.PartitionBy)(nil)
  4804    }
  4805  
  4806  partition_by:
  4807    PARTITION BY LIST '(' name_list ')' '(' list_partitions ')'
  4808    {
  4809      $$.val = &tree.PartitionBy{
  4810        Fields: $5.nameList(),
  4811        List: $8.listPartitions(),
  4812      }
  4813    }
  4814  | PARTITION BY RANGE '(' name_list ')' '(' range_partitions ')'
  4815    {
  4816      $$.val = &tree.PartitionBy{
  4817        Fields: $5.nameList(),
  4818        Range: $8.rangePartitions(),
  4819      }
  4820    }
  4821  | PARTITION BY NOTHING
  4822    {
  4823      $$.val = (*tree.PartitionBy)(nil)
  4824    }
  4825  
  4826  list_partitions:
  4827    list_partition
  4828    {
  4829      $$.val = []tree.ListPartition{$1.listPartition()}
  4830    }
  4831  | list_partitions ',' list_partition
  4832    {
  4833      $$.val = append($1.listPartitions(), $3.listPartition())
  4834    }
  4835  
  4836  list_partition:
  4837    partition VALUES IN '(' expr_list ')' opt_partition_by
  4838    {
  4839      $$.val = tree.ListPartition{
  4840        Name: tree.UnrestrictedName($1),
  4841        Exprs: $5.exprs(),
  4842        Subpartition: $7.partitionBy(),
  4843      }
  4844    }
  4845  
  4846  range_partitions:
  4847    range_partition
  4848    {
  4849      $$.val = []tree.RangePartition{$1.rangePartition()}
  4850    }
  4851  | range_partitions ',' range_partition
  4852    {
  4853      $$.val = append($1.rangePartitions(), $3.rangePartition())
  4854    }
  4855  
  4856  range_partition:
  4857    partition VALUES FROM '(' expr_list ')' TO '(' expr_list ')' opt_partition_by
  4858    {
  4859      $$.val = tree.RangePartition{
  4860        Name: tree.UnrestrictedName($1),
  4861        From: $5.exprs(),
  4862        To: $9.exprs(),
  4863        Subpartition: $11.partitionBy(),
  4864      }
  4865    }
  4866  
  4867  // Treat SERIAL pseudo-types as separate case so that types.T does not have to
  4868  // support them as first-class types (e.g. they should not be supported as CAST
  4869  // target types).
  4870  column_def:
  4871    column_name typename col_qual_list
  4872    {
  4873      typ := $2.typeReference()
  4874      tableDef, err := tree.NewColumnTableDef(tree.Name($1), typ, tree.IsReferenceSerialType(typ), $3.colQuals())
  4875      if err != nil {
  4876        return setErr(sqllex, err)
  4877      }
  4878      $$.val = tableDef
  4879    }
  4880  
  4881  col_qual_list:
  4882    col_qual_list col_qualification
  4883    {
  4884      $$.val = append($1.colQuals(), $2.colQual())
  4885    }
  4886  | /* EMPTY */
  4887    {
  4888      $$.val = []tree.NamedColumnQualification(nil)
  4889    }
  4890  
  4891  col_qualification:
  4892    CONSTRAINT constraint_name col_qualification_elem
  4893    {
  4894      $$.val = tree.NamedColumnQualification{Name: tree.Name($2), Qualification: $3.colQualElem()}
  4895    }
  4896  | col_qualification_elem
  4897    {
  4898      $$.val = tree.NamedColumnQualification{Qualification: $1.colQualElem()}
  4899    }
  4900  | COLLATE collation_name
  4901    {
  4902      $$.val = tree.NamedColumnQualification{Qualification: tree.ColumnCollation($2)}
  4903    }
  4904  | FAMILY family_name
  4905    {
  4906      $$.val = tree.NamedColumnQualification{Qualification: &tree.ColumnFamilyConstraint{Family: tree.Name($2)}}
  4907    }
  4908  | CREATE FAMILY family_name
  4909    {
  4910      $$.val = tree.NamedColumnQualification{Qualification: &tree.ColumnFamilyConstraint{Family: tree.Name($3), Create: true}}
  4911    }
  4912  | CREATE FAMILY
  4913    {
  4914      $$.val = tree.NamedColumnQualification{Qualification: &tree.ColumnFamilyConstraint{Create: true}}
  4915    }
  4916  | CREATE IF NOT EXISTS FAMILY family_name
  4917    {
  4918      $$.val = tree.NamedColumnQualification{Qualification: &tree.ColumnFamilyConstraint{Family: tree.Name($6), Create: true, IfNotExists: true}}
  4919    }
  4920  
  4921  // DEFAULT NULL is already the default for Postgres. But define it here and
  4922  // carry it forward into the system to make it explicit.
  4923  // - thomas 1998-09-13
  4924  //
  4925  // WITH NULL and NULL are not SQL-standard syntax elements, so leave them
  4926  // out. Use DEFAULT NULL to explicitly indicate that a column may have that
  4927  // value. WITH NULL leads to shift/reduce conflicts with WITH TIME ZONE anyway.
  4928  // - thomas 1999-01-08
  4929  //
  4930  // DEFAULT expression must be b_expr not a_expr to prevent shift/reduce
  4931  // conflict on NOT (since NOT might start a subsequent NOT NULL constraint, or
  4932  // be part of a_expr NOT LIKE or similar constructs).
  4933  col_qualification_elem:
  4934    NOT NULL
  4935    {
  4936      $$.val = tree.NotNullConstraint{}
  4937    }
  4938  | NULL
  4939    {
  4940      $$.val = tree.NullConstraint{}
  4941    }
  4942  | UNIQUE
  4943    {
  4944      $$.val = tree.UniqueConstraint{}
  4945    }
  4946  | PRIMARY KEY
  4947    {
  4948      $$.val = tree.PrimaryKeyConstraint{}
  4949    }
  4950  | PRIMARY KEY USING HASH WITH BUCKET_COUNT '=' a_expr
  4951  {
  4952    $$.val = tree.ShardedPrimaryKeyConstraint{
  4953      Sharded: true,
  4954      ShardBuckets: $8.expr(),
  4955    }
  4956  }
  4957  | CHECK '(' a_expr ')'
  4958    {
  4959      $$.val = &tree.ColumnCheckConstraint{Expr: $3.expr()}
  4960    }
  4961  | DEFAULT b_expr
  4962    {
  4963      $$.val = &tree.ColumnDefault{Expr: $2.expr()}
  4964    }
  4965  | REFERENCES table_name opt_name_parens key_match reference_actions
  4966   {
  4967      name := $2.unresolvedObjectName().ToTableName()
  4968      $$.val = &tree.ColumnFKConstraint{
  4969        Table: name,
  4970        Col: tree.Name($3),
  4971        Actions: $5.referenceActions(),
  4972        Match: $4.compositeKeyMatchMethod(),
  4973      }
  4974   }
  4975  | generated_as '(' a_expr ')' STORED
  4976   {
  4977      $$.val = &tree.ColumnComputedDef{Expr: $3.expr()}
  4978   }
  4979  | generated_as '(' a_expr ')' VIRTUAL
  4980   {
  4981      return unimplemented(sqllex, "virtual computed columns")
  4982   }
  4983  | generated_as error
  4984   {
  4985      sqllex.Error("use AS ( <expr> ) STORED")
  4986      return 1
  4987   }
  4988  
  4989  // GENERATED ALWAYS is a noise word for compatibility with Postgres.
  4990  generated_as:
  4991    AS {}
  4992  | GENERATED_ALWAYS ALWAYS AS {}
  4993  
  4994  
  4995  index_def:
  4996    INDEX opt_index_name '(' index_params ')' opt_hash_sharded opt_storing opt_interleave opt_partition_by opt_where_clause
  4997    {
  4998      $$.val = &tree.IndexTableDef{
  4999        Name:    tree.Name($2),
  5000        Columns: $4.idxElems(),
  5001        Sharded: $6.shardedIndexDef(),
  5002        Storing: $7.nameList(),
  5003        Interleave: $8.interleave(),
  5004        PartitionBy: $9.partitionBy(),
  5005        Predicate: $10.expr(),
  5006      }
  5007    }
  5008  | UNIQUE INDEX opt_index_name '(' index_params ')' opt_hash_sharded opt_storing opt_interleave opt_partition_by opt_where_clause
  5009    {
  5010      $$.val = &tree.UniqueConstraintTableDef{
  5011        IndexTableDef: tree.IndexTableDef {
  5012          Name:    tree.Name($3),
  5013          Columns: $5.idxElems(),
  5014          Sharded: $7.shardedIndexDef(),
  5015          Storing: $8.nameList(),
  5016          Interleave: $9.interleave(),
  5017          PartitionBy: $10.partitionBy(),
  5018          Predicate: $11.expr(),
  5019        },
  5020      }
  5021    }
  5022  | INVERTED INDEX opt_name '(' index_params ')' opt_where_clause
  5023    {
  5024      $$.val = &tree.IndexTableDef{
  5025        Name:    tree.Name($3),
  5026        Columns: $5.idxElems(),
  5027        Inverted: true,
  5028        Predicate: $7.expr(),
  5029      }
  5030    }
  5031  
  5032  family_def:
  5033    FAMILY opt_family_name '(' name_list ')'
  5034    {
  5035      $$.val = &tree.FamilyTableDef{
  5036        Name: tree.Name($2),
  5037        Columns: $4.nameList(),
  5038      }
  5039    }
  5040  
  5041  // constraint_elem specifies constraint syntax which is not embedded into a
  5042  // column definition. col_qualification_elem specifies the embedded form.
  5043  // - thomas 1997-12-03
  5044  table_constraint:
  5045    CONSTRAINT constraint_name constraint_elem
  5046    {
  5047      $$.val = $3.constraintDef()
  5048      $$.val.(tree.ConstraintTableDef).SetName(tree.Name($2))
  5049    }
  5050  | constraint_elem
  5051    {
  5052      $$.val = $1.constraintDef()
  5053    }
  5054  
  5055  constraint_elem:
  5056    CHECK '(' a_expr ')' opt_deferrable
  5057    {
  5058      $$.val = &tree.CheckConstraintTableDef{
  5059        Expr: $3.expr(),
  5060      }
  5061    }
  5062  | UNIQUE '(' index_params ')' opt_storing opt_interleave opt_partition_by opt_deferrable opt_where_clause
  5063    {
  5064      $$.val = &tree.UniqueConstraintTableDef{
  5065        IndexTableDef: tree.IndexTableDef{
  5066          Columns: $3.idxElems(),
  5067          Storing: $5.nameList(),
  5068          Interleave: $6.interleave(),
  5069          PartitionBy: $7.partitionBy(),
  5070          Predicate: $9.expr(),
  5071        },
  5072      }
  5073    }
  5074  | PRIMARY KEY '(' index_params ')' opt_hash_sharded opt_interleave
  5075    {
  5076      $$.val = &tree.UniqueConstraintTableDef{
  5077        IndexTableDef: tree.IndexTableDef{
  5078          Columns: $4.idxElems(),
  5079          Sharded: $6.shardedIndexDef(),
  5080          Interleave: $7.interleave(),
  5081        },
  5082        PrimaryKey: true,
  5083      }
  5084    }
  5085  | FOREIGN KEY '(' name_list ')' REFERENCES table_name
  5086      opt_column_list key_match reference_actions opt_deferrable
  5087    {
  5088      name := $7.unresolvedObjectName().ToTableName()
  5089      $$.val = &tree.ForeignKeyConstraintTableDef{
  5090        Table: name,
  5091        FromCols: $4.nameList(),
  5092        ToCols: $8.nameList(),
  5093        Match: $9.compositeKeyMatchMethod(),
  5094        Actions: $10.referenceActions(),
  5095      }
  5096    }
  5097  | EXCLUDE USING error
  5098    {
  5099      return unimplementedWithIssueDetail(sqllex, 46657, "add constraint exclude using")
  5100    }
  5101  
  5102  
  5103  create_as_opt_col_list:
  5104    '(' create_as_table_defs ')'
  5105    {
  5106      $$.val = $2.val
  5107    }
  5108  | /* EMPTY */
  5109    {
  5110      $$.val = tree.TableDefs(nil)
  5111    }
  5112  
  5113  create_as_table_defs:
  5114    column_name create_as_col_qual_list
  5115    {
  5116      tableDef, err := tree.NewColumnTableDef(tree.Name($1), nil, false, $2.colQuals())
  5117      if err != nil {
  5118        return setErr(sqllex, err)
  5119      }
  5120  
  5121      var colToTableDef tree.TableDef = tableDef
  5122      $$.val = tree.TableDefs{colToTableDef}
  5123    }
  5124  | create_as_table_defs ',' column_name create_as_col_qual_list
  5125    {
  5126      tableDef, err := tree.NewColumnTableDef(tree.Name($3), nil, false, $4.colQuals())
  5127      if err != nil {
  5128        return setErr(sqllex, err)
  5129      }
  5130  
  5131      var colToTableDef tree.TableDef = tableDef
  5132  
  5133      $$.val = append($1.tblDefs(), colToTableDef)
  5134    }
  5135  | create_as_table_defs ',' family_def
  5136    {
  5137      $$.val = append($1.tblDefs(), $3.tblDef())
  5138    }
  5139  | create_as_table_defs ',' create_as_constraint_def
  5140  {
  5141    var constraintToTableDef tree.TableDef = $3.constraintDef()
  5142    $$.val = append($1.tblDefs(), constraintToTableDef)
  5143  }
  5144  
  5145  create_as_constraint_def:
  5146    create_as_constraint_elem
  5147    {
  5148      $$.val = $1.constraintDef()
  5149    }
  5150  
  5151  create_as_constraint_elem:
  5152    PRIMARY KEY '(' create_as_params ')'
  5153    {
  5154      $$.val = &tree.UniqueConstraintTableDef{
  5155        IndexTableDef: tree.IndexTableDef{
  5156          Columns: $4.idxElems(),
  5157        },
  5158        PrimaryKey:    true,
  5159      }
  5160    }
  5161  
  5162  create_as_params:
  5163    create_as_param
  5164    {
  5165      $$.val = tree.IndexElemList{$1.idxElem()}
  5166    }
  5167  | create_as_params ',' create_as_param
  5168    {
  5169      $$.val = append($1.idxElems(), $3.idxElem())
  5170    }
  5171  
  5172  create_as_param:
  5173    column_name
  5174    {
  5175      $$.val = tree.IndexElem{Column: tree.Name($1)}
  5176    }
  5177  
  5178  create_as_col_qual_list:
  5179    create_as_col_qual_list create_as_col_qualification
  5180    {
  5181      $$.val = append($1.colQuals(), $2.colQual())
  5182    }
  5183  | /* EMPTY */
  5184    {
  5185      $$.val = []tree.NamedColumnQualification(nil)
  5186    }
  5187  
  5188  create_as_col_qualification:
  5189    create_as_col_qualification_elem
  5190    {
  5191      $$.val = tree.NamedColumnQualification{Qualification: $1.colQualElem()}
  5192    }
  5193  | FAMILY family_name
  5194    {
  5195      $$.val = tree.NamedColumnQualification{Qualification: &tree.ColumnFamilyConstraint{Family: tree.Name($2)}}
  5196    }
  5197  
  5198  create_as_col_qualification_elem:
  5199    PRIMARY KEY
  5200    {
  5201      $$.val = tree.PrimaryKeyConstraint{}
  5202    }
  5203  
  5204  opt_deferrable:
  5205    /* EMPTY */ { /* no error */ }
  5206  | DEFERRABLE { return unimplementedWithIssueDetail(sqllex, 31632, "deferrable") }
  5207  | DEFERRABLE INITIALLY DEFERRED { return unimplementedWithIssueDetail(sqllex, 31632, "def initially deferred") }
  5208  | DEFERRABLE INITIALLY IMMEDIATE { return unimplementedWithIssueDetail(sqllex, 31632, "def initially immediate") }
  5209  | INITIALLY DEFERRED { return unimplementedWithIssueDetail(sqllex, 31632, "initially deferred") }
  5210  | INITIALLY IMMEDIATE { return unimplementedWithIssueDetail(sqllex, 31632, "initially immediate") }
  5211  
  5212  storing:
  5213    COVERING
  5214  | STORING
  5215  | INCLUDE
  5216  
  5217  // TODO(pmattis): It would be nice to support a syntax like STORING
  5218  // ALL or STORING (*). The syntax addition is straightforward, but we
  5219  // need to be careful with the rest of the implementation. In
  5220  // particular, columns stored at indexes are currently encoded in such
  5221  // a way that adding a new column would require rewriting the existing
  5222  // index values. We will need to change the storage format so that it
  5223  // is a list of <columnID, value> pairs which will allow both adding
  5224  // and dropping columns without rewriting indexes that are storing the
  5225  // adjusted column.
  5226  opt_storing:
  5227    storing '(' name_list ')'
  5228    {
  5229      $$.val = $3.nameList()
  5230    }
  5231  | /* EMPTY */
  5232    {
  5233      $$.val = tree.NameList(nil)
  5234    }
  5235  
  5236  opt_hash_sharded:
  5237    USING HASH WITH BUCKET_COUNT '=' a_expr
  5238    {
  5239      $$.val = &tree.ShardedIndexDef{
  5240        ShardBuckets: $6.expr(),
  5241      }
  5242    }
  5243    | /* EMPTY */
  5244    {
  5245      $$.val = (*tree.ShardedIndexDef)(nil)
  5246    }
  5247  
  5248  opt_column_list:
  5249    '(' name_list ')'
  5250    {
  5251      $$.val = $2.nameList()
  5252    }
  5253  | /* EMPTY */
  5254    {
  5255      $$.val = tree.NameList(nil)
  5256    }
  5257  
  5258  // https://www.postgresql.org/docs/10/sql-createtable.html
  5259  //
  5260  // "A value inserted into the referencing column(s) is matched against
  5261  // the values of the referenced table and referenced columns using the
  5262  // given match type. There are three match types: MATCH FULL, MATCH
  5263  // PARTIAL, and MATCH SIMPLE (which is the default). MATCH FULL will
  5264  // not allow one column of a multicolumn foreign key to be null unless
  5265  // all foreign key columns are null; if they are all null, the row is
  5266  // not required to have a match in the referenced table. MATCH SIMPLE
  5267  // allows any of the foreign key columns to be null; if any of them
  5268  // are null, the row is not required to have a match in the referenced
  5269  // table. MATCH PARTIAL is not yet implemented. (Of course, NOT NULL
  5270  // constraints can be applied to the referencing column(s) to prevent
  5271  // these cases from arising.)"
  5272  key_match:
  5273    MATCH SIMPLE
  5274    {
  5275      $$.val = tree.MatchSimple
  5276    }
  5277  | MATCH FULL
  5278    {
  5279      $$.val = tree.MatchFull
  5280    }
  5281  | MATCH PARTIAL
  5282    {
  5283      return unimplementedWithIssueDetail(sqllex, 20305, "match partial")
  5284    }
  5285  | /* EMPTY */
  5286    {
  5287      $$.val = tree.MatchSimple
  5288    }
  5289  
  5290  // We combine the update and delete actions into one value temporarily for
  5291  // simplicity of parsing, and then break them down again in the calling
  5292  // production.
  5293  reference_actions:
  5294    reference_on_update
  5295    {
  5296       $$.val = tree.ReferenceActions{Update: $1.referenceAction()}
  5297    }
  5298  | reference_on_delete
  5299    {
  5300       $$.val = tree.ReferenceActions{Delete: $1.referenceAction()}
  5301    }
  5302  | reference_on_update reference_on_delete
  5303    {
  5304      $$.val = tree.ReferenceActions{Update: $1.referenceAction(), Delete: $2.referenceAction()}
  5305    }
  5306  | reference_on_delete reference_on_update
  5307    {
  5308      $$.val = tree.ReferenceActions{Delete: $1.referenceAction(), Update: $2.referenceAction()}
  5309    }
  5310  | /* EMPTY */
  5311    {
  5312      $$.val = tree.ReferenceActions{}
  5313    }
  5314  
  5315  reference_on_update:
  5316    ON UPDATE reference_action
  5317    {
  5318      $$.val = $3.referenceAction()
  5319    }
  5320  
  5321  reference_on_delete:
  5322    ON DELETE reference_action
  5323    {
  5324      $$.val = $3.referenceAction()
  5325    }
  5326  
  5327  reference_action:
  5328  // NO ACTION is currently the default behavior. It is functionally the same as
  5329  // RESTRICT.
  5330    NO ACTION
  5331    {
  5332      $$.val = tree.NoAction
  5333    }
  5334  | RESTRICT
  5335    {
  5336      $$.val = tree.Restrict
  5337    }
  5338  | CASCADE
  5339    {
  5340      $$.val = tree.Cascade
  5341    }
  5342  | SET NULL
  5343    {
  5344      $$.val = tree.SetNull
  5345    }
  5346  | SET DEFAULT
  5347    {
  5348      $$.val = tree.SetDefault
  5349    }
  5350  
  5351  // %Help: CREATE SEQUENCE - create a new sequence
  5352  // %Category: DDL
  5353  // %Text:
  5354  // CREATE [TEMPORARY | TEMP] SEQUENCE <seqname>
  5355  //   [INCREMENT <increment>]
  5356  //   [MINVALUE <minvalue> | NO MINVALUE]
  5357  //   [MAXVALUE <maxvalue> | NO MAXVALUE]
  5358  //   [START [WITH] <start>]
  5359  //   [CACHE <cache>]
  5360  //   [NO CYCLE]
  5361  //   [VIRTUAL]
  5362  //
  5363  // %SeeAlso: CREATE TABLE
  5364  create_sequence_stmt:
  5365    CREATE opt_temp SEQUENCE sequence_name opt_sequence_option_list
  5366    {
  5367      name := $4.unresolvedObjectName().ToTableName()
  5368      $$.val = &tree.CreateSequence {
  5369        Name: name,
  5370        Temporary: $2.persistenceType(),
  5371        Options: $5.seqOpts(),
  5372      }
  5373    }
  5374  | CREATE opt_temp SEQUENCE IF NOT EXISTS sequence_name opt_sequence_option_list
  5375    {
  5376      name := $7.unresolvedObjectName().ToTableName()
  5377      $$.val = &tree.CreateSequence {
  5378        Name: name, Options: $8.seqOpts(),
  5379        Temporary: $2.persistenceType(),
  5380        IfNotExists: true,
  5381      }
  5382    }
  5383  | CREATE opt_temp SEQUENCE error // SHOW HELP: CREATE SEQUENCE
  5384  
  5385  opt_sequence_option_list:
  5386    sequence_option_list
  5387  | /* EMPTY */          { $$.val = []tree.SequenceOption(nil) }
  5388  
  5389  sequence_option_list:
  5390    sequence_option_elem                       { $$.val = []tree.SequenceOption{$1.seqOpt()} }
  5391  | sequence_option_list sequence_option_elem  { $$.val = append($1.seqOpts(), $2.seqOpt()) }
  5392  
  5393  sequence_option_elem:
  5394    AS typename                  { return unimplementedWithIssueDetail(sqllex, 25110, $2.typeReference().SQLString()) }
  5395  | CYCLE                        { /* SKIP DOC */
  5396                                   $$.val = tree.SequenceOption{Name: tree.SeqOptCycle} }
  5397  | NO CYCLE                     { $$.val = tree.SequenceOption{Name: tree.SeqOptNoCycle} }
  5398  | OWNED BY NONE                { $$.val = tree.SequenceOption{Name: tree.SeqOptOwnedBy, ColumnItemVal: nil} }
  5399  | OWNED BY column_path         { varName, err := $3.unresolvedName().NormalizeVarName()
  5400                                       if err != nil {
  5401                                         return setErr(sqllex, err)
  5402                                       }
  5403                                       columnItem, ok := varName.(*tree.ColumnItem)
  5404                                       if !ok {
  5405                                         sqllex.Error(fmt.Sprintf("invalid column name: %q", tree.ErrString($3.unresolvedName())))
  5406                                               return 1
  5407                                       }
  5408                                   $$.val = tree.SequenceOption{Name: tree.SeqOptOwnedBy, ColumnItemVal: columnItem} }
  5409  | CACHE signed_iconst64        { /* SKIP DOC */
  5410                                   x := $2.int64()
  5411                                   $$.val = tree.SequenceOption{Name: tree.SeqOptCache, IntVal: &x} }
  5412  | INCREMENT signed_iconst64    { x := $2.int64()
  5413                                   $$.val = tree.SequenceOption{Name: tree.SeqOptIncrement, IntVal: &x} }
  5414  | INCREMENT BY signed_iconst64 { x := $3.int64()
  5415                                   $$.val = tree.SequenceOption{Name: tree.SeqOptIncrement, IntVal: &x, OptionalWord: true} }
  5416  | MINVALUE signed_iconst64     { x := $2.int64()
  5417                                   $$.val = tree.SequenceOption{Name: tree.SeqOptMinValue, IntVal: &x} }
  5418  | NO MINVALUE                  { $$.val = tree.SequenceOption{Name: tree.SeqOptMinValue} }
  5419  | MAXVALUE signed_iconst64     { x := $2.int64()
  5420                                   $$.val = tree.SequenceOption{Name: tree.SeqOptMaxValue, IntVal: &x} }
  5421  | NO MAXVALUE                  { $$.val = tree.SequenceOption{Name: tree.SeqOptMaxValue} }
  5422  | START signed_iconst64        { x := $2.int64()
  5423                                   $$.val = tree.SequenceOption{Name: tree.SeqOptStart, IntVal: &x} }
  5424  | START WITH signed_iconst64   { x := $3.int64()
  5425                                   $$.val = tree.SequenceOption{Name: tree.SeqOptStart, IntVal: &x, OptionalWord: true} }
  5426  | VIRTUAL                      { $$.val = tree.SequenceOption{Name: tree.SeqOptVirtual} }
  5427  
  5428  // %Help: TRUNCATE - empty one or more tables
  5429  // %Category: DML
  5430  // %Text: TRUNCATE [TABLE] <tablename> [, ...] [CASCADE | RESTRICT]
  5431  // %SeeAlso: WEBDOCS/truncate.html
  5432  truncate_stmt:
  5433    TRUNCATE opt_table relation_expr_list opt_drop_behavior
  5434    {
  5435      $$.val = &tree.Truncate{Tables: $3.tableNames(), DropBehavior: $4.dropBehavior()}
  5436    }
  5437  | TRUNCATE error // SHOW HELP: TRUNCATE
  5438  
  5439  password_clause:
  5440    PASSWORD string_or_placeholder
  5441    {
  5442      $$.val = tree.KVOption{Key: tree.Name($1), Value: $2.expr()}
  5443    }
  5444  | PASSWORD NULL
  5445    {
  5446      $$.val = tree.KVOption{Key: tree.Name($1), Value: tree.DNull}
  5447    }
  5448  
  5449  // %Help: CREATE ROLE - define a new role
  5450  // %Category: Priv
  5451  // %Text: CREATE ROLE [IF NOT EXISTS] <name> [ [WITH] <OPTIONS...> ]
  5452  // %SeeAlso: ALTER ROLE, DROP ROLE, SHOW ROLES
  5453  create_role_stmt:
  5454    CREATE role_or_group_or_user string_or_placeholder opt_role_options
  5455    {
  5456      $$.val = &tree.CreateRole{Name: $3.expr(), KVOptions: $4.kvOptions(), IsRole: $2.bool()}
  5457    }
  5458  | CREATE role_or_group_or_user IF NOT EXISTS string_or_placeholder opt_role_options
  5459    {
  5460      $$.val = &tree.CreateRole{Name: $6.expr(), IfNotExists: true, KVOptions: $7.kvOptions(), IsRole: $2.bool()}
  5461    }
  5462  | CREATE role_or_group_or_user error // SHOW HELP: CREATE ROLE
  5463  
  5464  // %Help: ALTER ROLE - alter a role
  5465  // %Category: Priv
  5466  // %Text: ALTER ROLE <name> [WITH] <options...>
  5467  // %SeeAlso: CREATE ROLE, DROP ROLE, SHOW ROLES
  5468  alter_role_stmt:
  5469    ALTER role_or_group_or_user string_or_placeholder opt_role_options
  5470  {
  5471    $$.val = &tree.AlterRole{Name: $3.expr(), KVOptions: $4.kvOptions(), IsRole: $2.bool()}
  5472  }
  5473  | ALTER role_or_group_or_user IF EXISTS string_or_placeholder opt_role_options
  5474  {
  5475    $$.val = &tree.AlterRole{Name: $5.expr(), IfExists: true, KVOptions: $6.kvOptions(), IsRole: $2.bool()}
  5476  }
  5477  | ALTER role_or_group_or_user error // SHOW HELP: ALTER ROLE
  5478  
  5479  // "CREATE GROUP is now an alias for CREATE ROLE"
  5480  // https://www.postgresql.org/docs/10/static/sql-creategroup.html
  5481  role_or_group_or_user:
  5482    ROLE
  5483    {
  5484      $$.val = true
  5485    }
  5486  | GROUP
  5487    {
  5488      /* SKIP DOC */
  5489      $$.val = true
  5490    }
  5491  | USER
  5492    {
  5493      $$.val = false
  5494    }
  5495  
  5496  // %Help: CREATE VIEW - create a new view
  5497  // %Category: DDL
  5498  // %Text: CREATE [TEMPORARY | TEMP] VIEW <viewname> [( <colnames...> )] AS <source>
  5499  // %SeeAlso: CREATE TABLE, SHOW CREATE, WEBDOCS/create-view.html
  5500  create_view_stmt:
  5501    CREATE opt_temp opt_view_recursive VIEW view_name opt_column_list AS select_stmt
  5502    {
  5503      name := $5.unresolvedObjectName().ToTableName()
  5504      $$.val = &tree.CreateView{
  5505        Name: name,
  5506        ColumnNames: $6.nameList(),
  5507        AsSource: $8.slct(),
  5508        Temporary: $2.persistenceType(),
  5509        IfNotExists: false,
  5510        Replace: false,
  5511      }
  5512    }
  5513  // We cannot use a rule like opt_or_replace here as that would cause a conflict
  5514  // with the opt_temp rule.
  5515  | CREATE OR REPLACE opt_temp opt_view_recursive VIEW view_name opt_column_list AS select_stmt
  5516    {
  5517      name := $7.unresolvedObjectName().ToTableName()
  5518      $$.val = &tree.CreateView{
  5519        Name: name,
  5520        ColumnNames: $8.nameList(),
  5521        AsSource: $10.slct(),
  5522        Temporary: $4.persistenceType(),
  5523        IfNotExists: false,
  5524        Replace: true,
  5525      }
  5526    }
  5527  | CREATE opt_temp opt_view_recursive VIEW IF NOT EXISTS view_name opt_column_list AS select_stmt
  5528    {
  5529      name := $8.unresolvedObjectName().ToTableName()
  5530      $$.val = &tree.CreateView{
  5531        Name: name,
  5532        ColumnNames: $9.nameList(),
  5533        AsSource: $11.slct(),
  5534        Temporary: $2.persistenceType(),
  5535        IfNotExists: true,
  5536        Replace: false,
  5537      }
  5538    }
  5539  | CREATE opt_temp opt_view_recursive VIEW error // SHOW HELP: CREATE VIEW
  5540  
  5541  role_option:
  5542    CREATEROLE
  5543    {
  5544      $$.val = tree.KVOption{Key: tree.Name($1), Value: nil}
  5545    }
  5546  | NOCREATEROLE
  5547  	{
  5548  		$$.val = tree.KVOption{Key: tree.Name($1), Value: nil}
  5549  	}
  5550  | LOGIN
  5551  	{
  5552  		$$.val = tree.KVOption{Key: tree.Name($1), Value: nil}
  5553  	}
  5554  | NOLOGIN
  5555  	{
  5556  		$$.val = tree.KVOption{Key: tree.Name($1), Value: nil}
  5557  	}
  5558  | password_clause
  5559  | valid_until_clause
  5560  
  5561  role_options:
  5562    role_option
  5563    {
  5564      $$.val = []tree.KVOption{$1.kvOption()}
  5565    }
  5566  |  role_options role_option
  5567    {
  5568      $$.val = append($1.kvOptions(), $2.kvOption())
  5569    }
  5570  
  5571  opt_role_options:
  5572  	opt_with role_options
  5573  	{
  5574  		$$.val = $2.kvOptions()
  5575  	}
  5576  | /* EMPTY */
  5577  	{
  5578  		$$.val = nil
  5579  	}
  5580  
  5581  valid_until_clause:
  5582    VALID UNTIL string_or_placeholder
  5583    {
  5584  		$$.val = tree.KVOption{Key: tree.Name(fmt.Sprintf("%s_%s",$1, $2)), Value: $3.expr()}
  5585    }
  5586  | VALID UNTIL NULL
  5587    {
  5588  		$$.val = tree.KVOption{Key: tree.Name(fmt.Sprintf("%s_%s",$1, $2)), Value: tree.DNull}
  5589  	}
  5590  
  5591  opt_view_recursive:
  5592    /* EMPTY */ { /* no error */ }
  5593  | RECURSIVE { return unimplemented(sqllex, "create recursive view") }
  5594  
  5595  
  5596  // %Help: CREATE TYPE -- create a type
  5597  // %Category: DDL
  5598  // %Text: CREATE TYPE <type_name> AS ENUM (...)
  5599  // %SeeAlso: WEBDOCS/create-type.html
  5600  create_type_stmt:
  5601    // Enum types.
  5602    CREATE TYPE type_name AS ENUM '(' opt_enum_val_list ')'
  5603    {
  5604      $$.val = &tree.CreateType{
  5605        TypeName: $3.unresolvedObjectName(),
  5606        Variety: tree.Enum,
  5607        EnumLabels: $7.strs(),
  5608      }
  5609    }
  5610  | CREATE TYPE error // SHOW HELP: CREATE TYPE
  5611    // Record/Composite types.
  5612  | CREATE TYPE type_name AS '(' error      { return unimplementedWithIssue(sqllex, 27792) }
  5613    // Range types.
  5614  | CREATE TYPE type_name AS RANGE error    { return unimplementedWithIssue(sqllex, 27791) }
  5615    // Base (primitive) types.
  5616  | CREATE TYPE type_name '(' error         { return unimplementedWithIssueDetail(sqllex, 27793, "base") }
  5617    // Shell types, gateway to define base types using the previous syntax.
  5618  | CREATE TYPE type_name                   { return unimplementedWithIssueDetail(sqllex, 27793, "shell") }
  5619    // Domain types.
  5620  | CREATE DOMAIN type_name error           { return unimplementedWithIssueDetail(sqllex, 27796, "create") }
  5621  
  5622  opt_enum_val_list:
  5623    enum_val_list
  5624    {
  5625      $$.val = $1.strs()
  5626    }
  5627  | /* EMPTY */
  5628    {
  5629      $$.val = []string(nil)
  5630    }
  5631  
  5632  enum_val_list:
  5633    SCONST
  5634    {
  5635      $$.val = []string{$1}
  5636    }
  5637  | enum_val_list ',' SCONST
  5638    {
  5639      $$.val = append($1.strs(), $3)
  5640    }
  5641  
  5642  // %Help: CREATE INDEX - create a new index
  5643  // %Category: DDL
  5644  // %Text:
  5645  // CREATE [UNIQUE | INVERTED] INDEX [CONCURRENTLY] [IF NOT EXISTS] [<idxname>]
  5646  //        ON <tablename> ( <colname> [ASC | DESC] [, ...] )
  5647  //        [USING HASH WITH BUCKET_COUNT = <shard_buckets>] [STORING ( <colnames...> )] [<interleave>]
  5648  //
  5649  // Interleave clause:
  5650  //    INTERLEAVE IN PARENT <tablename> ( <colnames...> ) [CASCADE | RESTRICT]
  5651  //
  5652  // %SeeAlso: CREATE TABLE, SHOW INDEXES, SHOW CREATE,
  5653  // WEBDOCS/create-index.html
  5654  create_index_stmt:
  5655    CREATE opt_unique INDEX opt_concurrently opt_index_name ON table_name opt_using_gin_btree '(' index_params ')' opt_hash_sharded opt_storing opt_interleave opt_partition_by opt_where_clause
  5656    {
  5657      table := $7.unresolvedObjectName().ToTableName()
  5658      $$.val = &tree.CreateIndex{
  5659        Name:    tree.Name($5),
  5660        Table:   table,
  5661        Unique:  $2.bool(),
  5662        Columns: $10.idxElems(),
  5663        Sharded: $12.shardedIndexDef(),
  5664        Storing: $13.nameList(),
  5665        Interleave: $14.interleave(),
  5666        PartitionBy: $15.partitionBy(),
  5667        Predicate: $16.expr(),
  5668        Inverted: $8.bool(),
  5669        Concurrently: $4.bool(),
  5670      }
  5671    }
  5672  | CREATE opt_unique INDEX opt_concurrently IF NOT EXISTS index_name ON table_name opt_using_gin_btree '(' index_params ')' opt_hash_sharded opt_storing opt_interleave opt_partition_by opt_where_clause
  5673    {
  5674      table := $10.unresolvedObjectName().ToTableName()
  5675      $$.val = &tree.CreateIndex{
  5676        Name:        tree.Name($8),
  5677        Table:       table,
  5678        Unique:      $2.bool(),
  5679        IfNotExists: true,
  5680        Columns:     $13.idxElems(),
  5681        Sharded:     $15.shardedIndexDef(),
  5682        Storing:     $16.nameList(),
  5683        Interleave:  $17.interleave(),
  5684        PartitionBy: $18.partitionBy(),
  5685        Inverted:    $11.bool(),
  5686        Predicate:   $19.expr(),
  5687        Concurrently: $4.bool(),
  5688      }
  5689    }
  5690  | CREATE opt_unique INVERTED INDEX opt_concurrently opt_index_name ON table_name '(' index_params ')' opt_storing opt_interleave opt_partition_by opt_where_clause
  5691    {
  5692      table := $8.unresolvedObjectName().ToTableName()
  5693      $$.val = &tree.CreateIndex{
  5694        Name:       tree.Name($6),
  5695        Table:      table,
  5696        Unique:     $2.bool(),
  5697        Inverted:   true,
  5698        Columns:    $10.idxElems(),
  5699        Storing:     $12.nameList(),
  5700        Interleave:  $13.interleave(),
  5701        PartitionBy: $14.partitionBy(),
  5702        Predicate:   $15.expr(),
  5703        Concurrently: $5.bool(),
  5704      }
  5705    }
  5706  | CREATE opt_unique INVERTED INDEX opt_concurrently IF NOT EXISTS index_name ON table_name '(' index_params ')' opt_storing opt_interleave opt_partition_by opt_where_clause
  5707    {
  5708      table := $11.unresolvedObjectName().ToTableName()
  5709      $$.val = &tree.CreateIndex{
  5710        Name:        tree.Name($9),
  5711        Table:       table,
  5712        Unique:      $2.bool(),
  5713        Inverted:    true,
  5714        IfNotExists: true,
  5715        Columns:     $13.idxElems(),
  5716        Storing:     $15.nameList(),
  5717        Interleave:  $16.interleave(),
  5718        PartitionBy: $17.partitionBy(),
  5719        Predicate:   $18.expr(),
  5720        Concurrently: $5.bool(),
  5721      }
  5722    }
  5723  | CREATE opt_unique INDEX error // SHOW HELP: CREATE INDEX
  5724  
  5725  opt_using_gin_btree:
  5726    USING name
  5727    {
  5728      /* FORCE DOC */
  5729      switch $2 {
  5730        case "gin":
  5731          $$.val = true
  5732        case "btree":
  5733          $$.val = false
  5734        case "hash", "gist", "spgist", "brin":
  5735          return unimplemented(sqllex, "index using " + $2)
  5736        default:
  5737          sqllex.Error("unrecognized access method: " + $2)
  5738          return 1
  5739      }
  5740    }
  5741  | /* EMPTY */
  5742    {
  5743      $$.val = false
  5744    }
  5745  
  5746  opt_concurrently:
  5747    CONCURRENTLY
  5748    {
  5749      $$.val = true
  5750    }
  5751  | /* EMPTY */
  5752    {
  5753      $$.val = false
  5754    }
  5755  
  5756  opt_unique:
  5757    UNIQUE
  5758    {
  5759      $$.val = true
  5760    }
  5761  | /* EMPTY */
  5762    {
  5763      $$.val = false
  5764    }
  5765  
  5766  index_params:
  5767    index_elem
  5768    {
  5769      $$.val = tree.IndexElemList{$1.idxElem()}
  5770    }
  5771  | index_params ',' index_elem
  5772    {
  5773      $$.val = append($1.idxElems(), $3.idxElem())
  5774    }
  5775  
  5776  // Index attributes can be either simple column references, or arbitrary
  5777  // expressions in parens. For backwards-compatibility reasons, we allow an
  5778  // expression that is just a function call to be written without parens.
  5779  index_elem:
  5780    a_expr opt_asc_desc opt_nulls_order
  5781    {
  5782      /* FORCE DOC */
  5783      e := $1.expr()
  5784      dir := $2.dir()
  5785      nullsOrder := $3.nullsOrder()
  5786      // We currently only support the opposite of Postgres defaults.
  5787      if nullsOrder != tree.DefaultNullsOrder {
  5788        if dir == tree.Descending && nullsOrder == tree.NullsFirst {
  5789          return unimplementedWithIssue(sqllex, 6224)
  5790        }
  5791        if dir != tree.Descending && nullsOrder == tree.NullsLast {
  5792          return unimplementedWithIssue(sqllex, 6224)
  5793        }
  5794      }
  5795      if colName, ok := e.(*tree.UnresolvedName); ok && colName.NumParts == 1 {
  5796        $$.val = tree.IndexElem{Column: tree.Name(colName.Parts[0]), Direction: dir, NullsOrder: nullsOrder}
  5797      } else {
  5798        return unimplementedWithIssueDetail(sqllex, 9682, fmt.Sprintf("%T", e))
  5799      }
  5800    }
  5801  
  5802  opt_collate:
  5803    COLLATE collation_name { $$ = $2 }
  5804  | /* EMPTY */ { $$ = "" }
  5805  
  5806  opt_asc_desc:
  5807    ASC
  5808    {
  5809      $$.val = tree.Ascending
  5810    }
  5811  | DESC
  5812    {
  5813      $$.val = tree.Descending
  5814    }
  5815  | /* EMPTY */
  5816    {
  5817      $$.val = tree.DefaultDirection
  5818    }
  5819  
  5820  alter_rename_database_stmt:
  5821    ALTER DATABASE database_name RENAME TO database_name
  5822    {
  5823      $$.val = &tree.RenameDatabase{Name: tree.Name($3), NewName: tree.Name($6)}
  5824    }
  5825  
  5826  alter_rename_table_stmt:
  5827    ALTER TABLE relation_expr RENAME TO table_name
  5828    {
  5829      name := $3.unresolvedObjectName()
  5830      newName := $6.unresolvedObjectName()
  5831      $$.val = &tree.RenameTable{Name: name, NewName: newName, IfExists: false, IsView: false}
  5832    }
  5833  | ALTER TABLE IF EXISTS relation_expr RENAME TO table_name
  5834    {
  5835      name := $5.unresolvedObjectName()
  5836      newName := $8.unresolvedObjectName()
  5837      $$.val = &tree.RenameTable{Name: name, NewName: newName, IfExists: true, IsView: false}
  5838    }
  5839  
  5840  alter_rename_view_stmt:
  5841    ALTER VIEW relation_expr RENAME TO view_name
  5842    {
  5843      name := $3.unresolvedObjectName()
  5844      newName := $6.unresolvedObjectName()
  5845      $$.val = &tree.RenameTable{Name: name, NewName: newName, IfExists: false, IsView: true}
  5846    }
  5847  | ALTER VIEW IF EXISTS relation_expr RENAME TO view_name
  5848    {
  5849      name := $5.unresolvedObjectName()
  5850      newName := $8.unresolvedObjectName()
  5851      $$.val = &tree.RenameTable{Name: name, NewName: newName, IfExists: true, IsView: true}
  5852    }
  5853  
  5854  alter_rename_sequence_stmt:
  5855    ALTER SEQUENCE relation_expr RENAME TO sequence_name
  5856    {
  5857      name := $3.unresolvedObjectName()
  5858      newName := $6.unresolvedObjectName()
  5859      $$.val = &tree.RenameTable{Name: name, NewName: newName, IfExists: false, IsSequence: true}
  5860    }
  5861  | ALTER SEQUENCE IF EXISTS relation_expr RENAME TO sequence_name
  5862    {
  5863      name := $5.unresolvedObjectName()
  5864      newName := $8.unresolvedObjectName()
  5865      $$.val = &tree.RenameTable{Name: name, NewName: newName, IfExists: true, IsSequence: true}
  5866    }
  5867  
  5868  alter_rename_index_stmt:
  5869    ALTER INDEX table_index_name RENAME TO index_name
  5870    {
  5871      $$.val = &tree.RenameIndex{Index: $3.newTableIndexName(), NewName: tree.UnrestrictedName($6), IfExists: false}
  5872    }
  5873  | ALTER INDEX IF EXISTS table_index_name RENAME TO index_name
  5874    {
  5875      $$.val = &tree.RenameIndex{Index: $5.newTableIndexName(), NewName: tree.UnrestrictedName($8), IfExists: true}
  5876    }
  5877  
  5878  opt_column:
  5879    COLUMN {}
  5880  | /* EMPTY */ {}
  5881  
  5882  opt_set_data:
  5883    SET DATA {}
  5884  | /* EMPTY */ {}
  5885  
  5886  // %Help: RELEASE - complete a sub-transaction
  5887  // %Category: Txn
  5888  // %Text: RELEASE [SAVEPOINT] <savepoint name>
  5889  // %SeeAlso: SAVEPOINT, WEBDOCS/savepoint.html
  5890  release_stmt:
  5891    RELEASE savepoint_name
  5892    {
  5893      $$.val = &tree.ReleaseSavepoint{Savepoint: tree.Name($2)}
  5894    }
  5895  | RELEASE error // SHOW HELP: RELEASE
  5896  
  5897  // %Help: RESUME JOBS - resume background jobs
  5898  // %Category: Misc
  5899  // %Text:
  5900  // RESUME JOBS <selectclause>
  5901  // RESUME JOB <jobid>
  5902  // %SeeAlso: SHOW JOBS, CANCEL JOBS, PAUSE JOBS
  5903  resume_stmt:
  5904    RESUME JOB a_expr
  5905    {
  5906      $$.val = &tree.ControlJobs{
  5907        Jobs: &tree.Select{
  5908          Select: &tree.ValuesClause{Rows: []tree.Exprs{tree.Exprs{$3.expr()}}},
  5909        },
  5910        Command: tree.ResumeJob,
  5911      }
  5912    }
  5913  | RESUME JOBS select_stmt
  5914    {
  5915      $$.val = &tree.ControlJobs{Jobs: $3.slct(), Command: tree.ResumeJob}
  5916    }
  5917  | RESUME error // SHOW HELP: RESUME JOBS
  5918  
  5919  // %Help: SAVEPOINT - start a sub-transaction
  5920  // %Category: Txn
  5921  // %Text: SAVEPOINT <savepoint name>
  5922  // %SeeAlso: RELEASE, WEBDOCS/savepoint.html
  5923  savepoint_stmt:
  5924    SAVEPOINT name
  5925    {
  5926      $$.val = &tree.Savepoint{Name: tree.Name($2)}
  5927    }
  5928  | SAVEPOINT error // SHOW HELP: SAVEPOINT
  5929  
  5930  // BEGIN / START / COMMIT / END / ROLLBACK / ...
  5931  transaction_stmt:
  5932    begin_stmt    // EXTEND WITH HELP: BEGIN
  5933  | commit_stmt   // EXTEND WITH HELP: COMMIT
  5934  | rollback_stmt // EXTEND WITH HELP: ROLLBACK
  5935  | abort_stmt    /* SKIP DOC */
  5936  
  5937  // %Help: BEGIN - start a transaction
  5938  // %Category: Txn
  5939  // %Text:
  5940  // BEGIN [TRANSACTION] [ <txnparameter> [[,] ...] ]
  5941  // START TRANSACTION [ <txnparameter> [[,] ...] ]
  5942  //
  5943  // Transaction parameters:
  5944  //    ISOLATION LEVEL { SNAPSHOT | SERIALIZABLE }
  5945  //    PRIORITY { LOW | NORMAL | HIGH }
  5946  //
  5947  // %SeeAlso: COMMIT, ROLLBACK, WEBDOCS/begin-transaction.html
  5948  begin_stmt:
  5949    BEGIN opt_transaction begin_transaction
  5950    {
  5951      $$.val = $3.stmt()
  5952    }
  5953  | BEGIN error // SHOW HELP: BEGIN
  5954  | START TRANSACTION begin_transaction
  5955    {
  5956      $$.val = $3.stmt()
  5957    }
  5958  | START error // SHOW HELP: BEGIN
  5959  
  5960  // %Help: COMMIT - commit the current transaction
  5961  // %Category: Txn
  5962  // %Text:
  5963  // COMMIT [TRANSACTION]
  5964  // END [TRANSACTION]
  5965  // %SeeAlso: BEGIN, ROLLBACK, WEBDOCS/commit-transaction.html
  5966  commit_stmt:
  5967    COMMIT opt_transaction
  5968    {
  5969      $$.val = &tree.CommitTransaction{}
  5970    }
  5971  | COMMIT error // SHOW HELP: COMMIT
  5972  | END opt_transaction
  5973    {
  5974      $$.val = &tree.CommitTransaction{}
  5975    }
  5976  | END error // SHOW HELP: COMMIT
  5977  
  5978  abort_stmt:
  5979    ABORT opt_abort_mod
  5980    {
  5981      $$.val = &tree.RollbackTransaction{}
  5982    }
  5983  
  5984  opt_abort_mod:
  5985    TRANSACTION {}
  5986  | WORK        {}
  5987  | /* EMPTY */ {}
  5988  
  5989  // %Help: ROLLBACK - abort the current (sub-)transaction
  5990  // %Category: Txn
  5991  // %Text:
  5992  // ROLLBACK [TRANSACTION]
  5993  // ROLLBACK [TRANSACTION] TO [SAVEPOINT] <savepoint name>
  5994  // %SeeAlso: BEGIN, COMMIT, SAVEPOINT, WEBDOCS/rollback-transaction.html
  5995  rollback_stmt:
  5996    ROLLBACK opt_transaction
  5997    {
  5998       $$.val = &tree.RollbackTransaction{}
  5999    }
  6000  | ROLLBACK opt_transaction TO savepoint_name
  6001    {
  6002       $$.val = &tree.RollbackToSavepoint{Savepoint: tree.Name($4)}
  6003    }
  6004  | ROLLBACK error // SHOW HELP: ROLLBACK
  6005  
  6006  opt_transaction:
  6007    TRANSACTION {}
  6008  | /* EMPTY */ {}
  6009  
  6010  savepoint_name:
  6011    SAVEPOINT name
  6012    {
  6013      $$ = $2
  6014    }
  6015  | name
  6016    {
  6017      $$ = $1
  6018    }
  6019  
  6020  begin_transaction:
  6021    transaction_mode_list
  6022    {
  6023      $$.val = &tree.BeginTransaction{Modes: $1.transactionModes()}
  6024    }
  6025  | /* EMPTY */
  6026    {
  6027      $$.val = &tree.BeginTransaction{}
  6028    }
  6029  
  6030  transaction_mode_list:
  6031    transaction_mode
  6032    {
  6033      $$.val = $1.transactionModes()
  6034    }
  6035  | transaction_mode_list opt_comma transaction_mode
  6036    {
  6037      a := $1.transactionModes()
  6038      b := $3.transactionModes()
  6039      err := a.Merge(b)
  6040      if err != nil { return setErr(sqllex, err) }
  6041      $$.val = a
  6042    }
  6043  
  6044  // The transaction mode list after BEGIN should use comma-separated
  6045  // modes as per the SQL standard, but PostgreSQL historically allowed
  6046  // them to be listed without commas too.
  6047  opt_comma:
  6048    ','
  6049    { }
  6050  | /* EMPTY */
  6051    { }
  6052  
  6053  transaction_mode:
  6054    transaction_iso_level
  6055    {
  6056      /* SKIP DOC */
  6057      $$.val = tree.TransactionModes{Isolation: $1.isoLevel()}
  6058    }
  6059  | transaction_user_priority
  6060    {
  6061      $$.val = tree.TransactionModes{UserPriority: $1.userPriority()}
  6062    }
  6063  | transaction_read_mode
  6064    {
  6065      $$.val = tree.TransactionModes{ReadWriteMode: $1.readWriteMode()}
  6066    }
  6067  | as_of_clause
  6068    {
  6069      $$.val = tree.TransactionModes{AsOf: $1.asOfClause()}
  6070    }
  6071  
  6072  transaction_user_priority:
  6073    PRIORITY user_priority
  6074    {
  6075      $$.val = $2.userPriority()
  6076    }
  6077  
  6078  transaction_iso_level:
  6079    ISOLATION LEVEL iso_level
  6080    {
  6081      $$.val = $3.isoLevel()
  6082    }
  6083  
  6084  transaction_read_mode:
  6085    READ ONLY
  6086    {
  6087      $$.val = tree.ReadOnly
  6088    }
  6089  | READ WRITE
  6090    {
  6091      $$.val = tree.ReadWrite
  6092    }
  6093  
  6094  // %Help: CREATE DATABASE - create a new database
  6095  // %Category: DDL
  6096  // %Text: CREATE DATABASE [IF NOT EXISTS] <name>
  6097  // %SeeAlso: WEBDOCS/create-database.html
  6098  create_database_stmt:
  6099    CREATE DATABASE database_name opt_with opt_template_clause opt_encoding_clause opt_lc_collate_clause opt_lc_ctype_clause
  6100    {
  6101      $$.val = &tree.CreateDatabase{
  6102        Name: tree.Name($3),
  6103        Template: $5,
  6104        Encoding: $6,
  6105        Collate: $7,
  6106        CType: $8,
  6107      }
  6108    }
  6109  | CREATE DATABASE IF NOT EXISTS database_name opt_with opt_template_clause opt_encoding_clause opt_lc_collate_clause opt_lc_ctype_clause
  6110    {
  6111      $$.val = &tree.CreateDatabase{
  6112        IfNotExists: true,
  6113        Name: tree.Name($6),
  6114        Template: $8,
  6115        Encoding: $9,
  6116        Collate: $10,
  6117        CType: $11,
  6118      }
  6119     }
  6120  | CREATE DATABASE error // SHOW HELP: CREATE DATABASE
  6121  
  6122  opt_template_clause:
  6123    TEMPLATE opt_equal non_reserved_word_or_sconst
  6124    {
  6125      $$ = $3
  6126    }
  6127  | /* EMPTY */
  6128    {
  6129      $$ = ""
  6130    }
  6131  
  6132  opt_encoding_clause:
  6133    ENCODING opt_equal non_reserved_word_or_sconst
  6134    {
  6135      $$ = $3
  6136    }
  6137  | /* EMPTY */
  6138    {
  6139      $$ = ""
  6140    }
  6141  
  6142  opt_lc_collate_clause:
  6143    LC_COLLATE opt_equal non_reserved_word_or_sconst
  6144    {
  6145      $$ = $3
  6146    }
  6147  | /* EMPTY */
  6148    {
  6149      $$ = ""
  6150    }
  6151  
  6152  opt_lc_ctype_clause:
  6153    LC_CTYPE opt_equal non_reserved_word_or_sconst
  6154    {
  6155      $$ = $3
  6156    }
  6157  | /* EMPTY */
  6158    {
  6159      $$ = ""
  6160    }
  6161  
  6162  opt_equal:
  6163    '=' {}
  6164  | /* EMPTY */ {}
  6165  
  6166  // %Help: INSERT - create new rows in a table
  6167  // %Category: DML
  6168  // %Text:
  6169  // INSERT INTO <tablename> [[AS] <name>] [( <colnames...> )]
  6170  //        <selectclause>
  6171  //        [ON CONFLICT [( <colnames...> )] {DO UPDATE SET ... [WHERE <expr>] | DO NOTHING}]
  6172  //        [RETURNING <exprs...>]
  6173  // %SeeAlso: UPSERT, UPDATE, DELETE, WEBDOCS/insert.html
  6174  insert_stmt:
  6175    opt_with_clause INSERT INTO insert_target insert_rest returning_clause
  6176    {
  6177      $$.val = $5.stmt()
  6178      $$.val.(*tree.Insert).With = $1.with()
  6179      $$.val.(*tree.Insert).Table = $4.tblExpr()
  6180      $$.val.(*tree.Insert).Returning = $6.retClause()
  6181    }
  6182  | opt_with_clause INSERT INTO insert_target insert_rest on_conflict returning_clause
  6183    {
  6184      $$.val = $5.stmt()
  6185      $$.val.(*tree.Insert).With = $1.with()
  6186      $$.val.(*tree.Insert).Table = $4.tblExpr()
  6187      $$.val.(*tree.Insert).OnConflict = $6.onConflict()
  6188      $$.val.(*tree.Insert).Returning = $7.retClause()
  6189    }
  6190  | opt_with_clause INSERT error // SHOW HELP: INSERT
  6191  
  6192  // %Help: UPSERT - create or replace rows in a table
  6193  // %Category: DML
  6194  // %Text:
  6195  // UPSERT INTO <tablename> [AS <name>] [( <colnames...> )]
  6196  //        <selectclause>
  6197  //        [RETURNING <exprs...>]
  6198  // %SeeAlso: INSERT, UPDATE, DELETE, WEBDOCS/upsert.html
  6199  upsert_stmt:
  6200    opt_with_clause UPSERT INTO insert_target insert_rest returning_clause
  6201    {
  6202      $$.val = $5.stmt()
  6203      $$.val.(*tree.Insert).With = $1.with()
  6204      $$.val.(*tree.Insert).Table = $4.tblExpr()
  6205      $$.val.(*tree.Insert).OnConflict = &tree.OnConflict{}
  6206      $$.val.(*tree.Insert).Returning = $6.retClause()
  6207    }
  6208  | opt_with_clause UPSERT error // SHOW HELP: UPSERT
  6209  
  6210  insert_target:
  6211    table_name
  6212    {
  6213      name := $1.unresolvedObjectName().ToTableName()
  6214      $$.val = &name
  6215    }
  6216  // Can't easily make AS optional here, because VALUES in insert_rest would have
  6217  // a shift/reduce conflict with VALUES as an optional alias. We could easily
  6218  // allow unreserved_keywords as optional aliases, but that'd be an odd
  6219  // divergence from other places. So just require AS for now.
  6220  | table_name AS table_alias_name
  6221    {
  6222      name := $1.unresolvedObjectName().ToTableName()
  6223      $$.val = &tree.AliasedTableExpr{Expr: &name, As: tree.AliasClause{Alias: tree.Name($3)}}
  6224    }
  6225  | numeric_table_ref
  6226    {
  6227      $$.val = $1.tblExpr()
  6228    }
  6229  
  6230  insert_rest:
  6231    select_stmt
  6232    {
  6233      $$.val = &tree.Insert{Rows: $1.slct()}
  6234    }
  6235  | '(' insert_column_list ')' select_stmt
  6236    {
  6237      $$.val = &tree.Insert{Columns: $2.nameList(), Rows: $4.slct()}
  6238    }
  6239  | DEFAULT VALUES
  6240    {
  6241      $$.val = &tree.Insert{Rows: &tree.Select{}}
  6242    }
  6243  
  6244  insert_column_list:
  6245    insert_column_item
  6246    {
  6247      $$.val = tree.NameList{tree.Name($1)}
  6248    }
  6249  | insert_column_list ',' insert_column_item
  6250    {
  6251      $$.val = append($1.nameList(), tree.Name($3))
  6252    }
  6253  
  6254  // insert_column_item represents the target of an INSERT/UPSERT or one
  6255  // of the LHS operands in an UPDATE SET statement.
  6256  //
  6257  //    INSERT INTO foo (x, y) VALUES ...
  6258  //                     ^^^^ here
  6259  //
  6260  //    UPDATE foo SET x = 1+2, (y, z) = (4, 5)
  6261  //                   ^^ here   ^^^^ here
  6262  //
  6263  // Currently CockroachDB only supports simple column names in this
  6264  // position. The rule below can be extended to support a sequence of
  6265  // field subscript or array indexing operators to designate a part of
  6266  // a field, when partial updates are to be supported. This likely will
  6267  // be needed together with support for composite types (#27792).
  6268  insert_column_item:
  6269    column_name
  6270  | column_name '.' error { return unimplementedWithIssue(sqllex, 27792) }
  6271  
  6272  on_conflict:
  6273    ON CONFLICT opt_conf_expr DO UPDATE SET set_clause_list opt_where_clause
  6274    {
  6275      $$.val = &tree.OnConflict{Columns: $3.nameList(), Exprs: $7.updateExprs(), Where: tree.NewWhere(tree.AstWhere, $8.expr())}
  6276    }
  6277  | ON CONFLICT opt_conf_expr DO NOTHING
  6278    {
  6279      $$.val = &tree.OnConflict{Columns: $3.nameList(), DoNothing: true}
  6280    }
  6281  
  6282  opt_conf_expr:
  6283    '(' name_list ')'
  6284    {
  6285      $$.val = $2.nameList()
  6286    }
  6287  | '(' name_list ')' where_clause { return unimplementedWithIssue(sqllex, 32557) }
  6288  | ON CONSTRAINT constraint_name { return unimplementedWithIssue(sqllex, 28161) }
  6289  | /* EMPTY */
  6290    {
  6291      $$.val = tree.NameList(nil)
  6292    }
  6293  
  6294  returning_clause:
  6295    RETURNING target_list
  6296    {
  6297      ret := tree.ReturningExprs($2.selExprs())
  6298      $$.val = &ret
  6299    }
  6300  | RETURNING NOTHING
  6301    {
  6302      $$.val = tree.ReturningNothingClause
  6303    }
  6304  | /* EMPTY */
  6305    {
  6306      $$.val = tree.AbsentReturningClause
  6307    }
  6308  
  6309  // %Help: UPDATE - update rows of a table
  6310  // %Category: DML
  6311  // %Text:
  6312  // UPDATE <tablename> [[AS] <name>]
  6313  //        SET ...
  6314  //        [WHERE <expr>]
  6315  //        [ORDER BY <exprs...>]
  6316  //        [LIMIT <expr>]
  6317  //        [RETURNING <exprs...>]
  6318  // %SeeAlso: INSERT, UPSERT, DELETE, WEBDOCS/update.html
  6319  update_stmt:
  6320    opt_with_clause UPDATE table_expr_opt_alias_idx
  6321      SET set_clause_list opt_from_list opt_where_clause opt_sort_clause opt_limit_clause returning_clause
  6322    {
  6323      $$.val = &tree.Update{
  6324        With: $1.with(),
  6325        Table: $3.tblExpr(),
  6326        Exprs: $5.updateExprs(),
  6327        From: $6.tblExprs(),
  6328        Where: tree.NewWhere(tree.AstWhere, $7.expr()),
  6329        OrderBy: $8.orderBy(),
  6330        Limit: $9.limit(),
  6331        Returning: $10.retClause(),
  6332      }
  6333    }
  6334  | opt_with_clause UPDATE error // SHOW HELP: UPDATE
  6335  
  6336  opt_from_list:
  6337    FROM from_list {
  6338      $$.val = $2.tblExprs()
  6339    }
  6340  | /* EMPTY */ {
  6341      $$.val = tree.TableExprs{}
  6342  }
  6343  
  6344  set_clause_list:
  6345    set_clause
  6346    {
  6347      $$.val = tree.UpdateExprs{$1.updateExpr()}
  6348    }
  6349  | set_clause_list ',' set_clause
  6350    {
  6351      $$.val = append($1.updateExprs(), $3.updateExpr())
  6352    }
  6353  
  6354  // TODO(knz): The LHS in these can be extended to support
  6355  // a path to a field member when compound types are supported.
  6356  // Keep it simple for now.
  6357  set_clause:
  6358    single_set_clause
  6359  | multiple_set_clause
  6360  
  6361  single_set_clause:
  6362    column_name '=' a_expr
  6363    {
  6364      $$.val = &tree.UpdateExpr{Names: tree.NameList{tree.Name($1)}, Expr: $3.expr()}
  6365    }
  6366  | column_name '.' error { return unimplementedWithIssue(sqllex, 27792) }
  6367  
  6368  multiple_set_clause:
  6369    '(' insert_column_list ')' '=' in_expr
  6370    {
  6371      $$.val = &tree.UpdateExpr{Tuple: true, Names: $2.nameList(), Expr: $5.expr()}
  6372    }
  6373  
  6374  // A complete SELECT statement looks like this.
  6375  //
  6376  // The rule returns either a single select_stmt node or a tree of them,
  6377  // representing a set-operation tree.
  6378  //
  6379  // There is an ambiguity when a sub-SELECT is within an a_expr and there are
  6380  // excess parentheses: do the parentheses belong to the sub-SELECT or to the
  6381  // surrounding a_expr?  We don't really care, but bison wants to know. To
  6382  // resolve the ambiguity, we are careful to define the grammar so that the
  6383  // decision is staved off as long as possible: as long as we can keep absorbing
  6384  // parentheses into the sub-SELECT, we will do so, and only when it's no longer
  6385  // possible to do that will we decide that parens belong to the expression. For
  6386  // example, in "SELECT (((SELECT 2)) + 3)" the extra parentheses are treated as
  6387  // part of the sub-select. The necessity of doing it that way is shown by
  6388  // "SELECT (((SELECT 2)) UNION SELECT 2)". Had we parsed "((SELECT 2))" as an
  6389  // a_expr, it'd be too late to go back to the SELECT viewpoint when we see the
  6390  // UNION.
  6391  //
  6392  // This approach is implemented by defining a nonterminal select_with_parens,
  6393  // which represents a SELECT with at least one outer layer of parentheses, and
  6394  // being careful to use select_with_parens, never '(' select_stmt ')', in the
  6395  // expression grammar. We will then have shift-reduce conflicts which we can
  6396  // resolve in favor of always treating '(' <select> ')' as a
  6397  // select_with_parens. To resolve the conflicts, the productions that conflict
  6398  // with the select_with_parens productions are manually given precedences lower
  6399  // than the precedence of ')', thereby ensuring that we shift ')' (and then
  6400  // reduce to select_with_parens) rather than trying to reduce the inner
  6401  // <select> nonterminal to something else. We use UMINUS precedence for this,
  6402  // which is a fairly arbitrary choice.
  6403  //
  6404  // To be able to define select_with_parens itself without ambiguity, we need a
  6405  // nonterminal select_no_parens that represents a SELECT structure with no
  6406  // outermost parentheses. This is a little bit tedious, but it works.
  6407  //
  6408  // In non-expression contexts, we use select_stmt which can represent a SELECT
  6409  // with or without outer parentheses.
  6410  select_stmt:
  6411    select_no_parens %prec UMINUS
  6412  | select_with_parens %prec UMINUS
  6413    {
  6414      $$.val = &tree.Select{Select: $1.selectStmt()}
  6415    }
  6416  
  6417  select_with_parens:
  6418    '(' select_no_parens ')'
  6419    {
  6420      $$.val = &tree.ParenSelect{Select: $2.slct()}
  6421    }
  6422  | '(' select_with_parens ')'
  6423    {
  6424      $$.val = &tree.ParenSelect{Select: &tree.Select{Select: $2.selectStmt()}}
  6425    }
  6426  
  6427  // This rule parses the equivalent of the standard's <query expression>. The
  6428  // duplicative productions are annoying, but hard to get rid of without
  6429  // creating shift/reduce conflicts.
  6430  //
  6431  //      The locking clause (FOR UPDATE etc) may be before or after
  6432  //      LIMIT/OFFSET. In <=7.2.X, LIMIT/OFFSET had to be after FOR UPDATE We
  6433  //      now support both orderings, but prefer LIMIT/OFFSET before the locking
  6434  //      clause.
  6435  //      - 2002-08-28 bjm
  6436  select_no_parens:
  6437    simple_select
  6438    {
  6439      $$.val = &tree.Select{Select: $1.selectStmt()}
  6440    }
  6441  | select_clause sort_clause
  6442    {
  6443      $$.val = &tree.Select{Select: $1.selectStmt(), OrderBy: $2.orderBy()}
  6444    }
  6445  | select_clause opt_sort_clause for_locking_clause opt_select_limit
  6446    {
  6447      $$.val = &tree.Select{Select: $1.selectStmt(), OrderBy: $2.orderBy(), Limit: $4.limit(), Locking: $3.lockingClause()}
  6448    }
  6449  | select_clause opt_sort_clause select_limit opt_for_locking_clause
  6450    {
  6451      $$.val = &tree.Select{Select: $1.selectStmt(), OrderBy: $2.orderBy(), Limit: $3.limit(), Locking: $4.lockingClause()}
  6452    }
  6453  | with_clause select_clause
  6454    {
  6455      $$.val = &tree.Select{With: $1.with(), Select: $2.selectStmt()}
  6456    }
  6457  | with_clause select_clause sort_clause
  6458    {
  6459      $$.val = &tree.Select{With: $1.with(), Select: $2.selectStmt(), OrderBy: $3.orderBy()}
  6460    }
  6461  | with_clause select_clause opt_sort_clause for_locking_clause opt_select_limit
  6462    {
  6463      $$.val = &tree.Select{With: $1.with(), Select: $2.selectStmt(), OrderBy: $3.orderBy(), Limit: $5.limit(), Locking: $4.lockingClause()}
  6464    }
  6465  | with_clause select_clause opt_sort_clause select_limit opt_for_locking_clause
  6466    {
  6467      $$.val = &tree.Select{With: $1.with(), Select: $2.selectStmt(), OrderBy: $3.orderBy(), Limit: $4.limit(), Locking: $5.lockingClause()}
  6468    }
  6469  
  6470  for_locking_clause:
  6471    for_locking_items { $$.val = $1.lockingClause() }
  6472  | FOR READ ONLY     { $$.val = (tree.LockingClause)(nil) }
  6473  
  6474  opt_for_locking_clause:
  6475    for_locking_clause { $$.val = $1.lockingClause() }
  6476  | /* EMPTY */        { $$.val = (tree.LockingClause)(nil) }
  6477  
  6478  for_locking_items:
  6479    for_locking_item
  6480    {
  6481      $$.val = tree.LockingClause{$1.lockingItem()}
  6482    }
  6483  | for_locking_items for_locking_item
  6484    {
  6485      $$.val = append($1.lockingClause(), $2.lockingItem())
  6486    }
  6487  
  6488  for_locking_item:
  6489    for_locking_strength opt_locked_rels opt_nowait_or_skip
  6490    {
  6491      $$.val = &tree.LockingItem{
  6492        Strength:   $1.lockingStrength(),
  6493        Targets:    $2.tableNames(),
  6494        WaitPolicy: $3.lockingWaitPolicy(),
  6495      }
  6496    }
  6497  
  6498  for_locking_strength:
  6499    FOR UPDATE        { $$.val = tree.ForUpdate }
  6500  | FOR NO KEY UPDATE { $$.val = tree.ForNoKeyUpdate }
  6501  | FOR SHARE         { $$.val = tree.ForShare }
  6502  | FOR KEY SHARE     { $$.val = tree.ForKeyShare }
  6503  
  6504  opt_locked_rels:
  6505    /* EMPTY */        { $$.val = tree.TableNames{} }
  6506  | OF table_name_list { $$.val = $2.tableNames() }
  6507  
  6508  opt_nowait_or_skip:
  6509    /* EMPTY */ { $$.val = tree.LockWaitBlock }
  6510  | SKIP LOCKED { $$.val = tree.LockWaitSkip }
  6511  | NOWAIT      { $$.val = tree.LockWaitError }
  6512  
  6513  select_clause:
  6514  // We only provide help if an open parenthesis is provided, because
  6515  // otherwise the rule is ambiguous with the top-level statement list.
  6516    '(' error // SHOW HELP: <SELECTCLAUSE>
  6517  | simple_select
  6518  | select_with_parens
  6519  
  6520  // This rule parses SELECT statements that can appear within set operations,
  6521  // including UNION, INTERSECT and EXCEPT. '(' and ')' can be used to specify
  6522  // the ordering of the set operations. Without '(' and ')' we want the
  6523  // operations to be ordered per the precedence specs at the head of this file.
  6524  //
  6525  // As with select_no_parens, simple_select cannot have outer parentheses, but
  6526  // can have parenthesized subclauses.
  6527  //
  6528  // Note that sort clauses cannot be included at this level --- SQL requires
  6529  //       SELECT foo UNION SELECT bar ORDER BY baz
  6530  // to be parsed as
  6531  //       (SELECT foo UNION SELECT bar) ORDER BY baz
  6532  // not
  6533  //       SELECT foo UNION (SELECT bar ORDER BY baz)
  6534  //
  6535  // Likewise for WITH, FOR UPDATE and LIMIT. Therefore, those clauses are
  6536  // described as part of the select_no_parens production, not simple_select.
  6537  // This does not limit functionality, because you can reintroduce these clauses
  6538  // inside parentheses.
  6539  //
  6540  // NOTE: only the leftmost component select_stmt should have INTO. However,
  6541  // this is not checked by the grammar; parse analysis must check it.
  6542  //
  6543  // %Help: <SELECTCLAUSE> - access tabular data
  6544  // %Category: DML
  6545  // %Text:
  6546  // Select clause:
  6547  //   TABLE <tablename>
  6548  //   VALUES ( <exprs...> ) [ , ... ]
  6549  //   SELECT ... [ { INTERSECT | UNION | EXCEPT } [ ALL | DISTINCT ] <selectclause> ]
  6550  simple_select:
  6551    simple_select_clause // EXTEND WITH HELP: SELECT
  6552  | values_clause        // EXTEND WITH HELP: VALUES
  6553  | table_clause         // EXTEND WITH HELP: TABLE
  6554  | set_operation
  6555  
  6556  // %Help: SELECT - retrieve rows from a data source and compute a result
  6557  // %Category: DML
  6558  // %Text:
  6559  // SELECT [DISTINCT [ ON ( <expr> [ , ... ] ) ] ]
  6560  //        { <expr> [[AS] <name>] | [ [<dbname>.] <tablename>. ] * } [, ...]
  6561  //        [ FROM <source> ]
  6562  //        [ WHERE <expr> ]
  6563  //        [ GROUP BY <expr> [ , ... ] ]
  6564  //        [ HAVING <expr> ]
  6565  //        [ WINDOW <name> AS ( <definition> ) ]
  6566  //        [ { UNION | INTERSECT | EXCEPT } [ ALL | DISTINCT ] <selectclause> ]
  6567  //        [ ORDER BY <expr> [ ASC | DESC ] [, ...] ]
  6568  //        [ LIMIT { <expr> | ALL } ]
  6569  //        [ OFFSET <expr> [ ROW | ROWS ] ]
  6570  // %SeeAlso: WEBDOCS/select-clause.html
  6571  simple_select_clause:
  6572    SELECT opt_all_clause target_list
  6573      from_clause opt_where_clause
  6574      group_clause having_clause window_clause
  6575    {
  6576      $$.val = &tree.SelectClause{
  6577        Exprs:   $3.selExprs(),
  6578        From:    $4.from(),
  6579        Where:   tree.NewWhere(tree.AstWhere, $5.expr()),
  6580        GroupBy: $6.groupBy(),
  6581        Having:  tree.NewWhere(tree.AstHaving, $7.expr()),
  6582        Window:  $8.window(),
  6583      }
  6584    }
  6585  | SELECT distinct_clause target_list
  6586      from_clause opt_where_clause
  6587      group_clause having_clause window_clause
  6588    {
  6589      $$.val = &tree.SelectClause{
  6590        Distinct: $2.bool(),
  6591        Exprs:    $3.selExprs(),
  6592        From:     $4.from(),
  6593        Where:    tree.NewWhere(tree.AstWhere, $5.expr()),
  6594        GroupBy:  $6.groupBy(),
  6595        Having:   tree.NewWhere(tree.AstHaving, $7.expr()),
  6596        Window:   $8.window(),
  6597      }
  6598    }
  6599  | SELECT distinct_on_clause target_list
  6600      from_clause opt_where_clause
  6601      group_clause having_clause window_clause
  6602    {
  6603      $$.val = &tree.SelectClause{
  6604        Distinct:   true,
  6605        DistinctOn: $2.distinctOn(),
  6606        Exprs:      $3.selExprs(),
  6607        From:       $4.from(),
  6608        Where:      tree.NewWhere(tree.AstWhere, $5.expr()),
  6609        GroupBy:    $6.groupBy(),
  6610        Having:     tree.NewWhere(tree.AstHaving, $7.expr()),
  6611        Window:     $8.window(),
  6612      }
  6613    }
  6614  | SELECT error // SHOW HELP: SELECT
  6615  
  6616  set_operation:
  6617    select_clause UNION all_or_distinct select_clause
  6618    {
  6619      $$.val = &tree.UnionClause{
  6620        Type:  tree.UnionOp,
  6621        Left:  &tree.Select{Select: $1.selectStmt()},
  6622        Right: &tree.Select{Select: $4.selectStmt()},
  6623        All:   $3.bool(),
  6624      }
  6625    }
  6626  | select_clause INTERSECT all_or_distinct select_clause
  6627    {
  6628      $$.val = &tree.UnionClause{
  6629        Type:  tree.IntersectOp,
  6630        Left:  &tree.Select{Select: $1.selectStmt()},
  6631        Right: &tree.Select{Select: $4.selectStmt()},
  6632        All:   $3.bool(),
  6633      }
  6634    }
  6635  | select_clause EXCEPT all_or_distinct select_clause
  6636    {
  6637      $$.val = &tree.UnionClause{
  6638        Type:  tree.ExceptOp,
  6639        Left:  &tree.Select{Select: $1.selectStmt()},
  6640        Right: &tree.Select{Select: $4.selectStmt()},
  6641        All:   $3.bool(),
  6642      }
  6643    }
  6644  
  6645  // %Help: TABLE - select an entire table
  6646  // %Category: DML
  6647  // %Text: TABLE <tablename>
  6648  // %SeeAlso: SELECT, VALUES, WEBDOCS/table-expressions.html
  6649  table_clause:
  6650    TABLE table_ref
  6651    {
  6652      $$.val = &tree.SelectClause{
  6653        Exprs:       tree.SelectExprs{tree.StarSelectExpr()},
  6654        From:        tree.From{Tables: tree.TableExprs{$2.tblExpr()}},
  6655        TableSelect: true,
  6656      }
  6657    }
  6658  | TABLE error // SHOW HELP: TABLE
  6659  
  6660  // SQL standard WITH clause looks like:
  6661  //
  6662  // WITH [ RECURSIVE ] <query name> [ (<column> [, ...]) ]
  6663  //        AS [ [ NOT ] MATERIALIZED ] (query) [ SEARCH or CYCLE clause ]
  6664  //
  6665  // We don't currently support the SEARCH or CYCLE clause.
  6666  //
  6667  // Recognizing WITH_LA here allows a CTE to be named TIME or ORDINALITY.
  6668  with_clause:
  6669    WITH cte_list
  6670    {
  6671      $$.val = &tree.With{CTEList: $2.ctes()}
  6672    }
  6673  | WITH_LA cte_list
  6674    {
  6675      /* SKIP DOC */
  6676      $$.val = &tree.With{CTEList: $2.ctes()}
  6677    }
  6678  | WITH RECURSIVE cte_list
  6679    {
  6680      $$.val = &tree.With{Recursive: true, CTEList: $3.ctes()}
  6681    }
  6682  
  6683  cte_list:
  6684    common_table_expr
  6685    {
  6686      $$.val = []*tree.CTE{$1.cte()}
  6687    }
  6688  | cte_list ',' common_table_expr
  6689    {
  6690      $$.val = append($1.ctes(), $3.cte())
  6691    }
  6692  
  6693  materialize_clause:
  6694    MATERIALIZED
  6695    {
  6696      $$.val = true
  6697    }
  6698  | NOT MATERIALIZED
  6699    {
  6700      $$.val = false
  6701    }
  6702  
  6703  common_table_expr:
  6704    table_alias_name opt_column_list AS '(' preparable_stmt ')'
  6705      {
  6706        $$.val = &tree.CTE{
  6707          Name: tree.AliasClause{Alias: tree.Name($1), Cols: $2.nameList() },
  6708          Mtr: tree.MaterializeClause{
  6709            Set: false,
  6710          },
  6711          Stmt: $5.stmt(),
  6712        }
  6713      }
  6714  | table_alias_name opt_column_list AS materialize_clause '(' preparable_stmt ')'
  6715      {
  6716        $$.val = &tree.CTE{
  6717          Name: tree.AliasClause{Alias: tree.Name($1), Cols: $2.nameList() },
  6718          Mtr: tree.MaterializeClause{
  6719            Materialize: $4.bool(),
  6720            Set: true,
  6721          },
  6722          Stmt: $6.stmt(),
  6723        }
  6724      }
  6725  
  6726  opt_with:
  6727    WITH {}
  6728  | /* EMPTY */ {}
  6729  
  6730  opt_with_clause:
  6731    with_clause
  6732    {
  6733      $$.val = $1.with()
  6734    }
  6735  | /* EMPTY */
  6736    {
  6737      $$.val = nil
  6738    }
  6739  
  6740  opt_table:
  6741    TABLE {}
  6742  | /* EMPTY */ {}
  6743  
  6744  all_or_distinct:
  6745    ALL
  6746    {
  6747      $$.val = true
  6748    }
  6749  | DISTINCT
  6750    {
  6751      $$.val = false
  6752    }
  6753  | /* EMPTY */
  6754    {
  6755      $$.val = false
  6756    }
  6757  
  6758  distinct_clause:
  6759    DISTINCT
  6760    {
  6761      $$.val = true
  6762    }
  6763  
  6764  distinct_on_clause:
  6765    DISTINCT ON '(' expr_list ')'
  6766    {
  6767      $$.val = tree.DistinctOn($4.exprs())
  6768    }
  6769  
  6770  opt_all_clause:
  6771    ALL {}
  6772  | /* EMPTY */ {}
  6773  
  6774  opt_sort_clause:
  6775    sort_clause
  6776    {
  6777      $$.val = $1.orderBy()
  6778    }
  6779  | /* EMPTY */
  6780    {
  6781      $$.val = tree.OrderBy(nil)
  6782    }
  6783  
  6784  sort_clause:
  6785    ORDER BY sortby_list
  6786    {
  6787      $$.val = tree.OrderBy($3.orders())
  6788    }
  6789  
  6790  single_sort_clause:
  6791    ORDER BY sortby
  6792    {
  6793      $$.val = tree.OrderBy([]*tree.Order{$3.order()})
  6794    }
  6795  | ORDER BY sortby ',' sortby_list
  6796    {
  6797      sqllex.Error("multiple ORDER BY clauses are not supported in this function")
  6798      return 1
  6799    }
  6800  
  6801  sortby_list:
  6802    sortby
  6803    {
  6804      $$.val = []*tree.Order{$1.order()}
  6805    }
  6806  | sortby_list ',' sortby
  6807    {
  6808      $$.val = append($1.orders(), $3.order())
  6809    }
  6810  
  6811  sortby:
  6812    a_expr opt_asc_desc opt_nulls_order
  6813    {
  6814      /* FORCE DOC */
  6815      dir := $2.dir()
  6816      nullsOrder := $3.nullsOrder()
  6817      // We currently only support the opposite of Postgres defaults.
  6818      if nullsOrder != tree.DefaultNullsOrder {
  6819        if dir == tree.Descending && nullsOrder == tree.NullsFirst {
  6820          return unimplementedWithIssue(sqllex, 6224)
  6821        }
  6822        if dir != tree.Descending && nullsOrder == tree.NullsLast {
  6823          return unimplementedWithIssue(sqllex, 6224)
  6824        }
  6825      }
  6826      $$.val = &tree.Order{
  6827        OrderType:  tree.OrderByColumn,
  6828        Expr:       $1.expr(),
  6829        Direction:  dir,
  6830        NullsOrder: nullsOrder,
  6831      }
  6832    }
  6833  | PRIMARY KEY table_name opt_asc_desc
  6834    {
  6835      name := $3.unresolvedObjectName().ToTableName()
  6836      $$.val = &tree.Order{OrderType: tree.OrderByIndex, Direction: $4.dir(), Table: name}
  6837    }
  6838  | INDEX table_name '@' index_name opt_asc_desc
  6839    {
  6840      name := $2.unresolvedObjectName().ToTableName()
  6841      $$.val = &tree.Order{
  6842        OrderType: tree.OrderByIndex,
  6843        Direction: $5.dir(),
  6844        Table:     name,
  6845        Index:     tree.UnrestrictedName($4),
  6846      }
  6847    }
  6848  
  6849  opt_nulls_order:
  6850    NULLS FIRST
  6851    {
  6852      $$.val = tree.NullsFirst
  6853    }
  6854  | NULLS LAST
  6855    {
  6856      $$.val = tree.NullsLast
  6857    }
  6858  | /* EMPTY */
  6859    {
  6860      $$.val = tree.DefaultNullsOrder
  6861    }
  6862  
  6863  // TODO(pmattis): Support ordering using arbitrary math ops?
  6864  // | a_expr USING math_op {}
  6865  
  6866  select_limit:
  6867    limit_clause offset_clause
  6868    {
  6869      if $1.limit() == nil {
  6870        $$.val = $2.limit()
  6871      } else {
  6872        $$.val = $1.limit()
  6873        $$.val.(*tree.Limit).Offset = $2.limit().Offset
  6874      }
  6875    }
  6876  | offset_clause limit_clause
  6877    {
  6878      $$.val = $1.limit()
  6879      if $2.limit() != nil {
  6880        $$.val.(*tree.Limit).Count = $2.limit().Count
  6881        $$.val.(*tree.Limit).LimitAll = $2.limit().LimitAll
  6882      }
  6883    }
  6884  | limit_clause
  6885  | offset_clause
  6886  
  6887  opt_select_limit:
  6888    select_limit { $$.val = $1.limit() }
  6889  | /* EMPTY */  { $$.val = (*tree.Limit)(nil) }
  6890  
  6891  opt_limit_clause:
  6892    limit_clause
  6893  | /* EMPTY */ { $$.val = (*tree.Limit)(nil) }
  6894  
  6895  limit_clause:
  6896    LIMIT ALL
  6897    {
  6898      $$.val = &tree.Limit{LimitAll: true}
  6899    }
  6900  | LIMIT a_expr
  6901    {
  6902      if $2.expr() == nil {
  6903        $$.val = (*tree.Limit)(nil)
  6904      } else {
  6905        $$.val = &tree.Limit{Count: $2.expr()}
  6906      }
  6907    }
  6908  // SQL:2008 syntax
  6909  // To avoid shift/reduce conflicts, handle the optional value with
  6910  // a separate production rather than an opt_ expression. The fact
  6911  // that ONLY is fully reserved means that this way, we defer any
  6912  // decision about what rule reduces ROW or ROWS to the point where
  6913  // we can see the ONLY token in the lookahead slot.
  6914  | FETCH first_or_next select_fetch_first_value row_or_rows ONLY
  6915    {
  6916      $$.val = &tree.Limit{Count: $3.expr()}
  6917    }
  6918  | FETCH first_or_next row_or_rows ONLY
  6919  	{
  6920      $$.val = &tree.Limit{
  6921        Count: tree.NewNumVal(constant.MakeInt64(1), "" /* origString */, false /* negative */),
  6922      }
  6923    }
  6924  
  6925  offset_clause:
  6926    OFFSET a_expr
  6927    {
  6928      $$.val = &tree.Limit{Offset: $2.expr()}
  6929    }
  6930    // SQL:2008 syntax
  6931    // The trailing ROW/ROWS in this case prevent the full expression
  6932    // syntax. c_expr is the best we can do.
  6933  | OFFSET select_fetch_first_value row_or_rows
  6934    {
  6935      $$.val = &tree.Limit{Offset: $2.expr()}
  6936    }
  6937  
  6938  // Allowing full expressions without parentheses causes various parsing
  6939  // problems with the trailing ROW/ROWS key words. SQL spec only calls for
  6940  // <simple value specification>, which is either a literal or a parameter (but
  6941  // an <SQL parameter reference> could be an identifier, bringing up conflicts
  6942  // with ROW/ROWS). We solve this by leveraging the presence of ONLY (see above)
  6943  // to determine whether the expression is missing rather than trying to make it
  6944  // optional in this rule.
  6945  //
  6946  // c_expr covers almost all the spec-required cases (and more), but it doesn't
  6947  // cover signed numeric literals, which are allowed by the spec. So we include
  6948  // those here explicitly.
  6949  select_fetch_first_value:
  6950    c_expr
  6951  | only_signed_iconst
  6952  | only_signed_fconst
  6953  
  6954  // noise words
  6955  row_or_rows:
  6956    ROW {}
  6957  | ROWS {}
  6958  
  6959  first_or_next:
  6960    FIRST {}
  6961  | NEXT {}
  6962  
  6963  // This syntax for group_clause tries to follow the spec quite closely.
  6964  // However, the spec allows only column references, not expressions,
  6965  // which introduces an ambiguity between implicit row constructors
  6966  // (a,b) and lists of column references.
  6967  //
  6968  // We handle this by using the a_expr production for what the spec calls
  6969  // <ordinary grouping set>, which in the spec represents either one column
  6970  // reference or a parenthesized list of column references. Then, we check the
  6971  // top node of the a_expr to see if it's an RowExpr, and if so, just grab and
  6972  // use the list, discarding the node. (this is done in parse analysis, not here)
  6973  //
  6974  // Each item in the group_clause list is either an expression tree or a
  6975  // GroupingSet node of some type.
  6976  group_clause:
  6977    GROUP BY expr_list
  6978    {
  6979      $$.val = tree.GroupBy($3.exprs())
  6980    }
  6981  | /* EMPTY */
  6982    {
  6983      $$.val = tree.GroupBy(nil)
  6984    }
  6985  
  6986  having_clause:
  6987    HAVING a_expr
  6988    {
  6989      $$.val = $2.expr()
  6990    }
  6991  | /* EMPTY */
  6992    {
  6993      $$.val = tree.Expr(nil)
  6994    }
  6995  
  6996  // Given "VALUES (a, b)" in a table expression context, we have to
  6997  // decide without looking any further ahead whether VALUES is the
  6998  // values clause or a set-generating function. Since VALUES is allowed
  6999  // as a function name both interpretations are feasible. We resolve
  7000  // the shift/reduce conflict by giving the first values_clause
  7001  // production a higher precedence than the VALUES token has, causing
  7002  // the parser to prefer to reduce, in effect assuming that the VALUES
  7003  // is not a function name.
  7004  //
  7005  // %Help: VALUES - select a given set of values
  7006  // %Category: DML
  7007  // %Text: VALUES ( <exprs...> ) [, ...]
  7008  // %SeeAlso: SELECT, TABLE, WEBDOCS/table-expressions.html
  7009  values_clause:
  7010    VALUES '(' expr_list ')' %prec UMINUS
  7011    {
  7012      $$.val = &tree.ValuesClause{Rows: []tree.Exprs{$3.exprs()}}
  7013    }
  7014  | VALUES error // SHOW HELP: VALUES
  7015  | values_clause ',' '(' expr_list ')'
  7016    {
  7017      valNode := $1.selectStmt().(*tree.ValuesClause)
  7018      valNode.Rows = append(valNode.Rows, $4.exprs())
  7019      $$.val = valNode
  7020    }
  7021  
  7022  // clauses common to all optimizable statements:
  7023  //  from_clause   - allow list of both JOIN expressions and table names
  7024  //  where_clause  - qualifications for joins or restrictions
  7025  
  7026  from_clause:
  7027    FROM from_list opt_as_of_clause
  7028    {
  7029      $$.val = tree.From{Tables: $2.tblExprs(), AsOf: $3.asOfClause()}
  7030    }
  7031  | FROM error // SHOW HELP: <SOURCE>
  7032  | /* EMPTY */
  7033    {
  7034      $$.val = tree.From{}
  7035    }
  7036  
  7037  from_list:
  7038    table_ref
  7039    {
  7040      $$.val = tree.TableExprs{$1.tblExpr()}
  7041    }
  7042  | from_list ',' table_ref
  7043    {
  7044      $$.val = append($1.tblExprs(), $3.tblExpr())
  7045    }
  7046  
  7047  index_flags_param:
  7048    FORCE_INDEX '=' index_name
  7049    {
  7050       $$.val = &tree.IndexFlags{Index: tree.UnrestrictedName($3)}
  7051    }
  7052  | FORCE_INDEX '=' '[' iconst64 ']'
  7053    {
  7054      /* SKIP DOC */
  7055      $$.val = &tree.IndexFlags{IndexID: tree.IndexID($4.int64())}
  7056    }
  7057  | ASC
  7058    {
  7059      /* SKIP DOC */
  7060      $$.val = &tree.IndexFlags{Direction: tree.Ascending}
  7061    }
  7062  | DESC
  7063    {
  7064      /* SKIP DOC */
  7065      $$.val = &tree.IndexFlags{Direction: tree.Descending}
  7066    }
  7067  |
  7068    NO_INDEX_JOIN
  7069    {
  7070      $$.val = &tree.IndexFlags{NoIndexJoin: true}
  7071    }
  7072  |
  7073    IGNORE_FOREIGN_KEYS
  7074    {
  7075      /* SKIP DOC */
  7076      $$.val = &tree.IndexFlags{IgnoreForeignKeys: true}
  7077    }
  7078  
  7079  index_flags_param_list:
  7080    index_flags_param
  7081    {
  7082      $$.val = $1.indexFlags()
  7083    }
  7084  |
  7085    index_flags_param_list ',' index_flags_param
  7086    {
  7087      a := $1.indexFlags()
  7088      b := $3.indexFlags()
  7089      if err := a.CombineWith(b); err != nil {
  7090        return setErr(sqllex, err)
  7091      }
  7092      $$.val = a
  7093    }
  7094  
  7095  opt_index_flags:
  7096    '@' index_name
  7097    {
  7098      $$.val = &tree.IndexFlags{Index: tree.UnrestrictedName($2)}
  7099    }
  7100  | '@' '[' iconst64 ']'
  7101    {
  7102      $$.val = &tree.IndexFlags{IndexID: tree.IndexID($3.int64())}
  7103    }
  7104  | '@' '{' index_flags_param_list '}'
  7105    {
  7106      flags := $3.indexFlags()
  7107      if err := flags.Check(); err != nil {
  7108        return setErr(sqllex, err)
  7109      }
  7110      $$.val = flags
  7111    }
  7112  | /* EMPTY */
  7113    {
  7114      $$.val = (*tree.IndexFlags)(nil)
  7115    }
  7116  
  7117  // %Help: <SOURCE> - define a data source for SELECT
  7118  // %Category: DML
  7119  // %Text:
  7120  // Data sources:
  7121  //   <tablename> [ @ { <idxname> | <indexflags> } ]
  7122  //   <tablefunc> ( <exprs...> )
  7123  //   ( { <selectclause> | <source> } )
  7124  //   <source> [AS] <alias> [( <colnames...> )]
  7125  //   <source> [ <jointype> ] JOIN <source> ON <expr>
  7126  //   <source> [ <jointype> ] JOIN <source> USING ( <colnames...> )
  7127  //   <source> NATURAL [ <jointype> ] JOIN <source>
  7128  //   <source> CROSS JOIN <source>
  7129  //   <source> WITH ORDINALITY
  7130  //   '[' EXPLAIN ... ']'
  7131  //   '[' SHOW ... ']'
  7132  //
  7133  // Index flags:
  7134  //   '{' FORCE_INDEX = <idxname> [, ...] '}'
  7135  //   '{' NO_INDEX_JOIN [, ...] '}'
  7136  //   '{' IGNORE_FOREIGN_KEYS [, ...] '}'
  7137  //
  7138  // Join types:
  7139  //   { INNER | { LEFT | RIGHT | FULL } [OUTER] } [ { HASH | MERGE | LOOKUP } ]
  7140  //
  7141  // %SeeAlso: WEBDOCS/table-expressions.html
  7142  table_ref:
  7143    numeric_table_ref opt_index_flags opt_ordinality opt_alias_clause
  7144    {
  7145      /* SKIP DOC */
  7146      $$.val = &tree.AliasedTableExpr{
  7147          Expr:       $1.tblExpr(),
  7148          IndexFlags: $2.indexFlags(),
  7149          Ordinality: $3.bool(),
  7150          As:         $4.aliasClause(),
  7151      }
  7152    }
  7153  | relation_expr opt_index_flags opt_ordinality opt_alias_clause
  7154    {
  7155      name := $1.unresolvedObjectName().ToTableName()
  7156      $$.val = &tree.AliasedTableExpr{
  7157        Expr:       &name,
  7158        IndexFlags: $2.indexFlags(),
  7159        Ordinality: $3.bool(),
  7160        As:         $4.aliasClause(),
  7161      }
  7162    }
  7163  | select_with_parens opt_ordinality opt_alias_clause
  7164    {
  7165      $$.val = &tree.AliasedTableExpr{
  7166        Expr:       &tree.Subquery{Select: $1.selectStmt()},
  7167        Ordinality: $2.bool(),
  7168        As:         $3.aliasClause(),
  7169      }
  7170    }
  7171  | LATERAL select_with_parens opt_ordinality opt_alias_clause
  7172    {
  7173      $$.val = &tree.AliasedTableExpr{
  7174        Expr:       &tree.Subquery{Select: $2.selectStmt()},
  7175        Ordinality: $3.bool(),
  7176        Lateral:    true,
  7177        As:         $4.aliasClause(),
  7178      }
  7179    }
  7180  | joined_table
  7181    {
  7182      $$.val = $1.tblExpr()
  7183    }
  7184  | '(' joined_table ')' opt_ordinality alias_clause
  7185    {
  7186      $$.val = &tree.AliasedTableExpr{Expr: &tree.ParenTableExpr{Expr: $2.tblExpr()}, Ordinality: $4.bool(), As: $5.aliasClause()}
  7187    }
  7188  | func_table opt_ordinality opt_alias_clause
  7189    {
  7190      f := $1.tblExpr()
  7191      $$.val = &tree.AliasedTableExpr{
  7192        Expr: f,
  7193        Ordinality: $2.bool(),
  7194        // Technically, LATERAL is always implied on an SRF, but including it
  7195        // here makes re-printing the AST slightly tricky.
  7196        As: $3.aliasClause(),
  7197      }
  7198    }
  7199  | LATERAL func_table opt_ordinality opt_alias_clause
  7200    {
  7201      f := $2.tblExpr()
  7202      $$.val = &tree.AliasedTableExpr{
  7203        Expr: f,
  7204        Ordinality: $3.bool(),
  7205        Lateral: true,
  7206        As: $4.aliasClause(),
  7207      }
  7208    }
  7209  // The following syntax is a CockroachDB extension:
  7210  //     SELECT ... FROM [ EXPLAIN .... ] WHERE ...
  7211  //     SELECT ... FROM [ SHOW .... ] WHERE ...
  7212  //     SELECT ... FROM [ INSERT ... RETURNING ... ] WHERE ...
  7213  // A statement within square brackets can be used as a table expression (data source).
  7214  // We use square brackets for two reasons:
  7215  // - the grammar would be terribly ambiguous if we used simple
  7216  //   parentheses or no parentheses at all.
  7217  // - it carries visual semantic information, by marking the table
  7218  //   expression as radically different from the other things.
  7219  //   If a user does not know this and encounters this syntax, they
  7220  //   will know from the unusual choice that something rather different
  7221  //   is going on and may be pushed by the unusual syntax to
  7222  //   investigate further in the docs.
  7223  | '[' row_source_extension_stmt ']' opt_ordinality opt_alias_clause
  7224    {
  7225      $$.val = &tree.AliasedTableExpr{Expr: &tree.StatementSource{ Statement: $2.stmt() }, Ordinality: $4.bool(), As: $5.aliasClause() }
  7226    }
  7227  
  7228  numeric_table_ref:
  7229    '[' iconst64 opt_tableref_col_list alias_clause ']'
  7230    {
  7231      /* SKIP DOC */
  7232      $$.val = &tree.TableRef{
  7233        TableID: $2.int64(),
  7234        Columns: $3.tableRefCols(),
  7235        As:      $4.aliasClause(),
  7236      }
  7237    }
  7238  
  7239  func_table:
  7240    func_expr_windowless
  7241    {
  7242      $$.val = &tree.RowsFromExpr{Items: tree.Exprs{$1.expr()}}
  7243    }
  7244  | ROWS FROM '(' rowsfrom_list ')'
  7245    {
  7246      $$.val = &tree.RowsFromExpr{Items: $4.exprs()}
  7247    }
  7248  
  7249  rowsfrom_list:
  7250    rowsfrom_item
  7251    { $$.val = tree.Exprs{$1.expr()} }
  7252  | rowsfrom_list ',' rowsfrom_item
  7253    { $$.val = append($1.exprs(), $3.expr()) }
  7254  
  7255  rowsfrom_item:
  7256    func_expr_windowless opt_col_def_list
  7257    {
  7258      $$.val = $1.expr()
  7259    }
  7260  
  7261  opt_col_def_list:
  7262    /* EMPTY */
  7263    { }
  7264  | AS '(' error
  7265    { return unimplemented(sqllex, "ROWS FROM with col_def_list") }
  7266  
  7267  opt_tableref_col_list:
  7268    /* EMPTY */               { $$.val = nil }
  7269  | '(' ')'                   { $$.val = []tree.ColumnID{} }
  7270  | '(' tableref_col_list ')' { $$.val = $2.tableRefCols() }
  7271  
  7272  tableref_col_list:
  7273    iconst64
  7274    {
  7275      $$.val = []tree.ColumnID{tree.ColumnID($1.int64())}
  7276    }
  7277  | tableref_col_list ',' iconst64
  7278    {
  7279      $$.val = append($1.tableRefCols(), tree.ColumnID($3.int64()))
  7280    }
  7281  
  7282  opt_ordinality:
  7283    WITH_LA ORDINALITY
  7284    {
  7285      $$.val = true
  7286    }
  7287  | /* EMPTY */
  7288    {
  7289      $$.val = false
  7290    }
  7291  
  7292  // It may seem silly to separate joined_table from table_ref, but there is
  7293  // method in SQL's madness: if you don't do it this way you get reduce- reduce
  7294  // conflicts, because it's not clear to the parser generator whether to expect
  7295  // alias_clause after ')' or not. For the same reason we must treat 'JOIN' and
  7296  // 'join_type JOIN' separately, rather than allowing join_type to expand to
  7297  // empty; if we try it, the parser generator can't figure out when to reduce an
  7298  // empty join_type right after table_ref.
  7299  //
  7300  // Note that a CROSS JOIN is the same as an unqualified INNER JOIN, and an
  7301  // INNER JOIN/ON has the same shape but a qualification expression to limit
  7302  // membership. A NATURAL JOIN implicitly matches column names between tables
  7303  // and the shape is determined by which columns are in common. We'll collect
  7304  // columns during the later transformations.
  7305  
  7306  joined_table:
  7307    '(' joined_table ')'
  7308    {
  7309      $$.val = &tree.ParenTableExpr{Expr: $2.tblExpr()}
  7310    }
  7311  | table_ref CROSS opt_join_hint JOIN table_ref
  7312    {
  7313      $$.val = &tree.JoinTableExpr{JoinType: tree.AstCross, Left: $1.tblExpr(), Right: $5.tblExpr(), Hint: $3}
  7314    }
  7315  | table_ref join_type opt_join_hint JOIN table_ref join_qual
  7316    {
  7317      $$.val = &tree.JoinTableExpr{JoinType: $2, Left: $1.tblExpr(), Right: $5.tblExpr(), Cond: $6.joinCond(), Hint: $3}
  7318    }
  7319  | table_ref JOIN table_ref join_qual
  7320    {
  7321      $$.val = &tree.JoinTableExpr{Left: $1.tblExpr(), Right: $3.tblExpr(), Cond: $4.joinCond()}
  7322    }
  7323  | table_ref NATURAL join_type opt_join_hint JOIN table_ref
  7324    {
  7325      $$.val = &tree.JoinTableExpr{JoinType: $3, Left: $1.tblExpr(), Right: $6.tblExpr(), Cond: tree.NaturalJoinCond{}, Hint: $4}
  7326    }
  7327  | table_ref NATURAL JOIN table_ref
  7328    {
  7329      $$.val = &tree.JoinTableExpr{Left: $1.tblExpr(), Right: $4.tblExpr(), Cond: tree.NaturalJoinCond{}}
  7330    }
  7331  
  7332  alias_clause:
  7333    AS table_alias_name opt_column_list
  7334    {
  7335      $$.val = tree.AliasClause{Alias: tree.Name($2), Cols: $3.nameList()}
  7336    }
  7337  | table_alias_name opt_column_list
  7338    {
  7339      $$.val = tree.AliasClause{Alias: tree.Name($1), Cols: $2.nameList()}
  7340    }
  7341  
  7342  opt_alias_clause:
  7343    alias_clause
  7344  | /* EMPTY */
  7345    {
  7346      $$.val = tree.AliasClause{}
  7347    }
  7348  
  7349  as_of_clause:
  7350    AS_LA OF SYSTEM TIME a_expr
  7351    {
  7352      $$.val = tree.AsOfClause{Expr: $5.expr()}
  7353    }
  7354  
  7355  opt_as_of_clause:
  7356    as_of_clause
  7357  | /* EMPTY */
  7358    {
  7359      $$.val = tree.AsOfClause{}
  7360    }
  7361  
  7362  join_type:
  7363    FULL join_outer
  7364    {
  7365      $$ = tree.AstFull
  7366    }
  7367  | LEFT join_outer
  7368    {
  7369      $$ = tree.AstLeft
  7370    }
  7371  | RIGHT join_outer
  7372    {
  7373      $$ = tree.AstRight
  7374    }
  7375  | INNER
  7376    {
  7377      $$ = tree.AstInner
  7378    }
  7379  
  7380  // OUTER is just noise...
  7381  join_outer:
  7382    OUTER {}
  7383  | /* EMPTY */ {}
  7384  
  7385  // Join hint specifies that the join in the query should use a
  7386  // specific method.
  7387  
  7388  // The semantics are as follows:
  7389  //  - HASH forces a hash join; in other words, it disables merge and lookup
  7390  //    join. A hash join is always possible; even if there are no equality
  7391  //    columns - we consider cartesian join a degenerate case of the hash join
  7392  //    (one bucket).
  7393  //  - MERGE forces a merge join, even if it requires resorting both sides of
  7394  //    the join.
  7395  //  - LOOKUP forces a lookup join into the right side; the right side must be
  7396  //    a table with a suitable index. `LOOKUP` can only be used with INNER and
  7397  //    LEFT joins (though this is not enforced by the syntax).
  7398  //  - If it is not possible to use the algorithm in the hint, an error is
  7399  //    returned.
  7400  //  - When a join hint is specified, the two tables will not be reordered
  7401  //    by the optimizer.
  7402  opt_join_hint:
  7403    HASH
  7404    {
  7405      $$ = tree.AstHash
  7406    }
  7407  | MERGE
  7408    {
  7409      $$ = tree.AstMerge
  7410    }
  7411  | LOOKUP
  7412    {
  7413      $$ = tree.AstLookup
  7414    }
  7415  | /* EMPTY */
  7416    {
  7417      $$ = ""
  7418    }
  7419  
  7420  // JOIN qualification clauses
  7421  // Possibilities are:
  7422  //      USING ( column list ) allows only unqualified column names,
  7423  //          which must match between tables.
  7424  //      ON expr allows more general qualifications.
  7425  //
  7426  // We return USING as a List node, while an ON-expr will not be a List.
  7427  join_qual:
  7428    USING '(' name_list ')'
  7429    {
  7430      $$.val = &tree.UsingJoinCond{Cols: $3.nameList()}
  7431    }
  7432  | ON a_expr
  7433    {
  7434      $$.val = &tree.OnJoinCond{Expr: $2.expr()}
  7435    }
  7436  
  7437  relation_expr:
  7438    table_name              { $$.val = $1.unresolvedObjectName() }
  7439  | table_name '*'          { $$.val = $1.unresolvedObjectName() }
  7440  | ONLY table_name         { $$.val = $2.unresolvedObjectName() }
  7441  | ONLY '(' table_name ')' { $$.val = $3.unresolvedObjectName() }
  7442  
  7443  relation_expr_list:
  7444    relation_expr
  7445    {
  7446      name := $1.unresolvedObjectName().ToTableName()
  7447      $$.val = tree.TableNames{name}
  7448    }
  7449  | relation_expr_list ',' relation_expr
  7450    {
  7451      name := $3.unresolvedObjectName().ToTableName()
  7452      $$.val = append($1.tableNames(), name)
  7453    }
  7454  
  7455  // Given "UPDATE foo set set ...", we have to decide without looking any
  7456  // further ahead whether the first "set" is an alias or the UPDATE's SET
  7457  // keyword. Since "set" is allowed as a column name both interpretations are
  7458  // feasible. We resolve the shift/reduce conflict by giving the first
  7459  // table_expr_opt_alias_idx production a higher precedence than the SET token
  7460  // has, causing the parser to prefer to reduce, in effect assuming that the SET
  7461  // is not an alias.
  7462  table_expr_opt_alias_idx:
  7463    table_name_opt_idx %prec UMINUS
  7464    {
  7465       $$.val = $1.tblExpr()
  7466    }
  7467  | table_name_opt_idx table_alias_name
  7468    {
  7469       alias := $1.tblExpr().(*tree.AliasedTableExpr)
  7470       alias.As = tree.AliasClause{Alias: tree.Name($2)}
  7471       $$.val = alias
  7472    }
  7473  | table_name_opt_idx AS table_alias_name
  7474    {
  7475       alias := $1.tblExpr().(*tree.AliasedTableExpr)
  7476       alias.As = tree.AliasClause{Alias: tree.Name($3)}
  7477       $$.val = alias
  7478    }
  7479  | numeric_table_ref opt_index_flags
  7480    {
  7481      /* SKIP DOC */
  7482      $$.val = &tree.AliasedTableExpr{
  7483        Expr: $1.tblExpr(),
  7484        IndexFlags: $2.indexFlags(),
  7485      }
  7486    }
  7487  
  7488  table_name_opt_idx:
  7489    table_name opt_index_flags
  7490    {
  7491      name := $1.unresolvedObjectName().ToTableName()
  7492      $$.val = &tree.AliasedTableExpr{
  7493        Expr: &name,
  7494        IndexFlags: $2.indexFlags(),
  7495      }
  7496    }
  7497  
  7498  where_clause:
  7499    WHERE a_expr
  7500    {
  7501      $$.val = $2.expr()
  7502    }
  7503  
  7504  opt_where_clause:
  7505    where_clause
  7506  | /* EMPTY */
  7507    {
  7508      $$.val = tree.Expr(nil)
  7509    }
  7510  
  7511  // Type syntax
  7512  //   SQL introduces a large amount of type-specific syntax.
  7513  //   Define individual clauses to handle these cases, and use
  7514  //   the generic case to handle regular type-extensible Postgres syntax.
  7515  //   - thomas 1997-10-10
  7516  
  7517  typename:
  7518    simple_typename opt_array_bounds
  7519    {
  7520      if bounds := $2.int32s(); bounds != nil {
  7521        var err error
  7522        $$.val, err = arrayOf($1.typeReference(), bounds)
  7523        if err != nil {
  7524          return setErr(sqllex, err)
  7525        }
  7526      } else {
  7527        $$.val = $1.typeReference()
  7528      }
  7529    }
  7530    // SQL standard syntax, currently only one-dimensional
  7531    // Undocumented but support for potential Postgres compat
  7532  | simple_typename ARRAY '[' ICONST ']' {
  7533      /* SKIP DOC */
  7534      var err error
  7535      $$.val, err = arrayOf($1.typeReference(), nil)
  7536      if err != nil {
  7537        return setErr(sqllex, err)
  7538      }
  7539    }
  7540  | simple_typename ARRAY '[' ICONST ']' '[' error { return unimplementedWithIssue(sqllex, 32552) }
  7541  | simple_typename ARRAY {
  7542      var err error
  7543      $$.val, err = arrayOf($1.typeReference(), nil)
  7544      if err != nil {
  7545        return setErr(sqllex, err)
  7546      }
  7547    }
  7548  
  7549  cast_target:
  7550    typename
  7551    {
  7552      $$.val = $1.typeReference()
  7553    }
  7554  
  7555  opt_array_bounds:
  7556    // TODO(justin): reintroduce multiple array bounds
  7557    // opt_array_bounds '[' ']' { $$.val = append($1.int32s(), -1) }
  7558    '[' ']' { $$.val = []int32{-1} }
  7559  | '[' ']' '[' error { return unimplementedWithIssue(sqllex, 32552) }
  7560  | '[' ICONST ']'
  7561    {
  7562      /* SKIP DOC */
  7563      bound, err := $2.numVal().AsInt32()
  7564      if err != nil {
  7565        return setErr(sqllex, err)
  7566      }
  7567      $$.val = []int32{bound}
  7568    }
  7569  | '[' ICONST ']' '[' error { return unimplementedWithIssue(sqllex, 32552) }
  7570  | /* EMPTY */ { $$.val = []int32(nil) }
  7571  
  7572  // general_type_name is a variant of type_or_function_name but does not
  7573  // include some extra keywords (like FAMILY) which cause ambiguity with
  7574  // parsing of typenames in certain contexts.
  7575  general_type_name:
  7576    type_function_name_no_crdb_extra
  7577  
  7578  // complex_type_name mirrors the rule for complex_db_object_name, but uses
  7579  // general_type_name rather than db_object_name_component to avoid conflicts.
  7580  complex_type_name:
  7581    general_type_name '.' unrestricted_name
  7582    {
  7583      aIdx := sqllex.(*lexer).NewAnnotation()
  7584      res, err := tree.NewUnresolvedObjectName(2, [3]string{$3, $1}, aIdx)
  7585      if err != nil { return setErr(sqllex, err) }
  7586      $$.val = res
  7587    }
  7588  | general_type_name '.' unrestricted_name '.' unrestricted_name
  7589    {
  7590      aIdx := sqllex.(*lexer).NewAnnotation()
  7591      res, err := tree.NewUnresolvedObjectName(3, [3]string{$5, $3, $1}, aIdx)
  7592      if err != nil { return setErr(sqllex, err) }
  7593      $$.val = res
  7594    }
  7595  
  7596  simple_typename:
  7597    general_type_name
  7598    {
  7599      /* FORCE DOC */
  7600      // See https://www.postgresql.org/docs/9.1/static/datatype-character.html
  7601      // Postgres supports a special character type named "char" (with the quotes)
  7602      // that is a single-character column type. It's used by system tables.
  7603      // Eventually this clause will be used to parse user-defined types as well,
  7604      // since their names can be quoted.
  7605      if $1 == "char" {
  7606        $$.val = types.MakeQChar(0)
  7607      } else if $1 == "serial" {
  7608          switch sqllex.(*lexer).nakedIntType.Width() {
  7609          case 32:
  7610            $$.val = &types.Serial4Type
  7611          default:
  7612            $$.val = &types.Serial8Type
  7613          }
  7614      } else {
  7615        // Check the the type is one of our "non-keyword" type names.
  7616        // Otherwise, package it up as a type reference for later.
  7617        var ok bool
  7618        var err error
  7619        var unimp int
  7620        $$.val, ok, unimp = types.TypeForNonKeywordTypeName($1)
  7621        if !ok {
  7622          switch unimp {
  7623            case 0:
  7624              // In this case, we don't think this type is one of our
  7625              // known unsupported types, so make a type reference for it.
  7626              aIdx := sqllex.(*lexer).NewAnnotation()
  7627              $$.val, err = tree.NewUnresolvedObjectName(1, [3]string{$1}, aIdx)
  7628              if err != nil { return setErr(sqllex, err) }
  7629            case -1:
  7630              return unimplemented(sqllex, "type name " + $1)
  7631            default:
  7632              return unimplementedWithIssueDetail(sqllex, unimp, $1)
  7633          }
  7634        }
  7635      }
  7636    }
  7637  | '@' iconst32
  7638    {
  7639      id := $2.int32()
  7640      $$.val = &tree.IDTypeReference{ID: uint32(id)}
  7641    }
  7642  | complex_type_name
  7643    {
  7644      $$.val = $1.typeReference()
  7645    }
  7646  | const_typename
  7647  | bit_with_length
  7648  | character_with_length
  7649  | interval_type
  7650  | POINT error { return unimplementedWithIssueDetail(sqllex, 21286, "point") } // needed or else it generates a syntax error.
  7651  | POLYGON error { return unimplementedWithIssueDetail(sqllex, 21286, "polygon") } // needed or else it generates a syntax error.
  7652  
  7653  geo_shape:
  7654    POINT { $$.val = geopb.Shape_Point }
  7655  | LINESTRING { $$.val = geopb.Shape_LineString }
  7656  | POLYGON { $$.val = geopb.Shape_Polygon }
  7657  | GEOMETRYCOLLECTION { $$.val = geopb.Shape_GeometryCollection }
  7658  | MULTIPOLYGON { $$.val = geopb.Shape_MultiPolygon }
  7659  | MULTILINESTRING { $$.val = geopb.Shape_MultiLineString }
  7660  | MULTIPOINT { $$.val = geopb.Shape_MultiPoint }
  7661  | GEOMETRY { $$.val = geopb.Shape_Geometry }
  7662  
  7663  const_geo:
  7664    GEOGRAPHY { $$.val = types.Geography }
  7665  | GEOMETRY  { $$.val = types.Geometry }
  7666  | GEOMETRY '(' geo_shape ')'
  7667    {
  7668      $$.val = types.MakeGeometry($3.geoFigure(), 0)
  7669    }
  7670  | GEOGRAPHY '(' geo_shape ')'
  7671    {
  7672      $$.val = types.MakeGeography($3.geoFigure(), 0)
  7673    }
  7674  | GEOMETRY '(' geo_shape ',' iconst32 ')'
  7675    {
  7676      $$.val = types.MakeGeometry($3.geoFigure(), geopb.SRID($5.int32()))
  7677    }
  7678  | GEOGRAPHY '(' geo_shape ',' iconst32 ')'
  7679    {
  7680      $$.val = types.MakeGeography($3.geoFigure(), geopb.SRID($5.int32()))
  7681    }
  7682  
  7683  // We have a separate const_typename to allow defaulting fixed-length types
  7684  // such as CHAR() and BIT() to an unspecified length. SQL9x requires that these
  7685  // default to a length of one, but this makes no sense for constructs like CHAR
  7686  // 'hi' and BIT '0101', where there is an obvious better choice to make. Note
  7687  // that interval_type is not included here since it must be pushed up higher
  7688  // in the rules to accommodate the postfix options (e.g. INTERVAL '1'
  7689  // YEAR). Likewise, we have to handle the generic-type-name case in
  7690  // a_expr_const to avoid premature reduce/reduce conflicts against function
  7691  // names.
  7692  const_typename:
  7693    numeric
  7694  | bit_without_length
  7695  | character_without_length
  7696  | const_datetime
  7697  | const_geo
  7698  
  7699  opt_numeric_modifiers:
  7700    '(' iconst32 ')'
  7701    {
  7702      dec, err := newDecimal($2.int32(), 0)
  7703      if err != nil {
  7704        return setErr(sqllex, err)
  7705      }
  7706      $$.val = dec
  7707    }
  7708  | '(' iconst32 ',' iconst32 ')'
  7709    {
  7710      dec, err := newDecimal($2.int32(), $4.int32())
  7711      if err != nil {
  7712        return setErr(sqllex, err)
  7713      }
  7714      $$.val = dec
  7715    }
  7716  | /* EMPTY */
  7717    {
  7718      $$.val = nil
  7719    }
  7720  
  7721  // SQL numeric data types
  7722  numeric:
  7723    INT
  7724    {
  7725      $$.val = sqllex.(*lexer).nakedIntType
  7726    }
  7727  | INTEGER
  7728    {
  7729      $$.val = sqllex.(*lexer).nakedIntType
  7730    }
  7731  | SMALLINT
  7732    {
  7733      $$.val = types.Int2
  7734    }
  7735  | BIGINT
  7736    {
  7737      $$.val = types.Int
  7738    }
  7739  | REAL
  7740    {
  7741      $$.val = types.Float4
  7742    }
  7743  | FLOAT opt_float
  7744    {
  7745      $$.val = $2.colType()
  7746    }
  7747  | DOUBLE PRECISION
  7748    {
  7749      $$.val = types.Float
  7750    }
  7751  | DECIMAL opt_numeric_modifiers
  7752    {
  7753      typ := $2.colType()
  7754      if typ == nil {
  7755        typ = types.Decimal
  7756      }
  7757      $$.val = typ
  7758    }
  7759  | DEC opt_numeric_modifiers
  7760    {
  7761      typ := $2.colType()
  7762      if typ == nil {
  7763        typ = types.Decimal
  7764      }
  7765      $$.val = typ
  7766    }
  7767  | NUMERIC opt_numeric_modifiers
  7768    {
  7769      typ := $2.colType()
  7770      if typ == nil {
  7771        typ = types.Decimal
  7772      }
  7773      $$.val = typ
  7774    }
  7775  | BOOLEAN
  7776    {
  7777      $$.val = types.Bool
  7778    }
  7779  
  7780  opt_float:
  7781    '(' ICONST ')'
  7782    {
  7783      nv := $2.numVal()
  7784      prec, err := nv.AsInt64()
  7785      if err != nil {
  7786        return setErr(sqllex, err)
  7787      }
  7788      typ, err := newFloat(prec)
  7789      if err != nil {
  7790        return setErr(sqllex, err)
  7791      }
  7792      $$.val = typ
  7793    }
  7794  | /* EMPTY */
  7795    {
  7796      $$.val = types.Float
  7797    }
  7798  
  7799  bit_with_length:
  7800    BIT opt_varying '(' iconst32 ')'
  7801    {
  7802      bit, err := newBitType($4.int32(), $2.bool())
  7803      if err != nil { return setErr(sqllex, err) }
  7804      $$.val = bit
  7805    }
  7806  | VARBIT '(' iconst32 ')'
  7807    {
  7808      bit, err := newBitType($3.int32(), true)
  7809      if err != nil { return setErr(sqllex, err) }
  7810      $$.val = bit
  7811    }
  7812  
  7813  bit_without_length:
  7814    BIT
  7815    {
  7816      $$.val = types.MakeBit(1)
  7817    }
  7818  | BIT VARYING
  7819    {
  7820      $$.val = types.VarBit
  7821    }
  7822  | VARBIT
  7823    {
  7824      $$.val = types.VarBit
  7825    }
  7826  
  7827  character_with_length:
  7828    character_base '(' iconst32 ')'
  7829    {
  7830      colTyp := *$1.colType()
  7831      n := $3.int32()
  7832      if n == 0 {
  7833        sqllex.Error(fmt.Sprintf("length for type %s must be at least 1", colTyp.SQLString()))
  7834        return 1
  7835      }
  7836      $$.val = types.MakeScalar(types.StringFamily, colTyp.Oid(), colTyp.Precision(), n, colTyp.Locale())
  7837    }
  7838  
  7839  character_without_length:
  7840    character_base
  7841    {
  7842      $$.val = $1.colType()
  7843    }
  7844  
  7845  character_base:
  7846    char_aliases
  7847    {
  7848      $$.val = types.MakeChar(1)
  7849    }
  7850  | char_aliases VARYING
  7851    {
  7852      $$.val = types.VarChar
  7853    }
  7854  | VARCHAR
  7855    {
  7856      $$.val = types.VarChar
  7857    }
  7858  | STRING
  7859    {
  7860      $$.val = types.String
  7861    }
  7862  
  7863  char_aliases:
  7864    CHAR
  7865  | CHARACTER
  7866  
  7867  opt_varying:
  7868    VARYING     { $$.val = true }
  7869  | /* EMPTY */ { $$.val = false }
  7870  
  7871  // SQL date/time types
  7872  const_datetime:
  7873    DATE
  7874    {
  7875      $$.val = types.Date
  7876    }
  7877  | TIME opt_timezone
  7878    {
  7879      if $2.bool() {
  7880        $$.val = types.TimeTZ
  7881      } else {
  7882        $$.val = types.Time
  7883      }
  7884    }
  7885  | TIME '(' iconst32 ')' opt_timezone
  7886    {
  7887      prec := $3.int32()
  7888      if prec < 0 || prec > 6 {
  7889        sqllex.Error(fmt.Sprintf("precision %d out of range", prec))
  7890        return 1
  7891      }
  7892      if $5.bool() {
  7893        $$.val = types.MakeTimeTZ(prec)
  7894      } else {
  7895        $$.val = types.MakeTime(prec)
  7896      }
  7897    }
  7898  | TIMETZ                             { $$.val = types.TimeTZ }
  7899  | TIMETZ '(' iconst32 ')'
  7900    {
  7901      prec := $3.int32()
  7902      if prec < 0 || prec > 6 {
  7903        sqllex.Error(fmt.Sprintf("precision %d out of range", prec))
  7904        return 1
  7905      }
  7906      $$.val = types.MakeTimeTZ(prec)
  7907    }
  7908  | TIMESTAMP opt_timezone
  7909    {
  7910      if $2.bool() {
  7911        $$.val = types.TimestampTZ
  7912      } else {
  7913        $$.val = types.Timestamp
  7914      }
  7915    }
  7916  | TIMESTAMP '(' iconst32 ')' opt_timezone
  7917    {
  7918      prec := $3.int32()
  7919      if prec < 0 || prec > 6 {
  7920        sqllex.Error(fmt.Sprintf("precision %d out of range", prec))
  7921        return 1
  7922      }
  7923      if $5.bool() {
  7924        $$.val = types.MakeTimestampTZ(prec)
  7925      } else {
  7926        $$.val = types.MakeTimestamp(prec)
  7927      }
  7928    }
  7929  | TIMESTAMPTZ
  7930    {
  7931      $$.val = types.TimestampTZ
  7932    }
  7933  | TIMESTAMPTZ '(' iconst32 ')'
  7934    {
  7935      prec := $3.int32()
  7936      if prec < 0 || prec > 6 {
  7937        sqllex.Error(fmt.Sprintf("precision %d out of range", prec))
  7938        return 1
  7939      }
  7940      $$.val = types.MakeTimestampTZ(prec)
  7941    }
  7942  
  7943  opt_timezone:
  7944    WITH_LA TIME ZONE { $$.val = true; }
  7945  | WITHOUT TIME ZONE { $$.val = false; }
  7946  | /*EMPTY*/         { $$.val = false; }
  7947  
  7948  interval_type:
  7949    INTERVAL
  7950    {
  7951      $$.val = types.Interval
  7952    }
  7953  | INTERVAL interval_qualifier
  7954    {
  7955      $$.val = types.MakeInterval($2.intervalTypeMetadata())
  7956    }
  7957  | INTERVAL '(' iconst32 ')'
  7958    {
  7959      prec := $3.int32()
  7960      if prec < 0 || prec > 6 {
  7961        sqllex.Error(fmt.Sprintf("precision %d out of range", prec))
  7962        return 1
  7963      }
  7964      $$.val = types.MakeInterval(types.IntervalTypeMetadata{Precision: prec, PrecisionIsSet: true})
  7965    }
  7966  
  7967  interval_qualifier:
  7968    YEAR
  7969    {
  7970      $$.val = types.IntervalTypeMetadata{
  7971        DurationField: types.IntervalDurationField{
  7972          DurationType: types.IntervalDurationType_YEAR,
  7973        },
  7974      }
  7975    }
  7976  | MONTH
  7977    {
  7978      $$.val = types.IntervalTypeMetadata{
  7979        DurationField: types.IntervalDurationField{
  7980          DurationType: types.IntervalDurationType_MONTH,
  7981        },
  7982      }
  7983    }
  7984  | DAY
  7985    {
  7986      $$.val = types.IntervalTypeMetadata{
  7987        DurationField: types.IntervalDurationField{
  7988          DurationType: types.IntervalDurationType_DAY,
  7989        },
  7990      }
  7991    }
  7992  | HOUR
  7993    {
  7994      $$.val = types.IntervalTypeMetadata{
  7995        DurationField: types.IntervalDurationField{
  7996          DurationType: types.IntervalDurationType_HOUR,
  7997        },
  7998      }
  7999    }
  8000  | MINUTE
  8001    {
  8002      $$.val = types.IntervalTypeMetadata{
  8003        DurationField: types.IntervalDurationField{
  8004          DurationType: types.IntervalDurationType_MINUTE,
  8005        },
  8006      }
  8007    }
  8008  | interval_second
  8009    {
  8010      $$.val = $1.intervalTypeMetadata()
  8011    }
  8012  // Like Postgres, we ignore the left duration field. See explanation:
  8013  // https://www.postgresql.org/message-id/20110510040219.GD5617%40tornado.gateway.2wire.net
  8014  | YEAR TO MONTH
  8015    {
  8016      $$.val = types.IntervalTypeMetadata{
  8017        DurationField: types.IntervalDurationField{
  8018          FromDurationType: types.IntervalDurationType_YEAR,
  8019          DurationType: types.IntervalDurationType_MONTH,
  8020        },
  8021      }
  8022    }
  8023  | DAY TO HOUR
  8024    {
  8025      $$.val = types.IntervalTypeMetadata{
  8026        DurationField: types.IntervalDurationField{
  8027          FromDurationType: types.IntervalDurationType_DAY,
  8028          DurationType: types.IntervalDurationType_HOUR,
  8029        },
  8030      }
  8031    }
  8032  | DAY TO MINUTE
  8033    {
  8034      $$.val = types.IntervalTypeMetadata{
  8035        DurationField: types.IntervalDurationField{
  8036          FromDurationType: types.IntervalDurationType_DAY,
  8037          DurationType: types.IntervalDurationType_MINUTE,
  8038        },
  8039      }
  8040    }
  8041  | DAY TO interval_second
  8042    {
  8043      ret := $3.intervalTypeMetadata()
  8044      ret.DurationField.FromDurationType = types.IntervalDurationType_DAY
  8045      $$.val = ret
  8046    }
  8047  | HOUR TO MINUTE
  8048    {
  8049      $$.val = types.IntervalTypeMetadata{
  8050        DurationField: types.IntervalDurationField{
  8051          FromDurationType: types.IntervalDurationType_HOUR,
  8052          DurationType: types.IntervalDurationType_MINUTE,
  8053        },
  8054      }
  8055    }
  8056  | HOUR TO interval_second
  8057    {
  8058      ret := $3.intervalTypeMetadata()
  8059      ret.DurationField.FromDurationType = types.IntervalDurationType_HOUR
  8060      $$.val = ret
  8061    }
  8062  | MINUTE TO interval_second
  8063    {
  8064      $$.val = $3.intervalTypeMetadata()
  8065      ret := $3.intervalTypeMetadata()
  8066      ret.DurationField.FromDurationType = types.IntervalDurationType_MINUTE
  8067      $$.val = ret
  8068    }
  8069  
  8070  opt_interval_qualifier:
  8071    interval_qualifier
  8072  | /* EMPTY */
  8073    {
  8074      $$.val = nil
  8075    }
  8076  
  8077  interval_second:
  8078    SECOND
  8079    {
  8080      $$.val = types.IntervalTypeMetadata{
  8081        DurationField: types.IntervalDurationField{
  8082          DurationType: types.IntervalDurationType_SECOND,
  8083        },
  8084      }
  8085    }
  8086  | SECOND '(' iconst32 ')'
  8087    {
  8088      prec := $3.int32()
  8089      if prec < 0 || prec > 6 {
  8090        sqllex.Error(fmt.Sprintf("precision %d out of range", prec))
  8091        return 1
  8092      }
  8093      $$.val = types.IntervalTypeMetadata{
  8094        DurationField: types.IntervalDurationField{
  8095          DurationType: types.IntervalDurationType_SECOND,
  8096        },
  8097        PrecisionIsSet: true,
  8098        Precision: prec,
  8099      }
  8100    }
  8101  
  8102  // General expressions. This is the heart of the expression syntax.
  8103  //
  8104  // We have two expression types: a_expr is the unrestricted kind, and b_expr is
  8105  // a subset that must be used in some places to avoid shift/reduce conflicts.
  8106  // For example, we can't do BETWEEN as "BETWEEN a_expr AND a_expr" because that
  8107  // use of AND conflicts with AND as a boolean operator. So, b_expr is used in
  8108  // BETWEEN and we remove boolean keywords from b_expr.
  8109  //
  8110  // Note that '(' a_expr ')' is a b_expr, so an unrestricted expression can
  8111  // always be used by surrounding it with parens.
  8112  //
  8113  // c_expr is all the productions that are common to a_expr and b_expr; it's
  8114  // factored out just to eliminate redundant coding.
  8115  //
  8116  // Be careful of productions involving more than one terminal token. By
  8117  // default, bison will assign such productions the precedence of their last
  8118  // terminal, but in nearly all cases you want it to be the precedence of the
  8119  // first terminal instead; otherwise you will not get the behavior you expect!
  8120  // So we use %prec annotations freely to set precedences.
  8121  a_expr:
  8122    c_expr
  8123  | a_expr TYPECAST cast_target
  8124    {
  8125      $$.val = &tree.CastExpr{Expr: $1.expr(), Type: $3.typeReference(), SyntaxMode: tree.CastShort}
  8126    }
  8127  | a_expr TYPEANNOTATE typename
  8128    {
  8129      $$.val = &tree.AnnotateTypeExpr{Expr: $1.expr(), Type: $3.typeReference(), SyntaxMode: tree.AnnotateShort}
  8130    }
  8131  | a_expr COLLATE collation_name
  8132    {
  8133      $$.val = &tree.CollateExpr{Expr: $1.expr(), Locale: $3}
  8134    }
  8135  | a_expr AT TIME ZONE a_expr %prec AT
  8136    {
  8137      $$.val = &tree.FuncExpr{Func: tree.WrapFunction("timezone"), Exprs: tree.Exprs{$5.expr(), $1.expr()}}
  8138    }
  8139    // These operators must be called out explicitly in order to make use of
  8140    // bison's automatic operator-precedence handling. All other operator names
  8141    // are handled by the generic productions using "OP", below; and all those
  8142    // operators will have the same precedence.
  8143    //
  8144    // If you add more explicitly-known operators, be sure to add them also to
  8145    // b_expr and to the math_op list below.
  8146  | '+' a_expr %prec UMINUS
  8147    {
  8148      // Unary plus is a no-op. Desugar immediately.
  8149      $$.val = $2.expr()
  8150    }
  8151  | '-' a_expr %prec UMINUS
  8152    {
  8153      $$.val = unaryNegation($2.expr())
  8154    }
  8155  | '~' a_expr %prec UMINUS
  8156    {
  8157      $$.val = &tree.UnaryExpr{Operator: tree.UnaryComplement, Expr: $2.expr()}
  8158    }
  8159  | SQRT a_expr
  8160    {
  8161      $$.val = &tree.UnaryExpr{Operator: tree.UnarySqrt, Expr: $2.expr()}
  8162    }
  8163  | CBRT a_expr
  8164    {
  8165      $$.val = &tree.UnaryExpr{Operator: tree.UnaryCbrt, Expr: $2.expr()}
  8166    }
  8167  | a_expr '+' a_expr
  8168    {
  8169      $$.val = &tree.BinaryExpr{Operator: tree.Plus, Left: $1.expr(), Right: $3.expr()}
  8170    }
  8171  | a_expr '-' a_expr
  8172    {
  8173      $$.val = &tree.BinaryExpr{Operator: tree.Minus, Left: $1.expr(), Right: $3.expr()}
  8174    }
  8175  | a_expr '*' a_expr
  8176    {
  8177      $$.val = &tree.BinaryExpr{Operator: tree.Mult, Left: $1.expr(), Right: $3.expr()}
  8178    }
  8179  | a_expr '/' a_expr
  8180    {
  8181      $$.val = &tree.BinaryExpr{Operator: tree.Div, Left: $1.expr(), Right: $3.expr()}
  8182    }
  8183  | a_expr FLOORDIV a_expr
  8184    {
  8185      $$.val = &tree.BinaryExpr{Operator: tree.FloorDiv, Left: $1.expr(), Right: $3.expr()}
  8186    }
  8187  | a_expr '%' a_expr
  8188    {
  8189      $$.val = &tree.BinaryExpr{Operator: tree.Mod, Left: $1.expr(), Right: $3.expr()}
  8190    }
  8191  | a_expr '^' a_expr
  8192    {
  8193      $$.val = &tree.BinaryExpr{Operator: tree.Pow, Left: $1.expr(), Right: $3.expr()}
  8194    }
  8195  | a_expr '#' a_expr
  8196    {
  8197      $$.val = &tree.BinaryExpr{Operator: tree.Bitxor, Left: $1.expr(), Right: $3.expr()}
  8198    }
  8199  | a_expr '&' a_expr
  8200    {
  8201      $$.val = &tree.BinaryExpr{Operator: tree.Bitand, Left: $1.expr(), Right: $3.expr()}
  8202    }
  8203  | a_expr '|' a_expr
  8204    {
  8205      $$.val = &tree.BinaryExpr{Operator: tree.Bitor, Left: $1.expr(), Right: $3.expr()}
  8206    }
  8207  | a_expr '<' a_expr
  8208    {
  8209      $$.val = &tree.ComparisonExpr{Operator: tree.LT, Left: $1.expr(), Right: $3.expr()}
  8210    }
  8211  | a_expr '>' a_expr
  8212    {
  8213      $$.val = &tree.ComparisonExpr{Operator: tree.GT, Left: $1.expr(), Right: $3.expr()}
  8214    }
  8215  | a_expr '?' a_expr
  8216    {
  8217      $$.val = &tree.ComparisonExpr{Operator: tree.JSONExists, Left: $1.expr(), Right: $3.expr()}
  8218    }
  8219  | a_expr JSON_SOME_EXISTS a_expr
  8220    {
  8221      $$.val = &tree.ComparisonExpr{Operator: tree.JSONSomeExists, Left: $1.expr(), Right: $3.expr()}
  8222    }
  8223  | a_expr JSON_ALL_EXISTS a_expr
  8224    {
  8225      $$.val = &tree.ComparisonExpr{Operator: tree.JSONAllExists, Left: $1.expr(), Right: $3.expr()}
  8226    }
  8227  | a_expr CONTAINS a_expr
  8228    {
  8229      $$.val = &tree.ComparisonExpr{Operator: tree.Contains, Left: $1.expr(), Right: $3.expr()}
  8230    }
  8231  | a_expr CONTAINED_BY a_expr
  8232    {
  8233      $$.val = &tree.ComparisonExpr{Operator: tree.ContainedBy, Left: $1.expr(), Right: $3.expr()}
  8234    }
  8235  | a_expr '=' a_expr
  8236    {
  8237      $$.val = &tree.ComparisonExpr{Operator: tree.EQ, Left: $1.expr(), Right: $3.expr()}
  8238    }
  8239  | a_expr CONCAT a_expr
  8240    {
  8241      $$.val = &tree.BinaryExpr{Operator: tree.Concat, Left: $1.expr(), Right: $3.expr()}
  8242    }
  8243  | a_expr LSHIFT a_expr
  8244    {
  8245      $$.val = &tree.BinaryExpr{Operator: tree.LShift, Left: $1.expr(), Right: $3.expr()}
  8246    }
  8247  | a_expr RSHIFT a_expr
  8248    {
  8249      $$.val = &tree.BinaryExpr{Operator: tree.RShift, Left: $1.expr(), Right: $3.expr()}
  8250    }
  8251  | a_expr FETCHVAL a_expr
  8252    {
  8253      $$.val = &tree.BinaryExpr{Operator: tree.JSONFetchVal, Left: $1.expr(), Right: $3.expr()}
  8254    }
  8255  | a_expr FETCHTEXT a_expr
  8256    {
  8257      $$.val = &tree.BinaryExpr{Operator: tree.JSONFetchText, Left: $1.expr(), Right: $3.expr()}
  8258    }
  8259  | a_expr FETCHVAL_PATH a_expr
  8260    {
  8261      $$.val = &tree.BinaryExpr{Operator: tree.JSONFetchValPath, Left: $1.expr(), Right: $3.expr()}
  8262    }
  8263  | a_expr FETCHTEXT_PATH a_expr
  8264    {
  8265      $$.val = &tree.BinaryExpr{Operator: tree.JSONFetchTextPath, Left: $1.expr(), Right: $3.expr()}
  8266    }
  8267  | a_expr REMOVE_PATH a_expr
  8268    {
  8269      $$.val = &tree.FuncExpr{Func: tree.WrapFunction("json_remove_path"), Exprs: tree.Exprs{$1.expr(), $3.expr()}}
  8270    }
  8271  | a_expr INET_CONTAINED_BY_OR_EQUALS a_expr
  8272    {
  8273      $$.val = &tree.FuncExpr{Func: tree.WrapFunction("inet_contained_by_or_equals"), Exprs: tree.Exprs{$1.expr(), $3.expr()}}
  8274    }
  8275  | a_expr AND_AND a_expr
  8276    {
  8277      $$.val = &tree.ComparisonExpr{Operator: tree.Overlaps, Left: $1.expr(), Right: $3.expr()}
  8278    }
  8279  | a_expr INET_CONTAINS_OR_EQUALS a_expr
  8280    {
  8281      $$.val = &tree.FuncExpr{Func: tree.WrapFunction("inet_contains_or_equals"), Exprs: tree.Exprs{$1.expr(), $3.expr()}}
  8282    }
  8283  | a_expr LESS_EQUALS a_expr
  8284    {
  8285      $$.val = &tree.ComparisonExpr{Operator: tree.LE, Left: $1.expr(), Right: $3.expr()}
  8286    }
  8287  | a_expr GREATER_EQUALS a_expr
  8288    {
  8289      $$.val = &tree.ComparisonExpr{Operator: tree.GE, Left: $1.expr(), Right: $3.expr()}
  8290    }
  8291  | a_expr NOT_EQUALS a_expr
  8292    {
  8293      $$.val = &tree.ComparisonExpr{Operator: tree.NE, Left: $1.expr(), Right: $3.expr()}
  8294    }
  8295  | a_expr AND a_expr
  8296    {
  8297      $$.val = &tree.AndExpr{Left: $1.expr(), Right: $3.expr()}
  8298    }
  8299  | a_expr OR a_expr
  8300    {
  8301      $$.val = &tree.OrExpr{Left: $1.expr(), Right: $3.expr()}
  8302    }
  8303  | NOT a_expr
  8304    {
  8305      $$.val = &tree.NotExpr{Expr: $2.expr()}
  8306    }
  8307  | NOT_LA a_expr %prec NOT
  8308    {
  8309      $$.val = &tree.NotExpr{Expr: $2.expr()}
  8310    }
  8311  | a_expr LIKE a_expr
  8312    {
  8313      $$.val = &tree.ComparisonExpr{Operator: tree.Like, Left: $1.expr(), Right: $3.expr()}
  8314    }
  8315  | a_expr LIKE a_expr ESCAPE a_expr %prec ESCAPE
  8316    {
  8317      $$.val = &tree.FuncExpr{Func: tree.WrapFunction("like_escape"), Exprs: tree.Exprs{$1.expr(), $3.expr(), $5.expr()}}
  8318    }
  8319  | a_expr NOT_LA LIKE a_expr %prec NOT_LA
  8320    {
  8321      $$.val = &tree.ComparisonExpr{Operator: tree.NotLike, Left: $1.expr(), Right: $4.expr()}
  8322    }
  8323  | a_expr NOT_LA LIKE a_expr ESCAPE a_expr %prec ESCAPE
  8324   {
  8325     $$.val = &tree.FuncExpr{Func: tree.WrapFunction("not_like_escape"), Exprs: tree.Exprs{$1.expr(), $4.expr(), $6.expr()}}
  8326   }
  8327  | a_expr ILIKE a_expr
  8328    {
  8329      $$.val = &tree.ComparisonExpr{Operator: tree.ILike, Left: $1.expr(), Right: $3.expr()}
  8330    }
  8331  | a_expr ILIKE a_expr ESCAPE a_expr %prec ESCAPE
  8332    {
  8333      $$.val = &tree.FuncExpr{Func: tree.WrapFunction("ilike_escape"), Exprs: tree.Exprs{$1.expr(), $3.expr(), $5.expr()}}
  8334    }
  8335  | a_expr NOT_LA ILIKE a_expr %prec NOT_LA
  8336    {
  8337      $$.val = &tree.ComparisonExpr{Operator: tree.NotILike, Left: $1.expr(), Right: $4.expr()}
  8338    }
  8339  | a_expr NOT_LA ILIKE a_expr ESCAPE a_expr %prec ESCAPE
  8340   {
  8341     $$.val = &tree.FuncExpr{Func: tree.WrapFunction("not_ilike_escape"), Exprs: tree.Exprs{$1.expr(), $4.expr(), $6.expr()}}
  8342   }
  8343  | a_expr SIMILAR TO a_expr %prec SIMILAR
  8344    {
  8345      $$.val = &tree.ComparisonExpr{Operator: tree.SimilarTo, Left: $1.expr(), Right: $4.expr()}
  8346    }
  8347  | a_expr SIMILAR TO a_expr ESCAPE a_expr %prec ESCAPE
  8348    {
  8349      $$.val = &tree.FuncExpr{Func: tree.WrapFunction("similar_to_escape"), Exprs: tree.Exprs{$1.expr(), $4.expr(), $6.expr()}}
  8350    }
  8351  | a_expr NOT_LA SIMILAR TO a_expr %prec NOT_LA
  8352    {
  8353      $$.val = &tree.ComparisonExpr{Operator: tree.NotSimilarTo, Left: $1.expr(), Right: $5.expr()}
  8354    }
  8355  | a_expr NOT_LA SIMILAR TO a_expr ESCAPE a_expr %prec ESCAPE
  8356    {
  8357      $$.val = &tree.FuncExpr{Func: tree.WrapFunction("not_similar_to_escape"), Exprs: tree.Exprs{$1.expr(), $5.expr(), $7.expr()}}
  8358    }
  8359  | a_expr '~' a_expr
  8360    {
  8361      $$.val = &tree.ComparisonExpr{Operator: tree.RegMatch, Left: $1.expr(), Right: $3.expr()}
  8362    }
  8363  | a_expr NOT_REGMATCH a_expr
  8364    {
  8365      $$.val = &tree.ComparisonExpr{Operator: tree.NotRegMatch, Left: $1.expr(), Right: $3.expr()}
  8366    }
  8367  | a_expr REGIMATCH a_expr
  8368    {
  8369      $$.val = &tree.ComparisonExpr{Operator: tree.RegIMatch, Left: $1.expr(), Right: $3.expr()}
  8370    }
  8371  | a_expr NOT_REGIMATCH a_expr
  8372    {
  8373      $$.val = &tree.ComparisonExpr{Operator: tree.NotRegIMatch, Left: $1.expr(), Right: $3.expr()}
  8374    }
  8375  | a_expr IS NAN %prec IS
  8376    {
  8377      $$.val = &tree.ComparisonExpr{Operator: tree.EQ, Left: $1.expr(), Right: tree.NewStrVal("NaN")}
  8378    }
  8379  | a_expr IS NOT NAN %prec IS
  8380    {
  8381      $$.val = &tree.ComparisonExpr{Operator: tree.NE, Left: $1.expr(), Right: tree.NewStrVal("NaN")}
  8382    }
  8383  | a_expr IS NULL %prec IS
  8384    {
  8385      $$.val = &tree.IsNullExpr{Expr: $1.expr()}
  8386    }
  8387  | a_expr ISNULL %prec IS
  8388    {
  8389      $$.val = &tree.IsNullExpr{Expr: $1.expr()}
  8390    }
  8391  | a_expr IS NOT NULL %prec IS
  8392    {
  8393      $$.val = &tree.IsNotNullExpr{Expr: $1.expr()}
  8394    }
  8395  | a_expr NOTNULL %prec IS
  8396    {
  8397      $$.val = &tree.IsNotNullExpr{Expr: $1.expr()}
  8398    }
  8399  | row OVERLAPS row { return unimplemented(sqllex, "overlaps") }
  8400  | a_expr IS TRUE %prec IS
  8401    {
  8402      $$.val = &tree.ComparisonExpr{Operator: tree.IsNotDistinctFrom, Left: $1.expr(), Right: tree.MakeDBool(true)}
  8403    }
  8404  | a_expr IS NOT TRUE %prec IS
  8405    {
  8406      $$.val = &tree.ComparisonExpr{Operator: tree.IsDistinctFrom, Left: $1.expr(), Right: tree.MakeDBool(true)}
  8407    }
  8408  | a_expr IS FALSE %prec IS
  8409    {
  8410      $$.val = &tree.ComparisonExpr{Operator: tree.IsNotDistinctFrom, Left: $1.expr(), Right: tree.MakeDBool(false)}
  8411    }
  8412  | a_expr IS NOT FALSE %prec IS
  8413    {
  8414      $$.val = &tree.ComparisonExpr{Operator: tree.IsDistinctFrom, Left: $1.expr(), Right: tree.MakeDBool(false)}
  8415    }
  8416  | a_expr IS UNKNOWN %prec IS
  8417    {
  8418      $$.val = &tree.ComparisonExpr{Operator: tree.IsNotDistinctFrom, Left: $1.expr(), Right: tree.DNull}
  8419    }
  8420  | a_expr IS NOT UNKNOWN %prec IS
  8421    {
  8422      $$.val = &tree.ComparisonExpr{Operator: tree.IsDistinctFrom, Left: $1.expr(), Right: tree.DNull}
  8423    }
  8424  | a_expr IS DISTINCT FROM a_expr %prec IS
  8425    {
  8426      $$.val = &tree.ComparisonExpr{Operator: tree.IsDistinctFrom, Left: $1.expr(), Right: $5.expr()}
  8427    }
  8428  | a_expr IS NOT DISTINCT FROM a_expr %prec IS
  8429    {
  8430      $$.val = &tree.ComparisonExpr{Operator: tree.IsNotDistinctFrom, Left: $1.expr(), Right: $6.expr()}
  8431    }
  8432  | a_expr IS OF '(' type_list ')' %prec IS
  8433    {
  8434      $$.val = &tree.IsOfTypeExpr{Expr: $1.expr(), Types: $5.typeReferences()}
  8435    }
  8436  | a_expr IS NOT OF '(' type_list ')' %prec IS
  8437    {
  8438      $$.val = &tree.IsOfTypeExpr{Not: true, Expr: $1.expr(), Types: $6.typeReferences()}
  8439    }
  8440  | a_expr BETWEEN opt_asymmetric b_expr AND a_expr %prec BETWEEN
  8441    {
  8442      $$.val = &tree.RangeCond{Left: $1.expr(), From: $4.expr(), To: $6.expr()}
  8443    }
  8444  | a_expr NOT_LA BETWEEN opt_asymmetric b_expr AND a_expr %prec NOT_LA
  8445    {
  8446      $$.val = &tree.RangeCond{Not: true, Left: $1.expr(), From: $5.expr(), To: $7.expr()}
  8447    }
  8448  | a_expr BETWEEN SYMMETRIC b_expr AND a_expr %prec BETWEEN
  8449    {
  8450      $$.val = &tree.RangeCond{Symmetric: true, Left: $1.expr(), From: $4.expr(), To: $6.expr()}
  8451    }
  8452  | a_expr NOT_LA BETWEEN SYMMETRIC b_expr AND a_expr %prec NOT_LA
  8453    {
  8454      $$.val = &tree.RangeCond{Not: true, Symmetric: true, Left: $1.expr(), From: $5.expr(), To: $7.expr()}
  8455    }
  8456  | a_expr IN in_expr
  8457    {
  8458      $$.val = &tree.ComparisonExpr{Operator: tree.In, Left: $1.expr(), Right: $3.expr()}
  8459    }
  8460  | a_expr NOT_LA IN in_expr %prec NOT_LA
  8461    {
  8462      $$.val = &tree.ComparisonExpr{Operator: tree.NotIn, Left: $1.expr(), Right: $4.expr()}
  8463    }
  8464  | a_expr subquery_op sub_type a_expr %prec CONCAT
  8465    {
  8466      op := $3.cmpOp()
  8467      subOp := $2.op()
  8468      subOpCmp, ok := subOp.(tree.ComparisonOperator)
  8469      if !ok {
  8470        sqllex.Error(fmt.Sprintf("%s %s <array> is invalid because %q is not a boolean operator",
  8471          subOp, op, subOp))
  8472        return 1
  8473      }
  8474      $$.val = &tree.ComparisonExpr{
  8475        Operator: op,
  8476        SubOperator: subOpCmp,
  8477        Left: $1.expr(),
  8478        Right: $4.expr(),
  8479      }
  8480    }
  8481  | DEFAULT
  8482    {
  8483      $$.val = tree.DefaultVal{}
  8484    }
  8485  // The UNIQUE predicate is a standard SQL feature but not yet implemented
  8486  // in PostgreSQL (as of 10.5).
  8487  | UNIQUE '(' error { return unimplemented(sqllex, "UNIQUE predicate") }
  8488  
  8489  // Restricted expressions
  8490  //
  8491  // b_expr is a subset of the complete expression syntax defined by a_expr.
  8492  //
  8493  // Presently, AND, NOT, IS, and IN are the a_expr keywords that would cause
  8494  // trouble in the places where b_expr is used. For simplicity, we just
  8495  // eliminate all the boolean-keyword-operator productions from b_expr.
  8496  b_expr:
  8497    c_expr
  8498  | b_expr TYPECAST cast_target
  8499    {
  8500      $$.val = &tree.CastExpr{Expr: $1.expr(), Type: $3.typeReference(), SyntaxMode: tree.CastShort}
  8501    }
  8502  | b_expr TYPEANNOTATE typename
  8503    {
  8504      $$.val = &tree.AnnotateTypeExpr{Expr: $1.expr(), Type: $3.typeReference(), SyntaxMode: tree.AnnotateShort}
  8505    }
  8506  | '+' b_expr %prec UMINUS
  8507    {
  8508      $$.val = $2.expr()
  8509    }
  8510  | '-' b_expr %prec UMINUS
  8511    {
  8512      $$.val = unaryNegation($2.expr())
  8513    }
  8514  | '~' b_expr %prec UMINUS
  8515    {
  8516      $$.val = &tree.UnaryExpr{Operator: tree.UnaryComplement, Expr: $2.expr()}
  8517    }
  8518  | b_expr '+' b_expr
  8519    {
  8520      $$.val = &tree.BinaryExpr{Operator: tree.Plus, Left: $1.expr(), Right: $3.expr()}
  8521    }
  8522  | b_expr '-' b_expr
  8523    {
  8524      $$.val = &tree.BinaryExpr{Operator: tree.Minus, Left: $1.expr(), Right: $3.expr()}
  8525    }
  8526  | b_expr '*' b_expr
  8527    {
  8528      $$.val = &tree.BinaryExpr{Operator: tree.Mult, Left: $1.expr(), Right: $3.expr()}
  8529    }
  8530  | b_expr '/' b_expr
  8531    {
  8532      $$.val = &tree.BinaryExpr{Operator: tree.Div, Left: $1.expr(), Right: $3.expr()}
  8533    }
  8534  | b_expr FLOORDIV b_expr
  8535    {
  8536      $$.val = &tree.BinaryExpr{Operator: tree.FloorDiv, Left: $1.expr(), Right: $3.expr()}
  8537    }
  8538  | b_expr '%' b_expr
  8539    {
  8540      $$.val = &tree.BinaryExpr{Operator: tree.Mod, Left: $1.expr(), Right: $3.expr()}
  8541    }
  8542  | b_expr '^' b_expr
  8543    {
  8544      $$.val = &tree.BinaryExpr{Operator: tree.Pow, Left: $1.expr(), Right: $3.expr()}
  8545    }
  8546  | b_expr '#' b_expr
  8547    {
  8548      $$.val = &tree.BinaryExpr{Operator: tree.Bitxor, Left: $1.expr(), Right: $3.expr()}
  8549    }
  8550  | b_expr '&' b_expr
  8551    {
  8552      $$.val = &tree.BinaryExpr{Operator: tree.Bitand, Left: $1.expr(), Right: $3.expr()}
  8553    }
  8554  | b_expr '|' b_expr
  8555    {
  8556      $$.val = &tree.BinaryExpr{Operator: tree.Bitor, Left: $1.expr(), Right: $3.expr()}
  8557    }
  8558  | b_expr '<' b_expr
  8559    {
  8560      $$.val = &tree.ComparisonExpr{Operator: tree.LT, Left: $1.expr(), Right: $3.expr()}
  8561    }
  8562  | b_expr '>' b_expr
  8563    {
  8564      $$.val = &tree.ComparisonExpr{Operator: tree.GT, Left: $1.expr(), Right: $3.expr()}
  8565    }
  8566  | b_expr '=' b_expr
  8567    {
  8568      $$.val = &tree.ComparisonExpr{Operator: tree.EQ, Left: $1.expr(), Right: $3.expr()}
  8569    }
  8570  | b_expr CONCAT b_expr
  8571    {
  8572      $$.val = &tree.BinaryExpr{Operator: tree.Concat, Left: $1.expr(), Right: $3.expr()}
  8573    }
  8574  | b_expr LSHIFT b_expr
  8575    {
  8576      $$.val = &tree.BinaryExpr{Operator: tree.LShift, Left: $1.expr(), Right: $3.expr()}
  8577    }
  8578  | b_expr RSHIFT b_expr
  8579    {
  8580      $$.val = &tree.BinaryExpr{Operator: tree.RShift, Left: $1.expr(), Right: $3.expr()}
  8581    }
  8582  | b_expr LESS_EQUALS b_expr
  8583    {
  8584      $$.val = &tree.ComparisonExpr{Operator: tree.LE, Left: $1.expr(), Right: $3.expr()}
  8585    }
  8586  | b_expr GREATER_EQUALS b_expr
  8587    {
  8588      $$.val = &tree.ComparisonExpr{Operator: tree.GE, Left: $1.expr(), Right: $3.expr()}
  8589    }
  8590  | b_expr NOT_EQUALS b_expr
  8591    {
  8592      $$.val = &tree.ComparisonExpr{Operator: tree.NE, Left: $1.expr(), Right: $3.expr()}
  8593    }
  8594  | b_expr IS DISTINCT FROM b_expr %prec IS
  8595    {
  8596      $$.val = &tree.ComparisonExpr{Operator: tree.IsDistinctFrom, Left: $1.expr(), Right: $5.expr()}
  8597    }
  8598  | b_expr IS NOT DISTINCT FROM b_expr %prec IS
  8599    {
  8600      $$.val = &tree.ComparisonExpr{Operator: tree.IsNotDistinctFrom, Left: $1.expr(), Right: $6.expr()}
  8601    }
  8602  | b_expr IS OF '(' type_list ')' %prec IS
  8603    {
  8604      $$.val = &tree.IsOfTypeExpr{Expr: $1.expr(), Types: $5.typeReferences()}
  8605    }
  8606  | b_expr IS NOT OF '(' type_list ')' %prec IS
  8607    {
  8608      $$.val = &tree.IsOfTypeExpr{Not: true, Expr: $1.expr(), Types: $6.typeReferences()}
  8609    }
  8610  
  8611  // Productions that can be used in both a_expr and b_expr.
  8612  //
  8613  // Note: productions that refer recursively to a_expr or b_expr mostly cannot
  8614  // appear here. However, it's OK to refer to a_exprs that occur inside
  8615  // parentheses, such as function arguments; that cannot introduce ambiguity to
  8616  // the b_expr syntax.
  8617  //
  8618  c_expr:
  8619    d_expr
  8620  | d_expr array_subscripts
  8621    {
  8622      $$.val = &tree.IndirectionExpr{
  8623        Expr: $1.expr(),
  8624        Indirection: $2.arraySubscripts(),
  8625      }
  8626    }
  8627  | case_expr
  8628  | EXISTS select_with_parens
  8629    {
  8630      $$.val = &tree.Subquery{Select: $2.selectStmt(), Exists: true}
  8631    }
  8632  
  8633  // Productions that can be followed by a postfix operator.
  8634  //
  8635  // Currently we support array indexing (see c_expr above).
  8636  //
  8637  // TODO(knz/jordan): this is the rule that can be extended to support
  8638  // composite types (#27792) with e.g.:
  8639  //
  8640  //     | '(' a_expr ')' field_access_ops
  8641  //
  8642  //     [...]
  8643  //
  8644  //     // field_access_ops supports the notations:
  8645  //     // - .a
  8646  //     // - .a[123]
  8647  //     // - .a.b[123][5456].c.d
  8648  //     // NOT [123] directly, this is handled in c_expr above.
  8649  //
  8650  //     field_access_ops:
  8651  //       field_access_op
  8652  //     | field_access_op other_subscripts
  8653  //
  8654  //     field_access_op:
  8655  //       '.' name
  8656  //     other_subscripts:
  8657  //       other_subscript
  8658  //     | other_subscripts other_subscript
  8659  //     other_subscript:
  8660  //        field_access_op
  8661  //     |  array_subscripts
  8662  
  8663  d_expr:
  8664    ICONST
  8665    {
  8666      $$.val = $1.numVal()
  8667    }
  8668  | FCONST
  8669    {
  8670      $$.val = $1.numVal()
  8671    }
  8672  | SCONST
  8673    {
  8674      $$.val = tree.NewStrVal($1)
  8675    }
  8676  | BCONST
  8677    {
  8678      $$.val = tree.NewBytesStrVal($1)
  8679    }
  8680  | BITCONST
  8681    {
  8682      d, err := tree.ParseDBitArray($1)
  8683      if err != nil { return setErr(sqllex, err) }
  8684      $$.val = d
  8685    }
  8686  | func_name '(' expr_list opt_sort_clause ')' SCONST { return unimplemented(sqllex, $1.unresolvedName().String() + "(...) SCONST") }
  8687  | typed_literal
  8688    {
  8689      $$.val = $1.expr()
  8690    }
  8691  | interval_value
  8692    {
  8693      $$.val = $1.expr()
  8694    }
  8695  | TRUE
  8696    {
  8697      $$.val = tree.MakeDBool(true)
  8698    }
  8699  | FALSE
  8700    {
  8701      $$.val = tree.MakeDBool(false)
  8702    }
  8703  | NULL
  8704    {
  8705      $$.val = tree.DNull
  8706    }
  8707  | column_path_with_star
  8708    {
  8709      $$.val = tree.Expr($1.unresolvedName())
  8710    }
  8711  | '@' iconst64
  8712    {
  8713      colNum := $2.int64()
  8714      if colNum < 1 || colNum > int64(MaxInt) {
  8715        sqllex.Error(fmt.Sprintf("invalid column ordinal: @%d", colNum))
  8716        return 1
  8717      }
  8718      $$.val = tree.NewOrdinalReference(int(colNum-1))
  8719    }
  8720  | PLACEHOLDER
  8721    {
  8722      p := $1.placeholder()
  8723      sqllex.(*lexer).UpdateNumPlaceholders(p)
  8724      $$.val = p
  8725    }
  8726  // TODO(knz/jordan): extend this for compound types. See explanation above.
  8727  | '(' a_expr ')' '.' '*'
  8728    {
  8729      $$.val = &tree.TupleStar{Expr: $2.expr()}
  8730    }
  8731  | '(' a_expr ')' '.' unrestricted_name
  8732    {
  8733      $$.val = &tree.ColumnAccessExpr{Expr: $2.expr(), ColName: $5 }
  8734    }
  8735  | '(' a_expr ')' '.' '@' ICONST
  8736    {
  8737      idx, err := $6.numVal().AsInt32()
  8738      if err != nil || idx <= 0 { return setErr(sqllex, err) }
  8739      $$.val = &tree.ColumnAccessExpr{Expr: $2.expr(), ByIndex: true, ColIndex: int(idx-1)}
  8740    }
  8741  | '(' a_expr ')'
  8742    {
  8743      $$.val = &tree.ParenExpr{Expr: $2.expr()}
  8744    }
  8745  | func_expr
  8746  | select_with_parens %prec UMINUS
  8747    {
  8748      $$.val = &tree.Subquery{Select: $1.selectStmt()}
  8749    }
  8750  | labeled_row
  8751    {
  8752      $$.val = $1.tuple()
  8753    }
  8754  | ARRAY select_with_parens %prec UMINUS
  8755    {
  8756      $$.val = &tree.ArrayFlatten{Subquery: &tree.Subquery{Select: $2.selectStmt()}}
  8757    }
  8758  | ARRAY row
  8759    {
  8760      $$.val = &tree.Array{Exprs: $2.tuple().Exprs}
  8761    }
  8762  | ARRAY array_expr
  8763    {
  8764      $$.val = $2.expr()
  8765    }
  8766  | GROUPING '(' expr_list ')' { return unimplemented(sqllex, "d_expr grouping") }
  8767  
  8768  func_application:
  8769    func_name '(' ')'
  8770    {
  8771      $$.val = &tree.FuncExpr{Func: $1.resolvableFuncRefFromName()}
  8772    }
  8773  | func_name '(' expr_list opt_sort_clause ')'
  8774    {
  8775      $$.val = &tree.FuncExpr{Func: $1.resolvableFuncRefFromName(), Exprs: $3.exprs(), OrderBy: $4.orderBy(), AggType: tree.GeneralAgg}
  8776    }
  8777  | func_name '(' VARIADIC a_expr opt_sort_clause ')' { return unimplemented(sqllex, "variadic") }
  8778  | func_name '(' expr_list ',' VARIADIC a_expr opt_sort_clause ')' { return unimplemented(sqllex, "variadic") }
  8779  | func_name '(' ALL expr_list opt_sort_clause ')'
  8780    {
  8781      $$.val = &tree.FuncExpr{Func: $1.resolvableFuncRefFromName(), Type: tree.AllFuncType, Exprs: $4.exprs(), OrderBy: $5.orderBy(), AggType: tree.GeneralAgg}
  8782    }
  8783  // TODO(ridwanmsharif): Once DISTINCT is supported by window aggregates,
  8784  // allow ordering to be specified below.
  8785  | func_name '(' DISTINCT expr_list ')'
  8786    {
  8787      $$.val = &tree.FuncExpr{Func: $1.resolvableFuncRefFromName(), Type: tree.DistinctFuncType, Exprs: $4.exprs()}
  8788    }
  8789  | func_name '(' '*' ')'
  8790    {
  8791      $$.val = &tree.FuncExpr{Func: $1.resolvableFuncRefFromName(), Exprs: tree.Exprs{tree.StarExpr()}}
  8792    }
  8793  | func_name '(' error { return helpWithFunction(sqllex, $1.resolvableFuncRefFromName()) }
  8794  
  8795  // typed_literal represents expressions like INT '4', or generally <TYPE> SCONST.
  8796  // This rule handles both the case of qualified and non-qualified typenames.
  8797  typed_literal:
  8798    // The key here is that none of the keywords in the func_name_no_crdb_extra
  8799    // production can overlap with the type rules in const_typename, otherwise
  8800    // we will have conflicts between this rule and the one below.
  8801    func_name_no_crdb_extra SCONST
  8802    {
  8803      name := $1.unresolvedName()
  8804      if name.NumParts == 1 {
  8805        typName := name.Parts[0]
  8806        /* FORCE DOC */
  8807        // See https://www.postgresql.org/docs/9.1/static/datatype-character.html
  8808        // Postgres supports a special character type named "char" (with the quotes)
  8809        // that is a single-character column type. It's used by system tables.
  8810        // Eventually this clause will be used to parse user-defined types as well,
  8811        // since their names can be quoted.
  8812        if typName == "char" {
  8813          $$.val = &tree.CastExpr{Expr: tree.NewStrVal($2), Type: types.MakeQChar(0), SyntaxMode: tree.CastPrepend}
  8814        } else if typName == "serial" {
  8815          switch sqllex.(*lexer).nakedIntType.Width() {
  8816          case 32:
  8817            $$.val = &tree.CastExpr{Expr: tree.NewStrVal($2), Type: &types.Serial4Type, SyntaxMode: tree.CastPrepend}
  8818          default:
  8819            $$.val = &tree.CastExpr{Expr: tree.NewStrVal($2), Type: &types.Serial8Type, SyntaxMode: tree.CastPrepend}
  8820          }
  8821        } else {
  8822          // Check the the type is one of our "non-keyword" type names.
  8823          // Otherwise, package it up as a type reference for later.
  8824          // However, if the type name is one of our known unsupported
  8825          // types, return an unimplemented error message.
  8826          var typ tree.ResolvableTypeReference
  8827          var ok bool
  8828          var err error
  8829          var unimp int
  8830          typ, ok, unimp = types.TypeForNonKeywordTypeName(typName)
  8831          if !ok {
  8832            switch unimp {
  8833              case 0:
  8834                // In this case, we don't think this type is one of our
  8835                // known unsupported types, so make a type reference for it.
  8836                aIdx := sqllex.(*lexer).NewAnnotation()
  8837                typ, err = name.ToUnresolvedObjectName(aIdx)
  8838                if err != nil { return setErr(sqllex, err) }
  8839              case -1:
  8840                return unimplemented(sqllex, "type name " + typName)
  8841              default:
  8842                return unimplementedWithIssueDetail(sqllex, unimp, typName)
  8843            }
  8844          }
  8845        $$.val = &tree.CastExpr{Expr: tree.NewStrVal($2), Type: typ, SyntaxMode: tree.CastPrepend}
  8846        }
  8847      } else {
  8848        aIdx := sqllex.(*lexer).NewAnnotation()
  8849        res, err := name.ToUnresolvedObjectName(aIdx)
  8850        if err != nil { return setErr(sqllex, err) }
  8851        $$.val = &tree.CastExpr{Expr: tree.NewStrVal($2), Type: res, SyntaxMode: tree.CastPrepend}
  8852      }
  8853    }
  8854  | const_typename SCONST
  8855    {
  8856      $$.val = &tree.CastExpr{Expr: tree.NewStrVal($2), Type: $1.colType(), SyntaxMode: tree.CastPrepend}
  8857    }
  8858  
  8859  // func_expr and its cousin func_expr_windowless are split out from c_expr just
  8860  // so that we have classifications for "everything that is a function call or
  8861  // looks like one". This isn't very important, but it saves us having to
  8862  // document which variants are legal in places like "FROM function()" or the
  8863  // backwards-compatible functional-index syntax for CREATE INDEX. (Note that
  8864  // many of the special SQL functions wouldn't actually make any sense as
  8865  // functional index entries, but we ignore that consideration here.)
  8866  func_expr:
  8867    func_application within_group_clause filter_clause over_clause
  8868    {
  8869      f := $1.expr().(*tree.FuncExpr)
  8870      w := $2.expr().(*tree.FuncExpr)
  8871      if w.AggType != 0 {
  8872        f.AggType = w.AggType
  8873        f.OrderBy = w.OrderBy
  8874      }
  8875      f.Filter = $3.expr()
  8876      f.WindowDef = $4.windowDef()
  8877      $$.val = f
  8878    }
  8879  | func_expr_common_subexpr
  8880    {
  8881      $$.val = $1.expr()
  8882    }
  8883  
  8884  // As func_expr but does not accept WINDOW functions directly (but they can
  8885  // still be contained in arguments for functions etc). Use this when window
  8886  // expressions are not allowed, where needed to disambiguate the grammar
  8887  // (e.g. in CREATE INDEX).
  8888  func_expr_windowless:
  8889    func_application { $$.val = $1.expr() }
  8890  | func_expr_common_subexpr { $$.val = $1.expr() }
  8891  
  8892  // Special expressions that are considered to be functions.
  8893  func_expr_common_subexpr:
  8894    COLLATION FOR '(' a_expr ')'
  8895    {
  8896      $$.val = &tree.FuncExpr{Func: tree.WrapFunction("pg_collation_for"), Exprs: tree.Exprs{$4.expr()}}
  8897    }
  8898  | CURRENT_DATE
  8899    {
  8900      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1)}
  8901    }
  8902  | CURRENT_SCHEMA
  8903    {
  8904      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1)}
  8905    }
  8906  // Special identifier current_catalog is equivalent to current_database().
  8907  // https://www.postgresql.org/docs/10/static/functions-info.html
  8908  | CURRENT_CATALOG
  8909    {
  8910      $$.val = &tree.FuncExpr{Func: tree.WrapFunction("current_database")}
  8911    }
  8912  | CURRENT_TIMESTAMP
  8913    {
  8914      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1)}
  8915    }
  8916  | CURRENT_TIME
  8917    {
  8918      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1)}
  8919    }
  8920  | LOCALTIMESTAMP
  8921    {
  8922      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1)}
  8923    }
  8924  | LOCALTIME
  8925    {
  8926      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1)}
  8927    }
  8928  | CURRENT_USER
  8929    {
  8930      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1)}
  8931    }
  8932  // Special identifier current_role is equivalent to current_user.
  8933  // https://www.postgresql.org/docs/10/static/functions-info.html
  8934  | CURRENT_ROLE
  8935    {
  8936      $$.val = &tree.FuncExpr{Func: tree.WrapFunction("current_user")}
  8937    }
  8938  | SESSION_USER
  8939    {
  8940      $$.val = &tree.FuncExpr{Func: tree.WrapFunction("current_user")}
  8941    }
  8942  | USER
  8943    {
  8944      $$.val = &tree.FuncExpr{Func: tree.WrapFunction("current_user")}
  8945    }
  8946  | CAST '(' a_expr AS cast_target ')'
  8947    {
  8948      $$.val = &tree.CastExpr{Expr: $3.expr(), Type: $5.typeReference(), SyntaxMode: tree.CastExplicit}
  8949    }
  8950  | ANNOTATE_TYPE '(' a_expr ',' typename ')'
  8951    {
  8952      $$.val = &tree.AnnotateTypeExpr{Expr: $3.expr(), Type: $5.typeReference(), SyntaxMode: tree.AnnotateExplicit}
  8953    }
  8954  | IF '(' a_expr ',' a_expr ',' a_expr ')'
  8955    {
  8956      $$.val = &tree.IfExpr{Cond: $3.expr(), True: $5.expr(), Else: $7.expr()}
  8957    }
  8958  | IFERROR '(' a_expr ',' a_expr ',' a_expr ')'
  8959    {
  8960      $$.val = &tree.IfErrExpr{Cond: $3.expr(), Else: $5.expr(), ErrCode: $7.expr()}
  8961    }
  8962  | IFERROR '(' a_expr ',' a_expr ')'
  8963    {
  8964      $$.val = &tree.IfErrExpr{Cond: $3.expr(), Else: $5.expr()}
  8965    }
  8966  | ISERROR '(' a_expr ')'
  8967    {
  8968      $$.val = &tree.IfErrExpr{Cond: $3.expr()}
  8969    }
  8970  | ISERROR '(' a_expr ',' a_expr ')'
  8971    {
  8972      $$.val = &tree.IfErrExpr{Cond: $3.expr(), ErrCode: $5.expr()}
  8973    }
  8974  | NULLIF '(' a_expr ',' a_expr ')'
  8975    {
  8976      $$.val = &tree.NullIfExpr{Expr1: $3.expr(), Expr2: $5.expr()}
  8977    }
  8978  | IFNULL '(' a_expr ',' a_expr ')'
  8979    {
  8980      $$.val = &tree.CoalesceExpr{Name: "IFNULL", Exprs: tree.Exprs{$3.expr(), $5.expr()}}
  8981    }
  8982  | COALESCE '(' expr_list ')'
  8983    {
  8984      $$.val = &tree.CoalesceExpr{Name: "COALESCE", Exprs: $3.exprs()}
  8985    }
  8986  | special_function
  8987  
  8988  special_function:
  8989    CURRENT_DATE '(' ')'
  8990    {
  8991      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1)}
  8992    }
  8993  | CURRENT_DATE '(' error { return helpWithFunctionByName(sqllex, $1) }
  8994  | CURRENT_SCHEMA '(' ')'
  8995    {
  8996      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1)}
  8997    }
  8998  | CURRENT_SCHEMA '(' error { return helpWithFunctionByName(sqllex, $1) }
  8999  | CURRENT_TIMESTAMP '(' ')'
  9000    {
  9001      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1)}
  9002    }
  9003  | CURRENT_TIMESTAMP '(' a_expr ')'
  9004    {
  9005      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1), Exprs: tree.Exprs{$3.expr()}}
  9006    }
  9007  | CURRENT_TIMESTAMP '(' error { return helpWithFunctionByName(sqllex, $1) }
  9008  | CURRENT_TIME '(' ')'
  9009    {
  9010      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1)}
  9011    }
  9012  | CURRENT_TIME '(' a_expr ')'
  9013    {
  9014      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1), Exprs: tree.Exprs{$3.expr()}}
  9015    }
  9016  | CURRENT_TIME '(' error { return helpWithFunctionByName(sqllex, $1) }
  9017  | LOCALTIMESTAMP '(' ')'
  9018    {
  9019      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1)}
  9020    }
  9021  | LOCALTIMESTAMP '(' a_expr ')'
  9022    {
  9023      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1), Exprs: tree.Exprs{$3.expr()}}
  9024    }
  9025  | LOCALTIMESTAMP '(' error { return helpWithFunctionByName(sqllex, $1) }
  9026  | LOCALTIME '(' ')'
  9027    {
  9028      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1)}
  9029    }
  9030  | LOCALTIME '(' a_expr ')'
  9031    {
  9032      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1), Exprs: tree.Exprs{$3.expr()}}
  9033    }
  9034  | LOCALTIME '(' error { return helpWithFunctionByName(sqllex, $1) }
  9035  | CURRENT_USER '(' ')'
  9036    {
  9037      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1)}
  9038    }
  9039  | CURRENT_USER '(' error { return helpWithFunctionByName(sqllex, $1) }
  9040  | EXTRACT '(' extract_list ')'
  9041    {
  9042      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1), Exprs: $3.exprs()}
  9043    }
  9044  | EXTRACT '(' error { return helpWithFunctionByName(sqllex, $1) }
  9045  | EXTRACT_DURATION '(' extract_list ')'
  9046    {
  9047      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1), Exprs: $3.exprs()}
  9048    }
  9049  | EXTRACT_DURATION '(' error { return helpWithFunctionByName(sqllex, $1) }
  9050  | OVERLAY '(' overlay_list ')'
  9051    {
  9052      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1), Exprs: $3.exprs()}
  9053    }
  9054  | OVERLAY '(' error { return helpWithFunctionByName(sqllex, $1) }
  9055  | POSITION '(' position_list ')'
  9056    {
  9057      $$.val = &tree.FuncExpr{Func: tree.WrapFunction("strpos"), Exprs: $3.exprs()}
  9058    }
  9059  | SUBSTRING '(' substr_list ')'
  9060    {
  9061      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1), Exprs: $3.exprs()}
  9062    }
  9063  | SUBSTRING '(' error { return helpWithFunctionByName(sqllex, $1) }
  9064  | TREAT '(' a_expr AS typename ')' { return unimplemented(sqllex, "treat") }
  9065  | TRIM '(' BOTH trim_list ')'
  9066    {
  9067      $$.val = &tree.FuncExpr{Func: tree.WrapFunction("btrim"), Exprs: $4.exprs()}
  9068    }
  9069  | TRIM '(' LEADING trim_list ')'
  9070    {
  9071      $$.val = &tree.FuncExpr{Func: tree.WrapFunction("ltrim"), Exprs: $4.exprs()}
  9072    }
  9073  | TRIM '(' TRAILING trim_list ')'
  9074    {
  9075      $$.val = &tree.FuncExpr{Func: tree.WrapFunction("rtrim"), Exprs: $4.exprs()}
  9076    }
  9077  | TRIM '(' trim_list ')'
  9078    {
  9079      $$.val = &tree.FuncExpr{Func: tree.WrapFunction("btrim"), Exprs: $3.exprs()}
  9080    }
  9081  | GREATEST '(' expr_list ')'
  9082    {
  9083      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1), Exprs: $3.exprs()}
  9084    }
  9085  | GREATEST '(' error { return helpWithFunctionByName(sqllex, $1) }
  9086  | LEAST '(' expr_list ')'
  9087    {
  9088      $$.val = &tree.FuncExpr{Func: tree.WrapFunction($1), Exprs: $3.exprs()}
  9089    }
  9090  | LEAST '(' error { return helpWithFunctionByName(sqllex, $1) }
  9091  
  9092  
  9093  // Aggregate decoration clauses
  9094  within_group_clause:
  9095    WITHIN GROUP '(' single_sort_clause ')'
  9096    {
  9097      $$.val = &tree.FuncExpr{OrderBy: $4.orderBy(), AggType: tree.OrderedSetAgg}
  9098    }
  9099  | /* EMPTY */
  9100    {
  9101      $$.val = &tree.FuncExpr{}
  9102    }
  9103  
  9104  filter_clause:
  9105    FILTER '(' WHERE a_expr ')'
  9106    {
  9107      $$.val = $4.expr()
  9108    }
  9109  | /* EMPTY */
  9110    {
  9111      $$.val = tree.Expr(nil)
  9112    }
  9113  
  9114  // Window Definitions
  9115  window_clause:
  9116    WINDOW window_definition_list
  9117    {
  9118      $$.val = $2.window()
  9119    }
  9120  | /* EMPTY */
  9121    {
  9122      $$.val = tree.Window(nil)
  9123    }
  9124  
  9125  window_definition_list:
  9126    window_definition
  9127    {
  9128      $$.val = tree.Window{$1.windowDef()}
  9129    }
  9130  | window_definition_list ',' window_definition
  9131    {
  9132      $$.val = append($1.window(), $3.windowDef())
  9133    }
  9134  
  9135  window_definition:
  9136    window_name AS window_specification
  9137    {
  9138      n := $3.windowDef()
  9139      n.Name = tree.Name($1)
  9140      $$.val = n
  9141    }
  9142  
  9143  over_clause:
  9144    OVER window_specification
  9145    {
  9146      $$.val = $2.windowDef()
  9147    }
  9148  | OVER window_name
  9149    {
  9150      $$.val = &tree.WindowDef{Name: tree.Name($2)}
  9151    }
  9152  | /* EMPTY */
  9153    {
  9154      $$.val = (*tree.WindowDef)(nil)
  9155    }
  9156  
  9157  window_specification:
  9158    '(' opt_existing_window_name opt_partition_clause
  9159      opt_sort_clause opt_frame_clause ')'
  9160    {
  9161      $$.val = &tree.WindowDef{
  9162        RefName: tree.Name($2),
  9163        Partitions: $3.exprs(),
  9164        OrderBy: $4.orderBy(),
  9165        Frame: $5.windowFrame(),
  9166      }
  9167    }
  9168  
  9169  // If we see PARTITION, RANGE, ROWS, or GROUPS as the first token after the '('
  9170  // of a window_specification, we want the assumption to be that there is no
  9171  // existing_window_name; but those keywords are unreserved and so could be
  9172  // names. We fix this by making them have the same precedence as IDENT and
  9173  // giving the empty production here a slightly higher precedence, so that the
  9174  // shift/reduce conflict is resolved in favor of reducing the rule. These
  9175  // keywords are thus precluded from being an existing_window_name but are not
  9176  // reserved for any other purpose.
  9177  opt_existing_window_name:
  9178    name
  9179  | /* EMPTY */ %prec CONCAT
  9180    {
  9181      $$ = ""
  9182    }
  9183  
  9184  opt_partition_clause:
  9185    PARTITION BY expr_list
  9186    {
  9187      $$.val = $3.exprs()
  9188    }
  9189  | /* EMPTY */
  9190    {
  9191      $$.val = tree.Exprs(nil)
  9192    }
  9193  
  9194  opt_frame_clause:
  9195    RANGE frame_extent opt_frame_exclusion
  9196    {
  9197      $$.val = &tree.WindowFrame{
  9198        Mode: tree.RANGE,
  9199        Bounds: $2.windowFrameBounds(),
  9200        Exclusion: $3.windowFrameExclusion(),
  9201      }
  9202    }
  9203  | ROWS frame_extent opt_frame_exclusion
  9204    {
  9205      $$.val = &tree.WindowFrame{
  9206        Mode: tree.ROWS,
  9207        Bounds: $2.windowFrameBounds(),
  9208        Exclusion: $3.windowFrameExclusion(),
  9209      }
  9210    }
  9211  | GROUPS frame_extent opt_frame_exclusion
  9212    {
  9213      $$.val = &tree.WindowFrame{
  9214        Mode: tree.GROUPS,
  9215        Bounds: $2.windowFrameBounds(),
  9216        Exclusion: $3.windowFrameExclusion(),
  9217      }
  9218    }
  9219  | /* EMPTY */
  9220    {
  9221      $$.val = (*tree.WindowFrame)(nil)
  9222    }
  9223  
  9224  frame_extent:
  9225    frame_bound
  9226    {
  9227      startBound := $1.windowFrameBound()
  9228      switch {
  9229      case startBound.BoundType == tree.UnboundedFollowing:
  9230        sqllex.Error("frame start cannot be UNBOUNDED FOLLOWING")
  9231        return 1
  9232      case startBound.BoundType == tree.OffsetFollowing:
  9233        sqllex.Error("frame starting from following row cannot end with current row")
  9234        return 1
  9235      }
  9236      $$.val = tree.WindowFrameBounds{StartBound: startBound}
  9237    }
  9238  | BETWEEN frame_bound AND frame_bound
  9239    {
  9240      startBound := $2.windowFrameBound()
  9241      endBound := $4.windowFrameBound()
  9242      switch {
  9243      case startBound.BoundType == tree.UnboundedFollowing:
  9244        sqllex.Error("frame start cannot be UNBOUNDED FOLLOWING")
  9245        return 1
  9246      case endBound.BoundType == tree.UnboundedPreceding:
  9247        sqllex.Error("frame end cannot be UNBOUNDED PRECEDING")
  9248        return 1
  9249      case startBound.BoundType == tree.CurrentRow && endBound.BoundType == tree.OffsetPreceding:
  9250        sqllex.Error("frame starting from current row cannot have preceding rows")
  9251        return 1
  9252      case startBound.BoundType == tree.OffsetFollowing && endBound.BoundType == tree.OffsetPreceding:
  9253        sqllex.Error("frame starting from following row cannot have preceding rows")
  9254        return 1
  9255      case startBound.BoundType == tree.OffsetFollowing && endBound.BoundType == tree.CurrentRow:
  9256        sqllex.Error("frame starting from following row cannot have preceding rows")
  9257        return 1
  9258      }
  9259      $$.val = tree.WindowFrameBounds{StartBound: startBound, EndBound: endBound}
  9260    }
  9261  
  9262  // This is used for both frame start and frame end, with output set up on the
  9263  // assumption it's frame start; the frame_extent productions must reject
  9264  // invalid cases.
  9265  frame_bound:
  9266    UNBOUNDED PRECEDING
  9267    {
  9268      $$.val = &tree.WindowFrameBound{BoundType: tree.UnboundedPreceding}
  9269    }
  9270  | UNBOUNDED FOLLOWING
  9271    {
  9272      $$.val = &tree.WindowFrameBound{BoundType: tree.UnboundedFollowing}
  9273    }
  9274  | CURRENT ROW
  9275    {
  9276      $$.val = &tree.WindowFrameBound{BoundType: tree.CurrentRow}
  9277    }
  9278  | a_expr PRECEDING
  9279    {
  9280      $$.val = &tree.WindowFrameBound{
  9281        OffsetExpr: $1.expr(),
  9282        BoundType: tree.OffsetPreceding,
  9283      }
  9284    }
  9285  | a_expr FOLLOWING
  9286    {
  9287      $$.val = &tree.WindowFrameBound{
  9288        OffsetExpr: $1.expr(),
  9289        BoundType: tree.OffsetFollowing,
  9290      }
  9291    }
  9292  
  9293  opt_frame_exclusion:
  9294    EXCLUDE CURRENT ROW
  9295    {
  9296      $$.val = tree.ExcludeCurrentRow
  9297    }
  9298  | EXCLUDE GROUP
  9299    {
  9300      $$.val = tree.ExcludeGroup
  9301    }
  9302  | EXCLUDE TIES
  9303    {
  9304      $$.val = tree.ExcludeTies
  9305    }
  9306  | EXCLUDE NO OTHERS
  9307    {
  9308      // EXCLUDE NO OTHERS is equivalent to omitting the frame exclusion clause.
  9309      $$.val = tree.NoExclusion
  9310    }
  9311  | /* EMPTY */
  9312    {
  9313      $$.val = tree.NoExclusion
  9314    }
  9315  
  9316  // Supporting nonterminals for expressions.
  9317  
  9318  // Explicit row production.
  9319  //
  9320  // SQL99 allows an optional ROW keyword, so we can now do single-element rows
  9321  // without conflicting with the parenthesized a_expr production. Without the
  9322  // ROW keyword, there must be more than one a_expr inside the parens.
  9323  row:
  9324    ROW '(' opt_expr_list ')'
  9325    {
  9326      $$.val = &tree.Tuple{Exprs: $3.exprs(), Row: true}
  9327    }
  9328  | expr_tuple_unambiguous
  9329    {
  9330      $$.val = $1.tuple()
  9331    }
  9332  
  9333  labeled_row:
  9334    row
  9335  | '(' row AS name_list ')'
  9336    {
  9337      t := $2.tuple()
  9338      labels := $4.nameList()
  9339      t.Labels = make([]string, len(labels))
  9340      for i, l := range labels {
  9341        t.Labels[i] = string(l)
  9342      }
  9343      $$.val = t
  9344    }
  9345  
  9346  sub_type:
  9347    ANY
  9348    {
  9349      $$.val = tree.Any
  9350    }
  9351  | SOME
  9352    {
  9353      $$.val = tree.Some
  9354    }
  9355  | ALL
  9356    {
  9357      $$.val = tree.All
  9358    }
  9359  
  9360  math_op:
  9361    '+' { $$.val = tree.Plus  }
  9362  | '-' { $$.val = tree.Minus }
  9363  | '*' { $$.val = tree.Mult  }
  9364  | '/' { $$.val = tree.Div   }
  9365  | FLOORDIV { $$.val = tree.FloorDiv }
  9366  | '%' { $$.val = tree.Mod    }
  9367  | '&' { $$.val = tree.Bitand }
  9368  | '|' { $$.val = tree.Bitor  }
  9369  | '^' { $$.val = tree.Pow }
  9370  | '#' { $$.val = tree.Bitxor }
  9371  | '<' { $$.val = tree.LT }
  9372  | '>' { $$.val = tree.GT }
  9373  | '=' { $$.val = tree.EQ }
  9374  | LESS_EQUALS    { $$.val = tree.LE }
  9375  | GREATER_EQUALS { $$.val = tree.GE }
  9376  | NOT_EQUALS     { $$.val = tree.NE }
  9377  
  9378  subquery_op:
  9379    math_op
  9380  | LIKE         { $$.val = tree.Like     }
  9381  | NOT_LA LIKE  { $$.val = tree.NotLike  }
  9382  | ILIKE        { $$.val = tree.ILike    }
  9383  | NOT_LA ILIKE { $$.val = tree.NotILike }
  9384    // cannot put SIMILAR TO here, because SIMILAR TO is a hack.
  9385    // the regular expression is preprocessed by a function (similar_escape),
  9386    // and the ~ operator for posix regular expressions is used.
  9387    //        x SIMILAR TO y     ->    x ~ similar_escape(y)
  9388    // this transformation is made on the fly by the parser upwards.
  9389    // however the SubLink structure which handles any/some/all stuff
  9390    // is not ready for such a thing.
  9391  
  9392  // expr_tuple1_ambiguous is a tuple expression with at least one expression.
  9393  // The allowable syntax is:
  9394  // ( )         -- empty tuple.
  9395  // ( E )       -- just one value, this is potentially ambiguous with
  9396  //             -- grouping parentheses. The ambiguity is resolved
  9397  //             -- by only allowing expr_tuple1_ambiguous on the RHS
  9398  //             -- of a IN expression.
  9399  // ( E, E, E ) -- comma-separated values, no trailing comma allowed.
  9400  // ( E, )      -- just one value with a comma, makes the syntax unambiguous
  9401  //             -- with grouping parentheses. This is not usually produced
  9402  //             -- by SQL clients, but can be produced by pretty-printing
  9403  //             -- internally in CockroachDB.
  9404  expr_tuple1_ambiguous:
  9405    '(' ')'
  9406    {
  9407      $$.val = &tree.Tuple{}
  9408    }
  9409  | '(' tuple1_ambiguous_values ')'
  9410    {
  9411      $$.val = &tree.Tuple{Exprs: $2.exprs()}
  9412    }
  9413  
  9414  tuple1_ambiguous_values:
  9415    a_expr
  9416    {
  9417      $$.val = tree.Exprs{$1.expr()}
  9418    }
  9419  | a_expr ','
  9420    {
  9421      $$.val = tree.Exprs{$1.expr()}
  9422    }
  9423  | a_expr ',' expr_list
  9424    {
  9425       $$.val = append(tree.Exprs{$1.expr()}, $3.exprs()...)
  9426    }
  9427  
  9428  // expr_tuple_unambiguous is a tuple expression with zero or more
  9429  // expressions. The allowable syntax is:
  9430  // ( )         -- zero values
  9431  // ( E, )      -- just one value. This is unambiguous with the (E) grouping syntax.
  9432  // ( E, E, E ) -- comma-separated values, more than 1.
  9433  expr_tuple_unambiguous:
  9434    '(' ')'
  9435    {
  9436      $$.val = &tree.Tuple{}
  9437    }
  9438  | '(' tuple1_unambiguous_values ')'
  9439    {
  9440      $$.val = &tree.Tuple{Exprs: $2.exprs()}
  9441    }
  9442  
  9443  tuple1_unambiguous_values:
  9444    a_expr ','
  9445    {
  9446      $$.val = tree.Exprs{$1.expr()}
  9447    }
  9448  | a_expr ',' expr_list
  9449    {
  9450       $$.val = append(tree.Exprs{$1.expr()}, $3.exprs()...)
  9451    }
  9452  
  9453  opt_expr_list:
  9454    expr_list
  9455  | /* EMPTY */
  9456    {
  9457      $$.val = tree.Exprs(nil)
  9458    }
  9459  
  9460  expr_list:
  9461    a_expr
  9462    {
  9463      $$.val = tree.Exprs{$1.expr()}
  9464    }
  9465  | expr_list ',' a_expr
  9466    {
  9467      $$.val = append($1.exprs(), $3.expr())
  9468    }
  9469  
  9470  type_list:
  9471    typename
  9472    {
  9473      $$.val = []tree.ResolvableTypeReference{$1.typeReference()}
  9474    }
  9475  | type_list ',' typename
  9476    {
  9477      $$.val = append($1.typeReferences(), $3.typeReference())
  9478    }
  9479  
  9480  array_expr:
  9481    '[' opt_expr_list ']'
  9482    {
  9483      $$.val = &tree.Array{Exprs: $2.exprs()}
  9484    }
  9485  | '[' array_expr_list ']'
  9486    {
  9487      $$.val = &tree.Array{Exprs: $2.exprs()}
  9488    }
  9489  
  9490  array_expr_list:
  9491    array_expr
  9492    {
  9493      $$.val = tree.Exprs{$1.expr()}
  9494    }
  9495  | array_expr_list ',' array_expr
  9496    {
  9497      $$.val = append($1.exprs(), $3.expr())
  9498    }
  9499  
  9500  extract_list:
  9501    extract_arg FROM a_expr
  9502    {
  9503      $$.val = tree.Exprs{tree.NewStrVal($1), $3.expr()}
  9504    }
  9505  | expr_list
  9506    {
  9507      $$.val = $1.exprs()
  9508    }
  9509  
  9510  // TODO(vivek): Narrow down to just IDENT once the other
  9511  // terms are not keywords.
  9512  extract_arg:
  9513    IDENT
  9514  | YEAR
  9515  | MONTH
  9516  | DAY
  9517  | HOUR
  9518  | MINUTE
  9519  | SECOND
  9520  | SCONST
  9521  
  9522  // OVERLAY() arguments
  9523  // SQL99 defines the OVERLAY() function:
  9524  //   - overlay(text placing text from int for int)
  9525  //   - overlay(text placing text from int)
  9526  // and similarly for binary strings
  9527  overlay_list:
  9528    a_expr overlay_placing substr_from substr_for
  9529    {
  9530      $$.val = tree.Exprs{$1.expr(), $2.expr(), $3.expr(), $4.expr()}
  9531    }
  9532  | a_expr overlay_placing substr_from
  9533    {
  9534      $$.val = tree.Exprs{$1.expr(), $2.expr(), $3.expr()}
  9535    }
  9536  | expr_list
  9537    {
  9538      $$.val = $1.exprs()
  9539    }
  9540  
  9541  overlay_placing:
  9542    PLACING a_expr
  9543    {
  9544      $$.val = $2.expr()
  9545    }
  9546  
  9547  // position_list uses b_expr not a_expr to avoid conflict with general IN
  9548  position_list:
  9549    b_expr IN b_expr
  9550    {
  9551      $$.val = tree.Exprs{$3.expr(), $1.expr()}
  9552    }
  9553  | /* EMPTY */
  9554    {
  9555      $$.val = tree.Exprs(nil)
  9556    }
  9557  
  9558  // SUBSTRING() arguments
  9559  // SQL9x defines a specific syntax for arguments to SUBSTRING():
  9560  //   - substring(text from int for int)
  9561  //   - substring(text from int) get entire string from starting point "int"
  9562  //   - substring(text for int) get first "int" characters of string
  9563  //   - substring(text from pattern) get entire string matching pattern
  9564  //   - substring(text from pattern for escape) same with specified escape char
  9565  // We also want to support generic substring functions which accept
  9566  // the usual generic list of arguments. So we will accept both styles
  9567  // here, and convert the SQL9x style to the generic list for further
  9568  // processing. - thomas 2000-11-28
  9569  substr_list:
  9570    a_expr substr_from substr_for
  9571    {
  9572      $$.val = tree.Exprs{$1.expr(), $2.expr(), $3.expr()}
  9573    }
  9574  | a_expr substr_for substr_from
  9575    {
  9576      $$.val = tree.Exprs{$1.expr(), $3.expr(), $2.expr()}
  9577    }
  9578  | a_expr substr_from
  9579    {
  9580      $$.val = tree.Exprs{$1.expr(), $2.expr()}
  9581    }
  9582  | a_expr substr_for
  9583    {
  9584      $$.val = tree.Exprs{$1.expr(), tree.NewDInt(1), $2.expr()}
  9585    }
  9586  | opt_expr_list
  9587    {
  9588      $$.val = $1.exprs()
  9589    }
  9590  
  9591  substr_from:
  9592    FROM a_expr
  9593    {
  9594      $$.val = $2.expr()
  9595    }
  9596  
  9597  substr_for:
  9598    FOR a_expr
  9599    {
  9600      $$.val = $2.expr()
  9601    }
  9602  
  9603  trim_list:
  9604    a_expr FROM expr_list
  9605    {
  9606      $$.val = append($3.exprs(), $1.expr())
  9607    }
  9608  | FROM expr_list
  9609    {
  9610      $$.val = $2.exprs()
  9611    }
  9612  | expr_list
  9613    {
  9614      $$.val = $1.exprs()
  9615    }
  9616  
  9617  in_expr:
  9618    select_with_parens
  9619    {
  9620      $$.val = &tree.Subquery{Select: $1.selectStmt()}
  9621    }
  9622  | expr_tuple1_ambiguous
  9623  
  9624  // Define SQL-style CASE clause.
  9625  // - Full specification
  9626  //      CASE WHEN a = b THEN c ... ELSE d END
  9627  // - Implicit argument
  9628  //      CASE a WHEN b THEN c ... ELSE d END
  9629  case_expr:
  9630    CASE case_arg when_clause_list case_default END
  9631    {
  9632      $$.val = &tree.CaseExpr{Expr: $2.expr(), Whens: $3.whens(), Else: $4.expr()}
  9633    }
  9634  
  9635  when_clause_list:
  9636    // There must be at least one
  9637    when_clause
  9638    {
  9639      $$.val = []*tree.When{$1.when()}
  9640    }
  9641  | when_clause_list when_clause
  9642    {
  9643      $$.val = append($1.whens(), $2.when())
  9644    }
  9645  
  9646  when_clause:
  9647    WHEN a_expr THEN a_expr
  9648    {
  9649      $$.val = &tree.When{Cond: $2.expr(), Val: $4.expr()}
  9650    }
  9651  
  9652  case_default:
  9653    ELSE a_expr
  9654    {
  9655      $$.val = $2.expr()
  9656    }
  9657  | /* EMPTY */
  9658    {
  9659      $$.val = tree.Expr(nil)
  9660    }
  9661  
  9662  case_arg:
  9663    a_expr
  9664  | /* EMPTY */
  9665    {
  9666      $$.val = tree.Expr(nil)
  9667    }
  9668  
  9669  array_subscript:
  9670    '[' a_expr ']'
  9671    {
  9672      $$.val = &tree.ArraySubscript{Begin: $2.expr()}
  9673    }
  9674  | '[' opt_slice_bound ':' opt_slice_bound ']'
  9675    {
  9676      $$.val = &tree.ArraySubscript{Begin: $2.expr(), End: $4.expr(), Slice: true}
  9677    }
  9678  
  9679  opt_slice_bound:
  9680    a_expr
  9681  | /*EMPTY*/
  9682    {
  9683      $$.val = tree.Expr(nil)
  9684    }
  9685  
  9686  array_subscripts:
  9687    array_subscript
  9688    {
  9689      $$.val = tree.ArraySubscripts{$1.arraySubscript()}
  9690    }
  9691  | array_subscripts array_subscript
  9692    {
  9693      $$.val = append($1.arraySubscripts(), $2.arraySubscript())
  9694    }
  9695  
  9696  opt_asymmetric:
  9697    ASYMMETRIC {}
  9698  | /* EMPTY */ {}
  9699  
  9700  target_list:
  9701    target_elem
  9702    {
  9703      $$.val = tree.SelectExprs{$1.selExpr()}
  9704    }
  9705  | target_list ',' target_elem
  9706    {
  9707      $$.val = append($1.selExprs(), $3.selExpr())
  9708    }
  9709  
  9710  target_elem:
  9711    a_expr AS target_name
  9712    {
  9713      $$.val = tree.SelectExpr{Expr: $1.expr(), As: tree.UnrestrictedName($3)}
  9714    }
  9715    // We support omitting AS only for column labels that aren't any known
  9716    // keyword. There is an ambiguity against postfix operators: is "a ! b" an
  9717    // infix expression, or a postfix expression and a column label?  We prefer
  9718    // to resolve this as an infix expression, which we accomplish by assigning
  9719    // IDENT a precedence higher than POSTFIXOP.
  9720  | a_expr IDENT
  9721    {
  9722      $$.val = tree.SelectExpr{Expr: $1.expr(), As: tree.UnrestrictedName($2)}
  9723    }
  9724  | a_expr
  9725    {
  9726      $$.val = tree.SelectExpr{Expr: $1.expr()}
  9727    }
  9728  | '*'
  9729    {
  9730      $$.val = tree.StarSelectExpr()
  9731    }
  9732  
  9733  // Names and constants.
  9734  
  9735  table_index_name_list:
  9736    table_index_name
  9737    {
  9738      $$.val = tree.TableIndexNames{$1.newTableIndexName()}
  9739    }
  9740  | table_index_name_list ',' table_index_name
  9741    {
  9742      $$.val = append($1.newTableIndexNames(), $3.newTableIndexName())
  9743    }
  9744  
  9745  table_pattern_list:
  9746    table_pattern
  9747    {
  9748      $$.val = tree.TablePatterns{$1.unresolvedName()}
  9749    }
  9750  | table_pattern_list ',' table_pattern
  9751    {
  9752      $$.val = append($1.tablePatterns(), $3.unresolvedName())
  9753    }
  9754  
  9755  // An index can be specified in a few different ways:
  9756  //
  9757  //   - with explicit table name:
  9758  //       <table>@<index>
  9759  //       <schema>.<table>@<index>
  9760  //       <catalog/db>.<table>@<index>
  9761  //       <catalog/db>.<schema>.<table>@<index>
  9762  //
  9763  //   - without explicit table name:
  9764  //       <index>
  9765  //       <schema>.<index>
  9766  //       <catalog/db>.<index>
  9767  //       <catalog/db>.<schema>.<index>
  9768  table_index_name:
  9769    table_name '@' index_name
  9770    {
  9771      name := $1.unresolvedObjectName().ToTableName()
  9772      $$.val = tree.TableIndexName{
  9773         Table: name,
  9774         Index: tree.UnrestrictedName($3),
  9775      }
  9776    }
  9777  | standalone_index_name
  9778    {
  9779      // Treat it as a table name, then pluck out the ObjectName.
  9780      name := $1.unresolvedObjectName().ToTableName()
  9781      indexName := tree.UnrestrictedName(name.ObjectName)
  9782      name.ObjectName = ""
  9783      $$.val = tree.TableIndexName{
  9784          Table: name,
  9785          Index: indexName,
  9786      }
  9787    }
  9788  
  9789  // table_pattern selects zero or more tables using a wildcard.
  9790  // Accepted patterns:
  9791  // - Patterns accepted by db_object_name
  9792  //   <table>
  9793  //   <schema>.<table>
  9794  //   <catalog/db>.<schema>.<table>
  9795  // - Wildcards:
  9796  //   <db/catalog>.<schema>.*
  9797  //   <schema>.*
  9798  //   *
  9799  table_pattern:
  9800    simple_db_object_name
  9801    {
  9802       $$.val = $1.unresolvedObjectName().ToUnresolvedName()
  9803    }
  9804  | complex_table_pattern
  9805  
  9806  // complex_table_pattern is the part of table_pattern which recognizes
  9807  // every pattern not composed of a single identifier.
  9808  complex_table_pattern:
  9809    complex_db_object_name
  9810    {
  9811       $$.val = $1.unresolvedObjectName().ToUnresolvedName()
  9812    }
  9813  | db_object_name_component '.' unrestricted_name '.' '*'
  9814    {
  9815       $$.val = &tree.UnresolvedName{Star: true, NumParts: 3, Parts: tree.NameParts{"", $3, $1}}
  9816    }
  9817  | db_object_name_component '.' '*'
  9818    {
  9819       $$.val = &tree.UnresolvedName{Star: true, NumParts: 2, Parts: tree.NameParts{"", $1}}
  9820    }
  9821  | '*'
  9822    {
  9823       $$.val = &tree.UnresolvedName{Star: true, NumParts: 1}
  9824    }
  9825  
  9826  name_list:
  9827    name
  9828    {
  9829      $$.val = tree.NameList{tree.Name($1)}
  9830    }
  9831  | name_list ',' name
  9832    {
  9833      $$.val = append($1.nameList(), tree.Name($3))
  9834    }
  9835  
  9836  // Constants
  9837  numeric_only:
  9838    signed_iconst
  9839  | signed_fconst
  9840  
  9841  signed_iconst:
  9842    ICONST
  9843  | only_signed_iconst
  9844  
  9845  only_signed_iconst:
  9846    '+' ICONST
  9847    {
  9848      $$.val = $2.numVal()
  9849    }
  9850  | '-' ICONST
  9851    {
  9852      n := $2.numVal()
  9853      n.SetNegative()
  9854      $$.val = n
  9855    }
  9856  
  9857  signed_fconst:
  9858    FCONST
  9859  | only_signed_fconst
  9860  
  9861  only_signed_fconst:
  9862    '+' FCONST
  9863    {
  9864      $$.val = $2.numVal()
  9865    }
  9866  | '-' FCONST
  9867    {
  9868      n := $2.numVal()
  9869      n.SetNegative()
  9870      $$.val = n
  9871    }
  9872  
  9873  // iconst32 accepts only unsigned integer literals that fit in an int32.
  9874  iconst32:
  9875    ICONST
  9876    {
  9877      val, err := $1.numVal().AsInt32()
  9878      if err != nil { return setErr(sqllex, err) }
  9879      $$.val = val
  9880    }
  9881  
  9882  // signed_iconst64 is a variant of signed_iconst which only accepts (signed) integer literals that fit in an int64.
  9883  // If you use signed_iconst, you have to call AsInt64(), which returns an error if the value is too big.
  9884  // This rule just doesn't match in that case.
  9885  signed_iconst64:
  9886    signed_iconst
  9887    {
  9888      val, err := $1.numVal().AsInt64()
  9889      if err != nil { return setErr(sqllex, err) }
  9890      $$.val = val
  9891    }
  9892  
  9893  // iconst64 accepts only unsigned integer literals that fit in an int64.
  9894  iconst64:
  9895    ICONST
  9896    {
  9897      val, err := $1.numVal().AsInt64()
  9898      if err != nil { return setErr(sqllex, err) }
  9899      $$.val = val
  9900    }
  9901  
  9902  interval_value:
  9903    INTERVAL SCONST opt_interval_qualifier
  9904    {
  9905      var err error
  9906      var d tree.Datum
  9907      if $3.val == nil {
  9908        d, err = tree.ParseDInterval($2)
  9909      } else {
  9910        d, err = tree.ParseDIntervalWithTypeMetadata($2, $3.intervalTypeMetadata())
  9911      }
  9912      if err != nil { return setErr(sqllex, err) }
  9913      $$.val = d
  9914    }
  9915  | INTERVAL '(' iconst32 ')' SCONST
  9916    {
  9917      prec := $3.int32()
  9918      if prec < 0 || prec > 6 {
  9919        sqllex.Error(fmt.Sprintf("precision %d out of range", prec))
  9920        return 1
  9921      }
  9922      d, err := tree.ParseDIntervalWithTypeMetadata($5, types.IntervalTypeMetadata{
  9923        Precision: prec,
  9924        PrecisionIsSet: true,
  9925      })
  9926      if err != nil { return setErr(sqllex, err) }
  9927      $$.val = d
  9928    }
  9929  
  9930  // Name classification hierarchy.
  9931  //
  9932  // IDENT is the lexeme returned by the lexer for identifiers that match no
  9933  // known keyword. In most cases, we can accept certain keywords as names, not
  9934  // only IDENTs. We prefer to accept as many such keywords as possible to
  9935  // minimize the impact of "reserved words" on programmers. So, we divide names
  9936  // into several possible classes. The classification is chosen in part to make
  9937  // keywords acceptable as names wherever possible.
  9938  
  9939  // Names specific to syntactic positions.
  9940  //
  9941  // The non-terminals "name", "unrestricted_name", "non_reserved_word",
  9942  // "unreserved_keyword", "non_reserved_word_or_sconst" etc. defined
  9943  // below are low-level, structural constructs.
  9944  //
  9945  // They are separate only because having them all as one rule would
  9946  // make the rest of the grammar ambiguous. However, because they are
  9947  // separate the question is then raised throughout the rest of the
  9948  // grammar: which of the name non-terminals should one use when
  9949  // defining a grammar rule?  Is an index a "name" or
  9950  // "unrestricted_name"? A partition? What about an index option?
  9951  //
  9952  // To make the decision easier, this section of the grammar creates
  9953  // meaningful, purpose-specific aliases to the non-terminals. These
  9954  // both make it easier to decide "which one should I use in this
  9955  // context" and also improves the readability of
  9956  // automatically-generated syntax diagrams.
  9957  
  9958  // Note: newlines between non-terminals matter to the doc generator.
  9959  
  9960  collation_name:        unrestricted_name
  9961  
  9962  partition_name:        unrestricted_name
  9963  
  9964  index_name:            unrestricted_name
  9965  
  9966  opt_index_name:        opt_name
  9967  
  9968  zone_name:             unrestricted_name
  9969  
  9970  target_name:           unrestricted_name
  9971  
  9972  constraint_name:       name
  9973  
  9974  database_name:         name
  9975  
  9976  column_name:           name
  9977  
  9978  family_name:           name
  9979  
  9980  opt_family_name:       opt_name
  9981  
  9982  table_alias_name:      name
  9983  
  9984  statistics_name:       name
  9985  
  9986  window_name:           name
  9987  
  9988  view_name:             table_name
  9989  
  9990  type_name:             db_object_name
  9991  
  9992  sequence_name:         db_object_name
  9993  
  9994  schema_name:           name
  9995  
  9996  table_name:            db_object_name
  9997  
  9998  standalone_index_name: db_object_name
  9999  
 10000  explain_option_name:   non_reserved_word
 10001  
 10002  cursor_name:           name
 10003  
 10004  // Names for column references.
 10005  // Accepted patterns:
 10006  // <colname>
 10007  // <table>.<colname>
 10008  // <schema>.<table>.<colname>
 10009  // <catalog/db>.<schema>.<table>.<colname>
 10010  //
 10011  // Note: the rule for accessing compound types, if those are ever
 10012  // supported, is not to be handled here. The syntax `a.b.c.d....y.z`
 10013  // in `select a.b.c.d from t` *always* designates a column `z` in a
 10014  // table `y`, regardless of the meaning of what's before.
 10015  column_path:
 10016    name
 10017    {
 10018        $$.val = &tree.UnresolvedName{NumParts:1, Parts: tree.NameParts{$1}}
 10019    }
 10020  | prefixed_column_path
 10021  
 10022  prefixed_column_path:
 10023    db_object_name_component '.' unrestricted_name
 10024    {
 10025        $$.val = &tree.UnresolvedName{NumParts:2, Parts: tree.NameParts{$3,$1}}
 10026    }
 10027  | db_object_name_component '.' unrestricted_name '.' unrestricted_name
 10028    {
 10029        $$.val = &tree.UnresolvedName{NumParts:3, Parts: tree.NameParts{$5,$3,$1}}
 10030    }
 10031  | db_object_name_component '.' unrestricted_name '.' unrestricted_name '.' unrestricted_name
 10032    {
 10033        $$.val = &tree.UnresolvedName{NumParts:4, Parts: tree.NameParts{$7,$5,$3,$1}}
 10034    }
 10035  
 10036  // Names for column references and wildcards.
 10037  // Accepted patterns:
 10038  // - those from column_path
 10039  // - <table>.*
 10040  // - <schema>.<table>.*
 10041  // - <catalog/db>.<schema>.<table>.*
 10042  // The single unqualified star is handled separately by target_elem.
 10043  column_path_with_star:
 10044    column_path
 10045  | db_object_name_component '.' unrestricted_name '.' unrestricted_name '.' '*'
 10046    {
 10047      $$.val = &tree.UnresolvedName{Star:true, NumParts:4, Parts: tree.NameParts{"",$5,$3,$1}}
 10048    }
 10049  | db_object_name_component '.' unrestricted_name '.' '*'
 10050    {
 10051      $$.val = &tree.UnresolvedName{Star:true, NumParts:3, Parts: tree.NameParts{"",$3,$1}}
 10052    }
 10053  | db_object_name_component '.' '*'
 10054    {
 10055      $$.val = &tree.UnresolvedName{Star:true, NumParts:2, Parts: tree.NameParts{"",$1}}
 10056    }
 10057  
 10058  // Names for functions.
 10059  // The production for a qualified func_name has to exactly match the production
 10060  // for a column_path, because we cannot tell which we are parsing until
 10061  // we see what comes after it ('(' or SCONST for a func_name, anything else for
 10062  // a name).
 10063  // However we cannot use column_path directly, because for a single function name
 10064  // we allow more possible tokens than a simple column name.
 10065  func_name:
 10066    type_function_name
 10067    {
 10068      $$.val = &tree.UnresolvedName{NumParts:1, Parts: tree.NameParts{$1}}
 10069    }
 10070  | prefixed_column_path
 10071  
 10072  // func_name_no_crdb_extra is the same rule as func_name, but does not
 10073  // contain some CRDB specific keywords like FAMILY.
 10074  func_name_no_crdb_extra:
 10075    type_function_name_no_crdb_extra
 10076    {
 10077      $$.val = &tree.UnresolvedName{NumParts:1, Parts: tree.NameParts{$1}}
 10078    }
 10079  | prefixed_column_path
 10080  
 10081  // Names for database objects (tables, sequences, views, stored functions).
 10082  // Accepted patterns:
 10083  // <table>
 10084  // <schema>.<table>
 10085  // <catalog/db>.<schema>.<table>
 10086  db_object_name:
 10087    simple_db_object_name
 10088  | complex_db_object_name
 10089  
 10090  // simple_db_object_name is the part of db_object_name that recognizes
 10091  // simple identifiers.
 10092  simple_db_object_name:
 10093    db_object_name_component
 10094    {
 10095      aIdx := sqllex.(*lexer).NewAnnotation()
 10096      res, err := tree.NewUnresolvedObjectName(1, [3]string{$1}, aIdx)
 10097      if err != nil { return setErr(sqllex, err) }
 10098      $$.val = res
 10099    }
 10100  
 10101  // complex_db_object_name is the part of db_object_name that recognizes
 10102  // composite names (not simple identifiers).
 10103  // It is split away from db_object_name in order to enable the definition
 10104  // of table_pattern.
 10105  complex_db_object_name:
 10106    db_object_name_component '.' unrestricted_name
 10107    {
 10108      aIdx := sqllex.(*lexer).NewAnnotation()
 10109      res, err := tree.NewUnresolvedObjectName(2, [3]string{$3, $1}, aIdx)
 10110      if err != nil { return setErr(sqllex, err) }
 10111      $$.val = res
 10112    }
 10113  | db_object_name_component '.' unrestricted_name '.' unrestricted_name
 10114    {
 10115      aIdx := sqllex.(*lexer).NewAnnotation()
 10116      res, err := tree.NewUnresolvedObjectName(3, [3]string{$5, $3, $1}, aIdx)
 10117      if err != nil { return setErr(sqllex, err) }
 10118      $$.val = res
 10119    }
 10120  
 10121  // DB object name component -- this cannot not include any reserved
 10122  // keyword because of ambiguity after FROM, but we've been too lax
 10123  // with reserved keywords and made INDEX and FAMILY reserved, so we're
 10124  // trying to gain them back here.
 10125  db_object_name_component:
 10126    name
 10127  | type_func_name_crdb_extra_keyword
 10128  | cockroachdb_extra_reserved_keyword
 10129  
 10130  // General name --- names that can be column, table, etc names.
 10131  name:
 10132    IDENT
 10133  | unreserved_keyword
 10134  | col_name_keyword
 10135  
 10136  opt_name:
 10137    name
 10138  | /* EMPTY */
 10139    {
 10140      $$ = ""
 10141    }
 10142  
 10143  opt_name_parens:
 10144    '(' name ')'
 10145    {
 10146      $$ = $2
 10147    }
 10148  | /* EMPTY */
 10149    {
 10150      $$ = ""
 10151    }
 10152  
 10153  // Structural, low-level names
 10154  
 10155  // Non-reserved word and also string literal constants.
 10156  non_reserved_word_or_sconst:
 10157    non_reserved_word
 10158  | SCONST
 10159  
 10160  // Type/function identifier --- names that can be type or function names.
 10161  type_function_name:
 10162    IDENT
 10163  | unreserved_keyword
 10164  | type_func_name_keyword
 10165  
 10166  // Type/function identifier without CRDB extra reserved keywords.
 10167  type_function_name_no_crdb_extra:
 10168    IDENT
 10169  | unreserved_keyword
 10170  | type_func_name_no_crdb_extra_keyword
 10171  
 10172  // Any not-fully-reserved word --- these names can be, eg, variable names.
 10173  non_reserved_word:
 10174    IDENT
 10175  | unreserved_keyword
 10176  | col_name_keyword
 10177  | type_func_name_keyword
 10178  
 10179  // Unrestricted name --- allowable names when there is no ambiguity with even
 10180  // reserved keywords, like in "AS" clauses. This presently includes *all*
 10181  // Postgres keywords.
 10182  unrestricted_name:
 10183    IDENT
 10184  | unreserved_keyword
 10185  | col_name_keyword
 10186  | type_func_name_keyword
 10187  | reserved_keyword
 10188  
 10189  // Keyword category lists. Generally, every keyword present in the Postgres
 10190  // grammar should appear in exactly one of these lists.
 10191  //
 10192  // Put a new keyword into the first list that it can go into without causing
 10193  // shift or reduce conflicts. The earlier lists define "less reserved"
 10194  // categories of keywords.
 10195  //
 10196  // "Unreserved" keywords --- available for use as any kind of name.
 10197  unreserved_keyword:
 10198    ABORT
 10199  | ACTION
 10200  | ADD
 10201  | ADMIN
 10202  | AFTER
 10203  | AGGREGATE
 10204  | ALTER
 10205  | ALWAYS
 10206  | AT
 10207  | ATTRIBUTE
 10208  | AUTOMATIC
 10209  | AUTHORIZATION
 10210  | BACKUP
 10211  | BEFORE
 10212  | BEGIN
 10213  | BUCKET_COUNT
 10214  | BUNDLE
 10215  | BY
 10216  | CACHE
 10217  | CANCEL
 10218  | CASCADE
 10219  | CHANGEFEED
 10220  | CLOSE
 10221  | CLUSTER
 10222  | COLUMNS
 10223  | COMMENT
 10224  | COMMENTS
 10225  | COMMIT
 10226  | COMMITTED
 10227  | COMPACT
 10228  | COMPLETE
 10229  | CONFLICT
 10230  | CONFIGURATION
 10231  | CONFIGURATIONS
 10232  | CONFIGURE
 10233  | CONSTRAINTS
 10234  | CONVERSION
 10235  | COPY
 10236  | COVERING
 10237  | CREATEROLE
 10238  | CUBE
 10239  | CURRENT
 10240  | CYCLE
 10241  | DATA
 10242  | DATABASE
 10243  | DATABASES
 10244  | DAY
 10245  | DEALLOCATE
 10246  | DECLARE
 10247  | DELETE
 10248  | DEFAULTS
 10249  | DEFERRED
 10250  | DISCARD
 10251  | DOMAIN
 10252  | DOUBLE
 10253  | DROP
 10254  | ENCODING
 10255  | ENUM
 10256  | ESCAPE
 10257  | EXCLUDE
 10258  | EXCLUDING
 10259  | EXECUTE
 10260  | EXPERIMENTAL
 10261  | EXPERIMENTAL_AUDIT
 10262  | EXPERIMENTAL_FINGERPRINTS
 10263  | EXPERIMENTAL_RELOCATE
 10264  | EXPERIMENTAL_REPLICA
 10265  | EXPIRATION
 10266  | EXPLAIN
 10267  | EXPORT
 10268  | EXTENSION
 10269  | FILES
 10270  | FILTER
 10271  | FIRST
 10272  | FOLLOWING
 10273  | FORCE_INDEX
 10274  | FUNCTION
 10275  | GENERATED
 10276  | GEOMETRYCOLLECTION
 10277  | GLOBAL
 10278  | GRANTS
 10279  | GROUPS
 10280  | HASH
 10281  | HIGH
 10282  | HISTOGRAM
 10283  | HOUR
 10284  | IDENTITY
 10285  | IMMEDIATE
 10286  | IMPORT
 10287  | INCLUDE
 10288  | INCLUDING
 10289  | INCREMENT
 10290  | INCREMENTAL
 10291  | INDEXES
 10292  | INJECT
 10293  | INSERT
 10294  | INTERLEAVE
 10295  | INVERTED
 10296  | ISOLATION
 10297  | JOB
 10298  | JOBS
 10299  | JSON
 10300  | KEY
 10301  | KEYS
 10302  | KV
 10303  | LANGUAGE
 10304  | LAST
 10305  | LC_COLLATE
 10306  | LC_CTYPE
 10307  | LEASE
 10308  | LESS
 10309  | LEVEL
 10310  | LINESTRING
 10311  | LIST
 10312  | LOCAL
 10313  | LOCKED
 10314  | LOGIN
 10315  | LOOKUP
 10316  | LOW
 10317  | MATCH
 10318  | MATERIALIZED
 10319  | MAXVALUE
 10320  | MERGE
 10321  | MINUTE
 10322  | MINVALUE
 10323  | MULTILINESTRING
 10324  | MULTIPOINT
 10325  | MULTIPOLYGON
 10326  | MONTH
 10327  | NAMES
 10328  | NAN
 10329  | NEXT
 10330  | NO
 10331  | NORMAL
 10332  | NO_INDEX_JOIN
 10333  | NOCREATEROLE
 10334  | NOLOGIN
 10335  | NOWAIT
 10336  | NULLS
 10337  | IGNORE_FOREIGN_KEYS
 10338  | OF
 10339  | OFF
 10340  | OIDS
 10341  | OPERATOR
 10342  | OPT
 10343  | OPTION
 10344  | OPTIONS
 10345  | ORDINALITY
 10346  | OTHERS
 10347  | OVER
 10348  | OWNED
 10349  | OWNER
 10350  | PARENT
 10351  | PARTIAL
 10352  | PARTITION
 10353  | PARTITIONS
 10354  | PASSWORD
 10355  | PAUSE
 10356  | PHYSICAL
 10357  | PLAN
 10358  | PLANS
 10359  | PRECEDING
 10360  | PREPARE
 10361  | PRESERVE
 10362  | PRIORITY
 10363  | PUBLIC
 10364  | PUBLICATION
 10365  | QUERIES
 10366  | QUERY
 10367  | RANGE
 10368  | RANGES
 10369  | READ
 10370  | RECURSIVE
 10371  | REF
 10372  | REINDEX
 10373  | RELEASE
 10374  | RENAME
 10375  | REPEATABLE
 10376  | REPLACE
 10377  | RESET
 10378  | RESTORE
 10379  | RESTRICT
 10380  | RESUME
 10381  | REVOKE
 10382  | ROLE
 10383  | ROLES
 10384  | ROLLBACK
 10385  | ROLLUP
 10386  | ROWS
 10387  | RULE
 10388  | SETTING
 10389  | SETTINGS
 10390  | STATUS
 10391  | SAVEPOINT
 10392  | SCATTER
 10393  | SCHEMA
 10394  | SCHEMAS
 10395  | SCRUB
 10396  | SEARCH
 10397  | SECOND
 10398  | SERIALIZABLE
 10399  | SEQUENCE
 10400  | SEQUENCES
 10401  | SERVER
 10402  | SESSION
 10403  | SESSIONS
 10404  | SET
 10405  | SHARE
 10406  | SHOW
 10407  | SIMPLE
 10408  | SKIP
 10409  | SNAPSHOT
 10410  | SPLIT
 10411  | SQL
 10412  | START
 10413  | STATISTICS
 10414  | STDIN
 10415  | STORAGE
 10416  | STORE
 10417  | STORED
 10418  | STORING
 10419  | STRICT
 10420  | SUBSCRIPTION
 10421  | SYNTAX
 10422  | SYSTEM
 10423  | TABLES
 10424  | TEMP
 10425  | TEMPLATE
 10426  | TEMPORARY
 10427  | TESTING_RELOCATE
 10428  | TEXT
 10429  | TIES
 10430  | TRACE
 10431  | TRANSACTION
 10432  | TRIGGER
 10433  | TRUNCATE
 10434  | TRUSTED
 10435  | TYPE
 10436  | THROTTLING
 10437  | UNBOUNDED
 10438  | UNCOMMITTED
 10439  | UNKNOWN
 10440  | UNLOGGED
 10441  | UNSPLIT
 10442  | UNTIL
 10443  | UPDATE
 10444  | UPSERT
 10445  | USE
 10446  | USERS
 10447  | VALID
 10448  | VALIDATE
 10449  | VALUE
 10450  | VARYING
 10451  | VIEW
 10452  | WITHIN
 10453  | WITHOUT
 10454  | WRITE
 10455  | YEAR
 10456  | ZONE
 10457  
 10458  // Column identifier --- keywords that can be column, table, etc names.
 10459  //
 10460  // Many of these keywords will in fact be recognized as type or function names
 10461  // too; but they have special productions for the purpose, and so can't be
 10462  // treated as "generic" type or function names.
 10463  //
 10464  // The type names appearing here are not usable as function names because they
 10465  // can be followed by '(' in typename productions, which looks too much like a
 10466  // function call for an LR(1) parser.
 10467  col_name_keyword:
 10468    ANNOTATE_TYPE
 10469  | BETWEEN
 10470  | BIGINT
 10471  | BIT
 10472  | BOOLEAN
 10473  | CHAR
 10474  | CHARACTER
 10475  | CHARACTERISTICS
 10476  | COALESCE
 10477  | DEC
 10478  | DECIMAL
 10479  | EXISTS
 10480  | EXTRACT
 10481  | EXTRACT_DURATION
 10482  | FLOAT
 10483  | GEOGRAPHY
 10484  | GEOMETRY
 10485  | GREATEST
 10486  | GROUPING
 10487  | IF
 10488  | IFERROR
 10489  | IFNULL
 10490  | INT
 10491  | INTEGER
 10492  | INTERVAL
 10493  | ISERROR
 10494  | LEAST
 10495  | NULLIF
 10496  | NUMERIC
 10497  | OUT
 10498  | OVERLAY
 10499  | POINT
 10500  | POLYGON
 10501  | POSITION
 10502  | PRECISION
 10503  | REAL
 10504  | ROW
 10505  | SMALLINT
 10506  | STRING
 10507  | SUBSTRING
 10508  | TIME
 10509  | TIMETZ
 10510  | TIMESTAMP
 10511  | TIMESTAMPTZ
 10512  | TREAT
 10513  | TRIM
 10514  | VALUES
 10515  | VARBIT
 10516  | VARCHAR
 10517  | VIRTUAL
 10518  | WORK
 10519  
 10520  // type_func_name_keyword contains both the standard set of
 10521  // type_func_name_keyword's along with the set of CRDB extensions.
 10522  type_func_name_keyword:
 10523    type_func_name_no_crdb_extra_keyword
 10524  | type_func_name_crdb_extra_keyword
 10525  
 10526  // Type/function identifier --- keywords that can be type or function names.
 10527  //
 10528  // Most of these are keywords that are used as operators in expressions; in
 10529  // general such keywords can't be column names because they would be ambiguous
 10530  // with variables, but they are unambiguous as function identifiers.
 10531  //
 10532  // Do not include POSITION, SUBSTRING, etc here since they have explicit
 10533  // productions in a_expr to support the goofy SQL9x argument syntax.
 10534  // - thomas 2000-11-28
 10535  //
 10536  // *** DO NOT ADD COCKROACHDB-SPECIFIC KEYWORDS HERE ***
 10537  //
 10538  // See type_func_name_crdb_extra_keyword below.
 10539  type_func_name_no_crdb_extra_keyword:
 10540    COLLATION
 10541  | CROSS
 10542  | FULL
 10543  | INNER
 10544  | ILIKE
 10545  | IS
 10546  | ISNULL
 10547  | JOIN
 10548  | LEFT
 10549  | LIKE
 10550  | NATURAL
 10551  | NONE
 10552  | NOTNULL
 10553  | OUTER
 10554  | OVERLAPS
 10555  | RIGHT
 10556  | SIMILAR
 10557  
 10558  // CockroachDB-specific keywords that can be used in type/function
 10559  // identifiers.
 10560  //
 10561  // *** REFRAIN FROM ADDING KEYWORDS HERE ***
 10562  //
 10563  // Adding keywords here creates non-resolvable incompatibilities with
 10564  // postgres clients.
 10565  //
 10566  type_func_name_crdb_extra_keyword:
 10567    FAMILY
 10568  
 10569  // Reserved keyword --- these keywords are usable only as a unrestricted_name.
 10570  //
 10571  // Keywords appear here if they could not be distinguished from variable, type,
 10572  // or function names in some contexts.
 10573  //
 10574  // *** NEVER ADD KEYWORDS HERE ***
 10575  //
 10576  // See cockroachdb_extra_reserved_keyword below.
 10577  //
 10578  reserved_keyword:
 10579    ALL
 10580  | ANALYSE
 10581  | ANALYZE
 10582  | AND
 10583  | ANY
 10584  | ARRAY
 10585  | AS
 10586  | ASC
 10587  | ASYMMETRIC
 10588  | BOTH
 10589  | CASE
 10590  | CAST
 10591  | CHECK
 10592  | COLLATE
 10593  | COLUMN
 10594  | CONCURRENTLY
 10595  | CONSTRAINT
 10596  | CREATE
 10597  | CURRENT_CATALOG
 10598  | CURRENT_DATE
 10599  | CURRENT_ROLE
 10600  | CURRENT_SCHEMA
 10601  | CURRENT_TIME
 10602  | CURRENT_TIMESTAMP
 10603  | CURRENT_USER
 10604  | DEFAULT
 10605  | DEFERRABLE
 10606  | DESC
 10607  | DISTINCT
 10608  | DO
 10609  | ELSE
 10610  | END
 10611  | EXCEPT
 10612  | FALSE
 10613  | FETCH
 10614  | FOR
 10615  | FOREIGN
 10616  | FROM
 10617  | GRANT
 10618  | GROUP
 10619  | HAVING
 10620  | IN
 10621  | INITIALLY
 10622  | INTERSECT
 10623  | INTO
 10624  | LATERAL
 10625  | LEADING
 10626  | LIMIT
 10627  | LOCALTIME
 10628  | LOCALTIMESTAMP
 10629  | NOT
 10630  | NULL
 10631  | OFFSET
 10632  | ON
 10633  | ONLY
 10634  | OR
 10635  | ORDER
 10636  | PLACING
 10637  | PRIMARY
 10638  | REFERENCES
 10639  | RETURNING
 10640  | SELECT
 10641  | SESSION_USER
 10642  | SOME
 10643  | SYMMETRIC
 10644  | TABLE
 10645  | THEN
 10646  | TO
 10647  | TRAILING
 10648  | TRUE
 10649  | UNION
 10650  | UNIQUE
 10651  | USER
 10652  | USING
 10653  | VARIADIC
 10654  | WHEN
 10655  | WHERE
 10656  | WINDOW
 10657  | WITH
 10658  | cockroachdb_extra_reserved_keyword
 10659  
 10660  // Reserved keywords in CockroachDB, in addition to those reserved in
 10661  // PostgreSQL.
 10662  //
 10663  // *** REFRAIN FROM ADDING KEYWORDS HERE ***
 10664  //
 10665  // Adding keywords here creates non-resolvable incompatibilities with
 10666  // postgres clients.
 10667  cockroachdb_extra_reserved_keyword:
 10668    INDEX
 10669  | NOTHING
 10670  
 10671  %%