000001  %include {
000002  /*
000003  ** 2001-09-15
000004  **
000005  ** The author disclaims copyright to this source code.  In place of
000006  ** a legal notice, here is a blessing:
000007  **
000008  **    May you do good and not evil.
000009  **    May you find forgiveness for yourself and forgive others.
000010  **    May you share freely, never taking more than you give.
000011  **
000012  *************************************************************************
000013  ** This file contains SQLite's SQL parser.
000014  **
000015  ** The canonical source code to this file ("parse.y") is a Lemon grammar 
000016  ** file that specifies the input grammar and actions to take while parsing.
000017  ** That input file is processed by Lemon to generate a C-language 
000018  ** implementation of a parser for the given grammar.  You might be reading
000019  ** this comment as part of the translated C-code.  Edits should be made
000020  ** to the original parse.y sources.
000021  */
000022  }
000023  
000024  // Function used to enlarge the parser stack, if needed
000025  %realloc parserStackRealloc
000026  %free    sqlite3_free
000027  
000028  // All token codes are small integers with #defines that begin with "TK_"
000029  %token_prefix TK_
000030  
000031  // The type of the data attached to each token is Token.  This is also the
000032  // default type for non-terminals.
000033  //
000034  %token_type {Token}
000035  %default_type {Token}
000036  
000037  // An extra argument to the constructor for the parser, which is available
000038  // to all actions.
000039  %extra_context {Parse *pParse}
000040  
000041  // This code runs whenever there is a syntax error
000042  //
000043  %syntax_error {
000044    UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
000045    if( TOKEN.z[0] ){
000046      sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
000047    }else{
000048      sqlite3ErrorMsg(pParse, "incomplete input");
000049    }
000050  }
000051  %stack_overflow {
000052    sqlite3OomFault(pParse->db);
000053  }
000054  
000055  // The name of the generated procedure that implements the parser
000056  // is as follows:
000057  %name sqlite3Parser
000058  
000059  // The following text is included near the beginning of the C source
000060  // code file that implements the parser.
000061  //
000062  %include {
000063  #include "sqliteInt.h"
000064  
000065  /*
000066  ** Disable all error recovery processing in the parser push-down
000067  ** automaton.
000068  */
000069  #define YYNOERRORRECOVERY 1
000070  
000071  /*
000072  ** Make yytestcase() the same as testcase()
000073  */
000074  #define yytestcase(X) testcase(X)
000075  
000076  /*
000077  ** Indicate that sqlite3ParserFree() will never be called with a null
000078  ** pointer.
000079  */
000080  #define YYPARSEFREENEVERNULL 1
000081  
000082  /*
000083  ** In the amalgamation, the parse.c file generated by lemon and the
000084  ** tokenize.c file are concatenated.  In that case, sqlite3RunParser()
000085  ** has access to the the size of the yyParser object and so the parser
000086  ** engine can be allocated from stack.  In that case, only the
000087  ** sqlite3ParserInit() and sqlite3ParserFinalize() routines are invoked
000088  ** and the sqlite3ParserAlloc() and sqlite3ParserFree() routines can be
000089  ** omitted.
000090  */
000091  #ifdef SQLITE_AMALGAMATION
000092  # define sqlite3Parser_ENGINEALWAYSONSTACK 1
000093  #endif
000094  
000095  /*
000096  ** Alternative datatype for the argument to the malloc() routine passed
000097  ** into sqlite3ParserAlloc().  The default is size_t.
000098  */
000099  #define YYMALLOCARGTYPE  u64
000100  
000101  /*
000102  ** An instance of the following structure describes the event of a
000103  ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
000104  ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
000105  **
000106  **      UPDATE ON (a,b,c)
000107  **
000108  ** Then the "b" IdList records the list "a,b,c".
000109  */
000110  struct TrigEvent { int a; IdList * b; };
000111  
000112  struct FrameBound     { int eType; Expr *pExpr; };
000113  
000114  /*
000115  ** Disable lookaside memory allocation for objects that might be
000116  ** shared across database connections.
000117  */
000118  static void disableLookaside(Parse *pParse){
000119    sqlite3 *db = pParse->db;
000120    pParse->disableLookaside++;
000121    DisableLookaside;
000122  }
000123  
000124  #if !defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) \
000125   && defined(SQLITE_UDL_CAPABLE_PARSER)
000126  /*
000127  ** Issue an error message if an ORDER BY or LIMIT clause occurs on an
000128  ** UPDATE or DELETE statement.
000129  */
000130  static void updateDeleteLimitError(
000131    Parse *pParse,
000132    ExprList *pOrderBy,
000133    Expr *pLimit
000134  ){
000135    if( pOrderBy ){
000136      sqlite3ErrorMsg(pParse, "syntax error near \"ORDER BY\"");
000137    }else{
000138      sqlite3ErrorMsg(pParse, "syntax error near \"LIMIT\"");
000139    }
000140    sqlite3ExprListDelete(pParse->db, pOrderBy);
000141    sqlite3ExprDelete(pParse->db, pLimit);
000142  }
000143  #endif /* SQLITE_ENABLE_UPDATE_DELETE_LIMIT */
000144  
000145  } // end %include
000146  
000147  // Input is a single SQL command
000148  input ::= cmdlist.
000149  cmdlist ::= cmdlist ecmd.
000150  cmdlist ::= ecmd.
000151  ecmd ::= SEMI.
000152  ecmd ::= cmdx SEMI.
000153  %ifndef SQLITE_OMIT_EXPLAIN
000154  ecmd ::= explain cmdx SEMI.       {NEVER-REDUCE}
000155  explain ::= EXPLAIN.              { if( pParse->pReprepare==0 ) pParse->explain = 1; }
000156  explain ::= EXPLAIN QUERY PLAN.   { if( pParse->pReprepare==0 ) pParse->explain = 2; }
000157  %endif  SQLITE_OMIT_EXPLAIN
000158  cmdx ::= cmd.           { sqlite3FinishCoding(pParse); }
000159  
000160  ///////////////////// Begin and end transactions. ////////////////////////////
000161  //
000162  
000163  cmd ::= BEGIN transtype(Y) trans_opt.  {sqlite3BeginTransaction(pParse, Y);}
000164  trans_opt ::= .
000165  trans_opt ::= TRANSACTION.
000166  trans_opt ::= TRANSACTION nm.
000167  %type transtype {int}
000168  transtype(A) ::= .             {A = TK_DEFERRED;}
000169  transtype(A) ::= DEFERRED(X).  {A = @X; /*A-overwrites-X*/}
000170  transtype(A) ::= IMMEDIATE(X). {A = @X; /*A-overwrites-X*/}
000171  transtype(A) ::= EXCLUSIVE(X). {A = @X; /*A-overwrites-X*/}
000172  cmd ::= COMMIT|END(X) trans_opt.   {sqlite3EndTransaction(pParse,@X);}
000173  cmd ::= ROLLBACK(X) trans_opt.     {sqlite3EndTransaction(pParse,@X);}
000174  
000175  savepoint_opt ::= SAVEPOINT.
000176  savepoint_opt ::= .
000177  cmd ::= SAVEPOINT nm(X). {
000178    sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &X);
000179  }
000180  cmd ::= RELEASE savepoint_opt nm(X). {
000181    sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &X);
000182  }
000183  cmd ::= ROLLBACK trans_opt TO savepoint_opt nm(X). {
000184    sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &X);
000185  }
000186  
000187  ///////////////////// The CREATE TABLE statement ////////////////////////////
000188  //
000189  cmd ::= create_table create_table_args.
000190  create_table ::= createkw temp(T) TABLE ifnotexists(E) nm(Y) dbnm(Z). {
000191     sqlite3StartTable(pParse,&Y,&Z,T,0,0,E);
000192  }
000193  createkw(A) ::= CREATE(A).  {disableLookaside(pParse);}
000194  
000195  %type ifnotexists {int}
000196  ifnotexists(A) ::= .              {A = 0;}
000197  ifnotexists(A) ::= IF NOT EXISTS. {A = 1;}
000198  %type temp {int}
000199  %ifndef SQLITE_OMIT_TEMPDB
000200  temp(A) ::= TEMP.  {A = pParse->db->init.busy==0;}
000201  %endif  SQLITE_OMIT_TEMPDB
000202  temp(A) ::= .      {A = 0;}
000203  create_table_args ::= LP columnlist conslist_opt(X) RP(E) table_option_set(F). {
000204    sqlite3EndTable(pParse,&X,&E,F,0);
000205  }
000206  create_table_args ::= AS select(S). {
000207    sqlite3EndTable(pParse,0,0,0,S);
000208    sqlite3SelectDelete(pParse->db, S);
000209  }
000210  %type table_option_set {u32}
000211  %type table_option {u32}
000212  table_option_set(A) ::= .    {A = 0;}
000213  table_option_set(A) ::= table_option(A).
000214  table_option_set(A) ::= table_option_set(X) COMMA table_option(Y). {A = X|Y;}
000215  table_option(A) ::= WITHOUT nm(X). {
000216    if( X.n==5 && sqlite3_strnicmp(X.z,"rowid",5)==0 ){
000217      A = TF_WithoutRowid | TF_NoVisibleRowid;
000218    }else{
000219      A = 0;
000220      sqlite3ErrorMsg(pParse, "unknown table option: %.*s", X.n, X.z);
000221    }
000222  }
000223  table_option(A) ::= nm(X). {
000224    if( X.n==6 && sqlite3_strnicmp(X.z,"strict",6)==0 ){
000225      A = TF_Strict;
000226    }else{
000227      A = 0;
000228      sqlite3ErrorMsg(pParse, "unknown table option: %.*s", X.n, X.z);
000229    }
000230  }
000231  columnlist ::= columnlist COMMA columnname carglist.
000232  columnlist ::= columnname carglist.
000233  columnname(A) ::= nm(A) typetoken(Y). {sqlite3AddColumn(pParse,A,Y);}
000234  
000235  // Declare some tokens early in order to influence their values, to 
000236  // improve performance and reduce the executable size.  The goal here is
000237  // to get the "jump" operations in ISNULL through ESCAPE to have numeric
000238  // values that are early enough so that all jump operations are clustered
000239  // at the beginning.
000240  //
000241  %token ABORT ACTION AFTER ANALYZE ASC ATTACH BEFORE BEGIN BY CASCADE CAST.
000242  %token CONFLICT DATABASE DEFERRED DESC DETACH EACH END EXCLUSIVE EXPLAIN FAIL.
000243  %token OR AND NOT IS MATCH LIKE_KW BETWEEN IN ISNULL NOTNULL NE EQ.
000244  %token GT LE LT GE ESCAPE.
000245  
000246  // The following directive causes tokens ABORT, AFTER, ASC, etc. to
000247  // fallback to ID if they will not parse as their original value.
000248  // This obviates the need for the "id" nonterminal.
000249  //
000250  %fallback ID
000251    ABORT ACTION AFTER ANALYZE ASC ATTACH BEFORE BEGIN BY CASCADE CAST COLUMNKW
000252    CONFLICT DATABASE DEFERRED DESC DETACH DO
000253    EACH END EXCLUSIVE EXPLAIN FAIL FOR
000254    IGNORE IMMEDIATE INITIALLY INSTEAD LIKE_KW MATCH NO PLAN
000255    QUERY KEY OF OFFSET PRAGMA RAISE RECURSIVE RELEASE REPLACE RESTRICT ROW ROWS
000256    ROLLBACK SAVEPOINT TEMP TRIGGER VACUUM VIEW VIRTUAL WITH WITHOUT
000257    NULLS FIRST LAST
000258  %ifdef SQLITE_OMIT_COMPOUND_SELECT
000259    EXCEPT INTERSECT UNION
000260  %endif SQLITE_OMIT_COMPOUND_SELECT
000261  %ifndef SQLITE_OMIT_WINDOWFUNC
000262    CURRENT FOLLOWING PARTITION PRECEDING RANGE UNBOUNDED
000263    EXCLUDE GROUPS OTHERS TIES
000264  %endif SQLITE_OMIT_WINDOWFUNC
000265  %ifndef SQLITE_OMIT_GENERATED_COLUMNS
000266    GENERATED ALWAYS
000267  %endif
000268    MATERIALIZED
000269    REINDEX RENAME CTIME_KW IF
000270    .
000271  %wildcard ANY.
000272  
000273  // Define operator precedence early so that this is the first occurrence
000274  // of the operator tokens in the grammar.  Keeping the operators together
000275  // causes them to be assigned integer values that are close together,
000276  // which keeps parser tables smaller.
000277  //
000278  // The token values assigned to these symbols is determined by the order
000279  // in which lemon first sees them.  It must be the case that ISNULL/NOTNULL,
000280  // NE/EQ, GT/LE, and GE/LT are separated by only a single value.  See
000281  // the sqlite3ExprIfFalse() routine for additional information on this
000282  // constraint.
000283  //
000284  %left OR.
000285  %left AND.
000286  %right NOT.
000287  %left IS MATCH LIKE_KW BETWEEN IN ISNULL NOTNULL NE EQ.
000288  %left GT LE LT GE.
000289  %right ESCAPE.
000290  %left BITAND BITOR LSHIFT RSHIFT.
000291  %left PLUS MINUS.
000292  %left STAR SLASH REM.
000293  %left CONCAT PTR.
000294  %left COLLATE.
000295  %right BITNOT.
000296  %nonassoc ON.
000297  
000298  // An IDENTIFIER can be a generic identifier, or one of several
000299  // keywords.  Any non-standard keyword can also be an identifier.
000300  //
000301  %token_class id  ID|INDEXED.
000302  
000303  // And "ids" is an identifer-or-string.
000304  //
000305  %token_class ids  ID|STRING.
000306  
000307  // An identifier or a join-keyword
000308  //
000309  %token_class idj  ID|INDEXED|JOIN_KW.
000310  
000311  // The name of a column or table can be any of the following:
000312  //
000313  %type nm {Token}
000314  nm(A) ::= idj(A).
000315  nm(A) ::= STRING(A).
000316  
000317  // A typetoken is really zero or more tokens that form a type name such
000318  // as can be found after the column name in a CREATE TABLE statement.
000319  // Multiple tokens are concatenated to form the value of the typetoken.
000320  //
000321  %type typetoken {Token}
000322  typetoken(A) ::= .   {A.n = 0; A.z = 0;}
000323  typetoken(A) ::= typename(A).
000324  typetoken(A) ::= typename(A) LP signed RP(Y). {
000325    A.n = (int)(&Y.z[Y.n] - A.z);
000326  }
000327  typetoken(A) ::= typename(A) LP signed COMMA signed RP(Y). {
000328    A.n = (int)(&Y.z[Y.n] - A.z);
000329  }
000330  %type typename {Token}
000331  typename(A) ::= ids(A).
000332  typename(A) ::= typename(A) ids(Y). {A.n=Y.n+(int)(Y.z-A.z);}
000333  signed ::= plus_num.
000334  signed ::= minus_num.
000335  
000336  // The scanpt non-terminal takes a value which is a pointer to the
000337  // input text just past the last token that has been shifted into
000338  // the parser.  By surrounding some phrase in the grammar with two
000339  // scanpt non-terminals, we can capture the input text for that phrase.
000340  // For example:
000341  //
000342  //      something ::= .... scanpt(A) phrase scanpt(Z).
000343  //
000344  // The text that is parsed as "phrase" is a string starting at A
000345  // and containing (int)(Z-A) characters.  There might be some extra
000346  // whitespace on either end of the text, but that can be removed in
000347  // post-processing, if needed.
000348  //
000349  %type scanpt {const char*}
000350  scanpt(A) ::= . {
000351    assert( yyLookahead!=YYNOCODE );
000352    A = yyLookaheadToken.z;
000353  }
000354  scantok(A) ::= . {
000355    assert( yyLookahead!=YYNOCODE );
000356    A = yyLookaheadToken;
000357  }
000358  
000359  // "carglist" is a list of additional constraints that come after the
000360  // column name and column type in a CREATE TABLE statement.
000361  //
000362  carglist ::= carglist ccons.
000363  carglist ::= .
000364  ccons ::= CONSTRAINT nm(X).           {pParse->constraintName = X;}
000365  ccons ::= DEFAULT scantok(A) term(X).
000366                              {sqlite3AddDefaultValue(pParse,X,A.z,&A.z[A.n]);}
000367  ccons ::= DEFAULT LP(A) expr(X) RP(Z).
000368                              {sqlite3AddDefaultValue(pParse,X,A.z+1,Z.z);}
000369  ccons ::= DEFAULT PLUS(A) scantok(Z) term(X).
000370                              {sqlite3AddDefaultValue(pParse,X,A.z,&Z.z[Z.n]);}
000371  ccons ::= DEFAULT MINUS(A) scantok(Z) term(X). {
000372    Expr *p = sqlite3PExpr(pParse, TK_UMINUS, X, 0);
000373    sqlite3AddDefaultValue(pParse,p,A.z,&Z.z[Z.n]);
000374  }
000375  ccons ::= DEFAULT scantok id(X).       {
000376    Expr *p = tokenExpr(pParse, TK_STRING, X);
000377    if( p ){
000378      sqlite3ExprIdToTrueFalse(p);
000379      testcase( p->op==TK_TRUEFALSE && sqlite3ExprTruthValue(p) );
000380    }
000381      sqlite3AddDefaultValue(pParse,p,X.z,X.z+X.n);
000382  }
000383  
000384  // In addition to the type name, we also care about the primary key and
000385  // UNIQUE constraints.
000386  //
000387  ccons ::= NULL onconf.
000388  ccons ::= NOT NULL onconf(R).    {sqlite3AddNotNull(pParse, R);}
000389  ccons ::= PRIMARY KEY sortorder(Z) onconf(R) autoinc(I).
000390                                   {sqlite3AddPrimaryKey(pParse,0,R,I,Z);}
000391  ccons ::= UNIQUE onconf(R).      {sqlite3CreateIndex(pParse,0,0,0,0,R,0,0,0,0,
000392                                     SQLITE_IDXTYPE_UNIQUE);}
000393  ccons ::= CHECK LP(A) expr(X) RP(B).  {sqlite3AddCheckConstraint(pParse,X,A.z,B.z);}
000394  ccons ::= REFERENCES nm(T) eidlist_opt(TA) refargs(R).
000395                                   {sqlite3CreateForeignKey(pParse,0,&T,TA,R);}
000396  ccons ::= defer_subclause(D).    {sqlite3DeferForeignKey(pParse,D);}
000397  ccons ::= COLLATE ids(C).        {sqlite3AddCollateType(pParse, &C);}
000398  ccons ::= GENERATED ALWAYS AS generated.
000399  ccons ::= AS generated.
000400  generated ::= LP expr(E) RP.          {sqlite3AddGenerated(pParse,E,0);}
000401  generated ::= LP expr(E) RP ID(TYPE). {sqlite3AddGenerated(pParse,E,&TYPE);}
000402  
000403  // The optional AUTOINCREMENT keyword
000404  %type autoinc {int}
000405  autoinc(X) ::= .          {X = 0;}
000406  autoinc(X) ::= AUTOINCR.  {X = 1;}
000407  
000408  // The next group of rules parses the arguments to a REFERENCES clause
000409  // that determine if the referential integrity checking is deferred or
000410  // or immediate and which determine what action to take if a ref-integ
000411  // check fails.
000412  //
000413  %type refargs {int}
000414  refargs(A) ::= .                  { A = OE_None*0x0101; /* EV: R-19803-45884 */}
000415  refargs(A) ::= refargs(A) refarg(Y). { A = (A & ~Y.mask) | Y.value; }
000416  %type refarg {struct {int value; int mask;}}
000417  refarg(A) ::= MATCH nm.              { A.value = 0;     A.mask = 0x000000; }
000418  refarg(A) ::= ON INSERT refact.      { A.value = 0;     A.mask = 0x000000; }
000419  refarg(A) ::= ON DELETE refact(X).   { A.value = X;     A.mask = 0x0000ff; }
000420  refarg(A) ::= ON UPDATE refact(X).   { A.value = X<<8;  A.mask = 0x00ff00; }
000421  %type refact {int}
000422  refact(A) ::= SET NULL.              { A = OE_SetNull;  /* EV: R-33326-45252 */}
000423  refact(A) ::= SET DEFAULT.           { A = OE_SetDflt;  /* EV: R-33326-45252 */}
000424  refact(A) ::= CASCADE.               { A = OE_Cascade;  /* EV: R-33326-45252 */}
000425  refact(A) ::= RESTRICT.              { A = OE_Restrict; /* EV: R-33326-45252 */}
000426  refact(A) ::= NO ACTION.             { A = OE_None;     /* EV: R-33326-45252 */}
000427  %type defer_subclause {int}
000428  defer_subclause(A) ::= NOT DEFERRABLE init_deferred_pred_opt.     {A = 0;}
000429  defer_subclause(A) ::= DEFERRABLE init_deferred_pred_opt(X).      {A = X;}
000430  %type init_deferred_pred_opt {int}
000431  init_deferred_pred_opt(A) ::= .                       {A = 0;}
000432  init_deferred_pred_opt(A) ::= INITIALLY DEFERRED.     {A = 1;}
000433  init_deferred_pred_opt(A) ::= INITIALLY IMMEDIATE.    {A = 0;}
000434  
000435  conslist_opt(A) ::= .                         {A.n = 0; A.z = 0;}
000436  conslist_opt(A) ::= COMMA(A) conslist.
000437  conslist ::= conslist tconscomma tcons.
000438  conslist ::= tcons.
000439  tconscomma ::= COMMA.            {pParse->constraintName.n = 0;}
000440  tconscomma ::= .
000441  tcons ::= CONSTRAINT nm(X).      {pParse->constraintName = X;}
000442  tcons ::= PRIMARY KEY LP sortlist(X) autoinc(I) RP onconf(R).
000443                                   {sqlite3AddPrimaryKey(pParse,X,R,I,0);}
000444  tcons ::= UNIQUE LP sortlist(X) RP onconf(R).
000445                                   {sqlite3CreateIndex(pParse,0,0,0,X,R,0,0,0,0,
000446                                         SQLITE_IDXTYPE_UNIQUE);}
000447  tcons ::= CHECK LP(A) expr(E) RP(B) onconf.
000448                                   {sqlite3AddCheckConstraint(pParse,E,A.z,B.z);}
000449  tcons ::= FOREIGN KEY LP eidlist(FA) RP
000450            REFERENCES nm(T) eidlist_opt(TA) refargs(R) defer_subclause_opt(D). {
000451      sqlite3CreateForeignKey(pParse, FA, &T, TA, R);
000452      sqlite3DeferForeignKey(pParse, D);
000453  }
000454  %type defer_subclause_opt {int}
000455  defer_subclause_opt(A) ::= .                    {A = 0;}
000456  defer_subclause_opt(A) ::= defer_subclause(A).
000457  
000458  // The following is a non-standard extension that allows us to declare the
000459  // default behavior when there is a constraint conflict.
000460  //
000461  %type onconf {int}
000462  %type orconf {int}
000463  %type resolvetype {int}
000464  onconf(A) ::= .                              {A = OE_Default;}
000465  onconf(A) ::= ON CONFLICT resolvetype(X).    {A = X;}
000466  orconf(A) ::= .                              {A = OE_Default;}
000467  orconf(A) ::= OR resolvetype(X).             {A = X;}
000468  resolvetype(A) ::= raisetype(A).
000469  resolvetype(A) ::= IGNORE.                   {A = OE_Ignore;}
000470  resolvetype(A) ::= REPLACE.                  {A = OE_Replace;}
000471  
000472  ////////////////////////// The DROP TABLE /////////////////////////////////////
000473  //
000474  cmd ::= DROP TABLE ifexists(E) fullname(X). {
000475    sqlite3DropTable(pParse, X, 0, E);
000476  }
000477  %type ifexists {int}
000478  ifexists(A) ::= IF EXISTS.   {A = 1;}
000479  ifexists(A) ::= .            {A = 0;}
000480  
000481  ///////////////////// The CREATE VIEW statement /////////////////////////////
000482  //
000483  %ifndef SQLITE_OMIT_VIEW
000484  cmd ::= createkw(X) temp(T) VIEW ifnotexists(E) nm(Y) dbnm(Z) eidlist_opt(C)
000485            AS select(S). {
000486    sqlite3CreateView(pParse, &X, &Y, &Z, C, S, T, E);
000487  }
000488  cmd ::= DROP VIEW ifexists(E) fullname(X). {
000489    sqlite3DropTable(pParse, X, 1, E);
000490  }
000491  %endif  SQLITE_OMIT_VIEW
000492  
000493  //////////////////////// The SELECT statement /////////////////////////////////
000494  //
000495  cmd ::= select(X).  {
000496    SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0, 0};
000497    sqlite3Select(pParse, X, &dest);
000498    sqlite3SelectDelete(pParse->db, X);
000499  }
000500  
000501  %type select {Select*}
000502  %destructor select {sqlite3SelectDelete(pParse->db, $$);}
000503  %type selectnowith {Select*}
000504  %destructor selectnowith {sqlite3SelectDelete(pParse->db, $$);}
000505  %type oneselect {Select*}
000506  %destructor oneselect {sqlite3SelectDelete(pParse->db, $$);}
000507  
000508  %include {
000509    /*
000510    ** For a compound SELECT statement, make sure p->pPrior->pNext==p for
000511    ** all elements in the list.  And make sure list length does not exceed
000512    ** SQLITE_LIMIT_COMPOUND_SELECT.
000513    */
000514    static void parserDoubleLinkSelect(Parse *pParse, Select *p){
000515      assert( p!=0 );
000516      if( p->pPrior ){
000517        Select *pNext = 0, *pLoop = p;
000518        int mxSelect, cnt = 1;
000519        while(1){
000520          pLoop->pNext = pNext;
000521          pLoop->selFlags |= SF_Compound;
000522          pNext = pLoop;
000523          pLoop = pLoop->pPrior;
000524          if( pLoop==0 ) break;
000525          cnt++;        
000526          if( pLoop->pOrderBy || pLoop->pLimit ){
000527            sqlite3ErrorMsg(pParse,"%s clause should come after %s not before",
000528               pLoop->pOrderBy!=0 ? "ORDER BY" : "LIMIT",
000529               sqlite3SelectOpName(pNext->op));
000530            break;
000531          }
000532        }
000533        if( (p->selFlags & (SF_MultiValue|SF_Values))==0
000534         && (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0
000535         && cnt>mxSelect
000536        ){
000537          sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
000538        }
000539      }
000540    }
000541  
000542    /* Attach a With object describing the WITH clause to a Select
000543    ** object describing the query for which the WITH clause is a prefix.
000544    */
000545    static Select *attachWithToSelect(Parse *pParse, Select *pSelect, With *pWith){
000546      if( pSelect ){
000547        pSelect->pWith = pWith;
000548        parserDoubleLinkSelect(pParse, pSelect);
000549      }else{
000550        sqlite3WithDelete(pParse->db, pWith);
000551      }
000552      return pSelect;
000553    }
000554  
000555    /* Memory allocator for parser stack resizing.  This is a thin wrapper around
000556    ** sqlite3_realloc() that includes a call to sqlite3FaultSim() to facilitate
000557    ** testing.
000558    */
000559    static void *parserStackRealloc(void *pOld, sqlite3_uint64 newSize){
000560      return sqlite3FaultSim(700) ? 0 : sqlite3_realloc(pOld, newSize);
000561    }
000562  }
000563  
000564  %ifndef SQLITE_OMIT_CTE
000565  select(A) ::= WITH wqlist(W) selectnowith(X). {A = attachWithToSelect(pParse,X,W);}
000566  select(A) ::= WITH RECURSIVE wqlist(W) selectnowith(X).
000567                                                {A = attachWithToSelect(pParse,X,W);}
000568  
000569  %endif /* SQLITE_OMIT_CTE */
000570  select(A) ::= selectnowith(A). {
000571    Select *p = A;
000572    if( p ){
000573      parserDoubleLinkSelect(pParse, p);
000574    }
000575  }
000576  
000577  selectnowith(A) ::= oneselect(A).
000578  %ifndef SQLITE_OMIT_COMPOUND_SELECT
000579  selectnowith(A) ::= selectnowith(A) multiselect_op(Y) oneselect(Z).  {
000580    Select *pRhs = Z;
000581    Select *pLhs = A;
000582    if( pRhs && pRhs->pPrior ){
000583      SrcList *pFrom;
000584      Token x;
000585      x.n = 0;
000586      parserDoubleLinkSelect(pParse, pRhs);
000587      pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0);
000588      pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0);
000589    }
000590    if( pRhs ){
000591      pRhs->op = (u8)Y;
000592      pRhs->pPrior = pLhs;
000593      if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue;
000594      pRhs->selFlags &= ~SF_MultiValue;
000595      if( Y!=TK_ALL ) pParse->hasCompound = 1;
000596    }else{
000597      sqlite3SelectDelete(pParse->db, pLhs);
000598    }
000599    A = pRhs;
000600  }
000601  %type multiselect_op {int}
000602  multiselect_op(A) ::= UNION(OP).             {A = @OP; /*A-overwrites-OP*/}
000603  multiselect_op(A) ::= UNION ALL.             {A = TK_ALL;}
000604  multiselect_op(A) ::= EXCEPT|INTERSECT(OP).  {A = @OP; /*A-overwrites-OP*/}
000605  %endif SQLITE_OMIT_COMPOUND_SELECT
000606  
000607  oneselect(A) ::= SELECT distinct(D) selcollist(W) from(X) where_opt(Y)
000608                   groupby_opt(P) having_opt(Q) 
000609                   orderby_opt(Z) limit_opt(L). {
000610    A = sqlite3SelectNew(pParse,W,X,Y,P,Q,Z,D,L);
000611  }
000612  %ifndef SQLITE_OMIT_WINDOWFUNC
000613  oneselect(A) ::= SELECT distinct(D) selcollist(W) from(X) where_opt(Y)
000614                   groupby_opt(P) having_opt(Q) window_clause(R)
000615                   orderby_opt(Z) limit_opt(L). {
000616    A = sqlite3SelectNew(pParse,W,X,Y,P,Q,Z,D,L);
000617    if( A ){
000618      A->pWinDefn = R;
000619    }else{
000620      sqlite3WindowListDelete(pParse->db, R);
000621    }
000622  }
000623  %endif
000624  
000625  
000626  // Single row VALUES clause.
000627  //
000628  %type values {Select*}
000629  oneselect(A) ::= values(A).
000630  %destructor values {sqlite3SelectDelete(pParse->db, $$);}
000631  values(A) ::= VALUES LP nexprlist(X) RP. {
000632    A = sqlite3SelectNew(pParse,X,0,0,0,0,0,SF_Values,0);
000633  }
000634  
000635  // Multiple row VALUES clause.
000636  //
000637  %type mvalues {Select*}
000638  oneselect(A) ::= mvalues(A). {
000639    sqlite3MultiValuesEnd(pParse, A);
000640  }
000641  %destructor mvalues {sqlite3SelectDelete(pParse->db, $$);}
000642  mvalues(A) ::= values(A) COMMA LP nexprlist(Y) RP. {
000643    A = sqlite3MultiValues(pParse, A, Y);
000644  }
000645  mvalues(A) ::= mvalues(A) COMMA LP nexprlist(Y) RP. {
000646    A = sqlite3MultiValues(pParse, A, Y);
000647  }
000648  
000649  // The "distinct" nonterminal is true (1) if the DISTINCT keyword is
000650  // present and false (0) if it is not.
000651  //
000652  %type distinct {int}
000653  distinct(A) ::= DISTINCT.   {A = SF_Distinct;}
000654  distinct(A) ::= ALL.        {A = SF_All;}
000655  distinct(A) ::= .           {A = 0;}
000656  
000657  // selcollist is a list of expressions that are to become the return
000658  // values of the SELECT statement.  The "*" in statements like
000659  // "SELECT * FROM ..." is encoded as a special expression with an
000660  // opcode of TK_ASTERISK.
000661  //
000662  %type selcollist {ExprList*}
000663  %destructor selcollist {sqlite3ExprListDelete(pParse->db, $$);}
000664  %type sclp {ExprList*}
000665  %destructor sclp {sqlite3ExprListDelete(pParse->db, $$);}
000666  sclp(A) ::= selcollist(A) COMMA.
000667  sclp(A) ::= .                                {A = 0;}
000668  selcollist(A) ::= sclp(A) scanpt(B) expr(X) scanpt(Z) as(Y).     {
000669     A = sqlite3ExprListAppend(pParse, A, X);
000670     if( Y.n>0 ) sqlite3ExprListSetName(pParse, A, &Y, 1);
000671     sqlite3ExprListSetSpan(pParse,A,B,Z);
000672  }
000673  selcollist(A) ::= sclp(A) scanpt STAR(X). {
000674    Expr *p = sqlite3Expr(pParse->db, TK_ASTERISK, 0);
000675    sqlite3ExprSetErrorOffset(p, (int)(X.z - pParse->zTail));
000676    A = sqlite3ExprListAppend(pParse, A, p);
000677  }
000678  selcollist(A) ::= sclp(A) scanpt nm(X) DOT STAR(Y). {
000679    Expr *pRight, *pLeft, *pDot;
000680    pRight = sqlite3PExpr(pParse, TK_ASTERISK, 0, 0);
000681    sqlite3ExprSetErrorOffset(pRight, (int)(Y.z - pParse->zTail));
000682    pLeft = tokenExpr(pParse, TK_ID, X);
000683    pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
000684    A = sqlite3ExprListAppend(pParse,A, pDot);
000685  }
000686  
000687  // An option "AS <id>" phrase that can follow one of the expressions that
000688  // define the result set, or one of the tables in the FROM clause.
000689  //
000690  %type as {Token}
000691  as(X) ::= AS nm(Y).    {X = Y;}
000692  as(X) ::= ids(X).
000693  as(X) ::= .            {X.n = 0; X.z = 0;}
000694  
000695  
000696  %type seltablist {SrcList*}
000697  %destructor seltablist {sqlite3SrcListDelete(pParse->db, $$);}
000698  %type stl_prefix {SrcList*}
000699  %destructor stl_prefix {sqlite3SrcListDelete(pParse->db, $$);}
000700  %type from {SrcList*}
000701  %destructor from {sqlite3SrcListDelete(pParse->db, $$);}
000702  
000703  // A complete FROM clause.
000704  //
000705  from(A) ::= .                {A = 0;}
000706  from(A) ::= FROM seltablist(X). {
000707    A = X;
000708    sqlite3SrcListShiftJoinType(pParse,A);
000709  }
000710  
000711  // "seltablist" is a "Select Table List" - the content of the FROM clause
000712  // in a SELECT statement.  "stl_prefix" is a prefix of this list.
000713  //
000714  stl_prefix(A) ::= seltablist(A) joinop(Y).    {
000715     if( ALWAYS(A && A->nSrc>0) ) A->a[A->nSrc-1].fg.jointype = (u8)Y;
000716  }
000717  stl_prefix(A) ::= .                           {A = 0;}
000718  seltablist(A) ::= stl_prefix(A) nm(Y) dbnm(D) as(Z) on_using(N). {
000719    A = sqlite3SrcListAppendFromTerm(pParse,A,&Y,&D,&Z,0,&N);
000720  }
000721  seltablist(A) ::= stl_prefix(A) nm(Y) dbnm(D) as(Z) indexed_by(I) on_using(N). {
000722    A = sqlite3SrcListAppendFromTerm(pParse,A,&Y,&D,&Z,0,&N);
000723    sqlite3SrcListIndexedBy(pParse, A, &I);
000724  }
000725  seltablist(A) ::= stl_prefix(A) nm(Y) dbnm(D) LP exprlist(E) RP as(Z) on_using(N). {
000726    A = sqlite3SrcListAppendFromTerm(pParse,A,&Y,&D,&Z,0,&N);
000727    sqlite3SrcListFuncArgs(pParse, A, E);
000728  }
000729  %ifndef SQLITE_OMIT_SUBQUERY
000730    seltablist(A) ::= stl_prefix(A) LP select(S) RP as(Z) on_using(N). {
000731      A = sqlite3SrcListAppendFromTerm(pParse,A,0,0,&Z,S,&N);
000732    }
000733    seltablist(A) ::= stl_prefix(A) LP seltablist(F) RP as(Z) on_using(N). {
000734      if( A==0 && Z.n==0 && N.pOn==0 && N.pUsing==0 ){
000735        A = F;
000736      }else if( ALWAYS(F!=0) && F->nSrc==1 ){
000737        A = sqlite3SrcListAppendFromTerm(pParse,A,0,0,&Z,0,&N);
000738        if( A ){
000739          SrcItem *pNew = &A->a[A->nSrc-1];
000740          SrcItem *pOld = F->a;
000741          pNew->zName = pOld->zName;
000742          pNew->zDatabase = pOld->zDatabase;
000743          pNew->pSelect = pOld->pSelect;
000744          if( pNew->pSelect && (pNew->pSelect->selFlags & SF_NestedFrom)!=0 ){
000745            pNew->fg.isNestedFrom = 1;
000746          }
000747          if( pOld->fg.isTabFunc ){
000748            pNew->u1.pFuncArg = pOld->u1.pFuncArg;
000749            pOld->u1.pFuncArg = 0;
000750            pOld->fg.isTabFunc = 0;
000751            pNew->fg.isTabFunc = 1;
000752          }
000753          pOld->zName = pOld->zDatabase = 0;
000754          pOld->pSelect = 0;
000755        }
000756        sqlite3SrcListDelete(pParse->db, F);
000757      }else{
000758        Select *pSubquery;
000759        sqlite3SrcListShiftJoinType(pParse,F);
000760        pSubquery = sqlite3SelectNew(pParse,0,F,0,0,0,0,SF_NestedFrom,0);
000761        A = sqlite3SrcListAppendFromTerm(pParse,A,0,0,&Z,pSubquery,&N);
000762      }
000763    }
000764  %endif  SQLITE_OMIT_SUBQUERY
000765  
000766  %type dbnm {Token}
000767  dbnm(A) ::= .          {A.z=0; A.n=0;}
000768  dbnm(A) ::= DOT nm(X). {A = X;}
000769  
000770  %type fullname {SrcList*}
000771  %destructor fullname {sqlite3SrcListDelete(pParse->db, $$);}
000772  fullname(A) ::= nm(X).  {
000773    A = sqlite3SrcListAppend(pParse,0,&X,0);
000774    if( IN_RENAME_OBJECT && A ) sqlite3RenameTokenMap(pParse, A->a[0].zName, &X);
000775  }
000776  fullname(A) ::= nm(X) DOT nm(Y). {
000777    A = sqlite3SrcListAppend(pParse,0,&X,&Y);
000778    if( IN_RENAME_OBJECT && A ) sqlite3RenameTokenMap(pParse, A->a[0].zName, &Y);
000779  }
000780  
000781  %type xfullname {SrcList*}
000782  %destructor xfullname {sqlite3SrcListDelete(pParse->db, $$);}
000783  xfullname(A) ::= nm(X).  
000784     {A = sqlite3SrcListAppend(pParse,0,&X,0); /*A-overwrites-X*/}
000785  xfullname(A) ::= nm(X) DOT nm(Y).  
000786     {A = sqlite3SrcListAppend(pParse,0,&X,&Y); /*A-overwrites-X*/}
000787  xfullname(A) ::= nm(X) DOT nm(Y) AS nm(Z).  {
000788     A = sqlite3SrcListAppend(pParse,0,&X,&Y); /*A-overwrites-X*/
000789     if( A ) A->a[0].zAlias = sqlite3NameFromToken(pParse->db, &Z);
000790  }
000791  xfullname(A) ::= nm(X) AS nm(Z). {  
000792     A = sqlite3SrcListAppend(pParse,0,&X,0); /*A-overwrites-X*/
000793     if( A ) A->a[0].zAlias = sqlite3NameFromToken(pParse->db, &Z);
000794  }
000795  
000796  %type joinop {int}
000797  joinop(X) ::= COMMA|JOIN.              { X = JT_INNER; }
000798  joinop(X) ::= JOIN_KW(A) JOIN.
000799                    {X = sqlite3JoinType(pParse,&A,0,0);  /*X-overwrites-A*/}
000800  joinop(X) ::= JOIN_KW(A) nm(B) JOIN.
000801                    {X = sqlite3JoinType(pParse,&A,&B,0); /*X-overwrites-A*/}
000802  joinop(X) ::= JOIN_KW(A) nm(B) nm(C) JOIN.
000803                    {X = sqlite3JoinType(pParse,&A,&B,&C);/*X-overwrites-A*/}
000804  
000805  // There is a parsing abiguity in an upsert statement that uses a
000806  // SELECT on the RHS of a the INSERT:
000807  //
000808  //      INSERT INTO tab SELECT * FROM aaa JOIN bbb ON CONFLICT ...
000809  //                                        here ----^^
000810  //
000811  // When the ON token is encountered, the parser does not know if it is
000812  // the beginning of an ON CONFLICT clause, or the beginning of an ON
000813  // clause associated with the JOIN.  The conflict is resolved in favor
000814  // of the JOIN.  If an ON CONFLICT clause is intended, insert a dummy
000815  // WHERE clause in between, like this:
000816  //
000817  //      INSERT INTO tab SELECT * FROM aaa JOIN bbb WHERE true ON CONFLICT ...
000818  //
000819  // The [AND] and [OR] precedence marks in the rules for on_using cause the
000820  // ON in this context to always be interpreted as belonging to the JOIN.
000821  //
000822  %type on_using {OnOrUsing}
000823  //%destructor on_using {sqlite3ClearOnOrUsing(pParse->db, &$$);}
000824  on_using(N) ::= ON expr(E).            {N.pOn = E; N.pUsing = 0;}
000825  on_using(N) ::= USING LP idlist(L) RP. {N.pOn = 0; N.pUsing = L;}
000826  on_using(N) ::= .                 [OR] {N.pOn = 0; N.pUsing = 0;}
000827  
000828  // Note that this block abuses the Token type just a little. If there is
000829  // no "INDEXED BY" clause, the returned token is empty (z==0 && n==0). If
000830  // there is an INDEXED BY clause, then the token is populated as per normal,
000831  // with z pointing to the token data and n containing the number of bytes
000832  // in the token.
000833  //
000834  // If there is a "NOT INDEXED" clause, then (z==0 && n==1), which is 
000835  // normally illegal. The sqlite3SrcListIndexedBy() function 
000836  // recognizes and interprets this as a special case.
000837  //
000838  %type indexed_opt {Token}
000839  %type indexed_by  {Token}
000840  indexed_opt(A) ::= .                 {A.z=0; A.n=0;}
000841  indexed_opt(A) ::= indexed_by(A).
000842  indexed_by(A)  ::= INDEXED BY nm(X). {A = X;}
000843  indexed_by(A)  ::= NOT INDEXED.      {A.z=0; A.n=1;}
000844  
000845  %type orderby_opt {ExprList*}
000846  %destructor orderby_opt {sqlite3ExprListDelete(pParse->db, $$);}
000847  
000848  // the sortlist non-terminal stores a list of expression where each
000849  // expression is optionally followed by ASC or DESC to indicate the
000850  // sort order.
000851  //
000852  %type sortlist {ExprList*}
000853  %destructor sortlist {sqlite3ExprListDelete(pParse->db, $$);}
000854  
000855  orderby_opt(A) ::= .                          {A = 0;}
000856  orderby_opt(A) ::= ORDER BY sortlist(X).      {A = X;}
000857  sortlist(A) ::= sortlist(A) COMMA expr(Y) sortorder(Z) nulls(X). {
000858    A = sqlite3ExprListAppend(pParse,A,Y);
000859    sqlite3ExprListSetSortOrder(A,Z,X);
000860  }
000861  sortlist(A) ::= expr(Y) sortorder(Z) nulls(X). {
000862    A = sqlite3ExprListAppend(pParse,0,Y); /*A-overwrites-Y*/
000863    sqlite3ExprListSetSortOrder(A,Z,X);
000864  }
000865  
000866  %type sortorder {int}
000867  
000868  sortorder(A) ::= ASC.           {A = SQLITE_SO_ASC;}
000869  sortorder(A) ::= DESC.          {A = SQLITE_SO_DESC;}
000870  sortorder(A) ::= .              {A = SQLITE_SO_UNDEFINED;}
000871  
000872  %type nulls {int}
000873  nulls(A) ::= NULLS FIRST.       {A = SQLITE_SO_ASC;}
000874  nulls(A) ::= NULLS LAST.        {A = SQLITE_SO_DESC;}
000875  nulls(A) ::= .                  {A = SQLITE_SO_UNDEFINED;}
000876  
000877  %type groupby_opt {ExprList*}
000878  %destructor groupby_opt {sqlite3ExprListDelete(pParse->db, $$);}
000879  groupby_opt(A) ::= .                      {A = 0;}
000880  groupby_opt(A) ::= GROUP BY nexprlist(X). {A = X;}
000881  
000882  %type having_opt {Expr*}
000883  %destructor having_opt {sqlite3ExprDelete(pParse->db, $$);}
000884  having_opt(A) ::= .                {A = 0;}
000885  having_opt(A) ::= HAVING expr(X).  {A = X;}
000886  
000887  %type limit_opt {Expr*}
000888  
000889  // The destructor for limit_opt will never fire in the current grammar.
000890  // The limit_opt non-terminal only occurs at the end of a single production
000891  // rule for SELECT statements.  As soon as the rule that create the 
000892  // limit_opt non-terminal reduces, the SELECT statement rule will also
000893  // reduce.  So there is never a limit_opt non-terminal on the stack 
000894  // except as a transient.  So there is never anything to destroy.
000895  //
000896  //%destructor limit_opt {sqlite3ExprDelete(pParse->db, $$);}
000897  limit_opt(A) ::= .       {A = 0;}
000898  limit_opt(A) ::= LIMIT expr(X).
000899                           {A = sqlite3PExpr(pParse,TK_LIMIT,X,0);}
000900  limit_opt(A) ::= LIMIT expr(X) OFFSET expr(Y). 
000901                           {A = sqlite3PExpr(pParse,TK_LIMIT,X,Y);}
000902  limit_opt(A) ::= LIMIT expr(X) COMMA expr(Y). 
000903                           {A = sqlite3PExpr(pParse,TK_LIMIT,Y,X);}
000904  
000905  /////////////////////////// The DELETE statement /////////////////////////////
000906  //
000907  %if SQLITE_ENABLE_UPDATE_DELETE_LIMIT || SQLITE_UDL_CAPABLE_PARSER
000908  cmd ::= with DELETE FROM xfullname(X) indexed_opt(I) where_opt_ret(W)
000909          orderby_opt(O) limit_opt(L). {
000910    sqlite3SrcListIndexedBy(pParse, X, &I);
000911  #ifndef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
000912    if( O || L ){
000913      updateDeleteLimitError(pParse,O,L);
000914      O = 0;
000915      L = 0;
000916    }
000917  #endif
000918    sqlite3DeleteFrom(pParse,X,W,O,L);
000919  }
000920  %else
000921  cmd ::= with DELETE FROM xfullname(X) indexed_opt(I) where_opt_ret(W). {
000922    sqlite3SrcListIndexedBy(pParse, X, &I);
000923    sqlite3DeleteFrom(pParse,X,W,0,0);
000924  }
000925  %endif
000926  
000927  %type where_opt {Expr*}
000928  %destructor where_opt {sqlite3ExprDelete(pParse->db, $$);}
000929  %type where_opt_ret {Expr*}
000930  %destructor where_opt_ret {sqlite3ExprDelete(pParse->db, $$);}
000931  
000932  where_opt(A) ::= .                    {A = 0;}
000933  where_opt(A) ::= WHERE expr(X).       {A = X;}
000934  where_opt_ret(A) ::= .                                      {A = 0;}
000935  where_opt_ret(A) ::= WHERE expr(X).                         {A = X;}
000936  where_opt_ret(A) ::= RETURNING selcollist(X).               
000937         {sqlite3AddReturning(pParse,X); A = 0;}
000938  where_opt_ret(A) ::= WHERE expr(X) RETURNING selcollist(Y).
000939         {sqlite3AddReturning(pParse,Y); A = X;}
000940  
000941  ////////////////////////// The UPDATE command ////////////////////////////////
000942  //
000943  %if SQLITE_ENABLE_UPDATE_DELETE_LIMIT || SQLITE_UDL_CAPABLE_PARSER
000944  cmd ::= with UPDATE orconf(R) xfullname(X) indexed_opt(I) SET setlist(Y) from(F)
000945          where_opt_ret(W) orderby_opt(O) limit_opt(L).  {
000946    sqlite3SrcListIndexedBy(pParse, X, &I);
000947    if( F ){
000948      SrcList *pFromClause = F;
000949      if( pFromClause->nSrc>1 ){
000950        Select *pSubquery;
000951        Token as;
000952        pSubquery = sqlite3SelectNew(pParse,0,pFromClause,0,0,0,0,SF_NestedFrom,0);
000953        as.n = 0;
000954        as.z = 0;
000955        pFromClause = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&as,pSubquery,0);
000956      }
000957      X = sqlite3SrcListAppendList(pParse, X, pFromClause);
000958    }
000959    sqlite3ExprListCheckLength(pParse,Y,"set list"); 
000960  #ifndef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
000961    if( O || L ){
000962      updateDeleteLimitError(pParse,O,L);
000963      O = 0;
000964      L = 0;
000965    }
000966  #endif
000967    sqlite3Update(pParse,X,Y,W,R,O,L,0);
000968  }
000969  %else
000970  cmd ::= with UPDATE orconf(R) xfullname(X) indexed_opt(I) SET setlist(Y) from(F)
000971          where_opt_ret(W). {
000972    sqlite3SrcListIndexedBy(pParse, X, &I);
000973    sqlite3ExprListCheckLength(pParse,Y,"set list"); 
000974    if( F ){
000975      SrcList *pFromClause = F;
000976      if( pFromClause->nSrc>1 ){
000977        Select *pSubquery;
000978        Token as;
000979        pSubquery = sqlite3SelectNew(pParse,0,pFromClause,0,0,0,0,SF_NestedFrom,0);
000980        as.n = 0;
000981        as.z = 0;
000982        pFromClause = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&as,pSubquery,0);
000983      }
000984      X = sqlite3SrcListAppendList(pParse, X, pFromClause);
000985    }
000986    sqlite3Update(pParse,X,Y,W,R,0,0,0);
000987  }
000988  %endif
000989  
000990  
000991  
000992  %type setlist {ExprList*}
000993  %destructor setlist {sqlite3ExprListDelete(pParse->db, $$);}
000994  
000995  setlist(A) ::= setlist(A) COMMA nm(X) EQ expr(Y). {
000996    A = sqlite3ExprListAppend(pParse, A, Y);
000997    sqlite3ExprListSetName(pParse, A, &X, 1);
000998  }
000999  setlist(A) ::= setlist(A) COMMA LP idlist(X) RP EQ expr(Y). {
001000    A = sqlite3ExprListAppendVector(pParse, A, X, Y);
001001  }
001002  setlist(A) ::= nm(X) EQ expr(Y). {
001003    A = sqlite3ExprListAppend(pParse, 0, Y);
001004    sqlite3ExprListSetName(pParse, A, &X, 1);
001005  }
001006  setlist(A) ::= LP idlist(X) RP EQ expr(Y). {
001007    A = sqlite3ExprListAppendVector(pParse, 0, X, Y);
001008  }
001009  
001010  ////////////////////////// The INSERT command /////////////////////////////////
001011  //
001012  cmd ::= with insert_cmd(R) INTO xfullname(X) idlist_opt(F) select(S)
001013          upsert(U). {
001014    sqlite3Insert(pParse, X, S, F, R, U);
001015  }
001016  cmd ::= with insert_cmd(R) INTO xfullname(X) idlist_opt(F) DEFAULT VALUES returning.
001017  {
001018    sqlite3Insert(pParse, X, 0, F, R, 0);
001019  }
001020  
001021  %type upsert {Upsert*}
001022  
001023  // Because upsert only occurs at the tip end of the INSERT rule for cmd,
001024  // there is never a case where the value of the upsert pointer will not
001025  // be destroyed by the cmd action.  So comment-out the destructor to
001026  // avoid unreachable code.
001027  //%destructor upsert {sqlite3UpsertDelete(pParse->db,$$);}
001028  upsert(A) ::= . { A = 0; }
001029  upsert(A) ::= RETURNING selcollist(X).  { A = 0; sqlite3AddReturning(pParse,X); }
001030  upsert(A) ::= ON CONFLICT LP sortlist(T) RP where_opt(TW)
001031                DO UPDATE SET setlist(Z) where_opt(W) upsert(N).
001032                { A = sqlite3UpsertNew(pParse->db,T,TW,Z,W,N);}
001033  upsert(A) ::= ON CONFLICT LP sortlist(T) RP where_opt(TW) DO NOTHING upsert(N).
001034                { A = sqlite3UpsertNew(pParse->db,T,TW,0,0,N); }
001035  upsert(A) ::= ON CONFLICT DO NOTHING returning.
001036                { A = sqlite3UpsertNew(pParse->db,0,0,0,0,0); }
001037  upsert(A) ::= ON CONFLICT DO UPDATE SET setlist(Z) where_opt(W) returning.
001038                { A = sqlite3UpsertNew(pParse->db,0,0,Z,W,0);}
001039  
001040  returning ::= RETURNING selcollist(X).  {sqlite3AddReturning(pParse,X);}
001041  returning ::= .
001042  
001043  %type insert_cmd {int}
001044  insert_cmd(A) ::= INSERT orconf(R).   {A = R;}
001045  insert_cmd(A) ::= REPLACE.            {A = OE_Replace;}
001046  
001047  %type idlist_opt {IdList*}
001048  %destructor idlist_opt {sqlite3IdListDelete(pParse->db, $$);}
001049  %type idlist {IdList*}
001050  %destructor idlist {sqlite3IdListDelete(pParse->db, $$);}
001051  
001052  idlist_opt(A) ::= .                       {A = 0;}
001053  idlist_opt(A) ::= LP idlist(X) RP.    {A = X;}
001054  idlist(A) ::= idlist(A) COMMA nm(Y).
001055      {A = sqlite3IdListAppend(pParse,A,&Y);}
001056  idlist(A) ::= nm(Y).
001057      {A = sqlite3IdListAppend(pParse,0,&Y); /*A-overwrites-Y*/}
001058  
001059  /////////////////////////// Expression Processing /////////////////////////////
001060  //
001061  
001062  %type expr {Expr*}
001063  %destructor expr {sqlite3ExprDelete(pParse->db, $$);}
001064  %type term {Expr*}
001065  %destructor term {sqlite3ExprDelete(pParse->db, $$);}
001066  
001067  %include {
001068  
001069    /* Construct a new Expr object from a single token */
001070    static Expr *tokenExpr(Parse *pParse, int op, Token t){
001071      Expr *p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr)+t.n+1);
001072      if( p ){
001073        /* memset(p, 0, sizeof(Expr)); */
001074        p->op = (u8)op;
001075        p->affExpr = 0;
001076        p->flags = EP_Leaf;
001077        ExprClearVVAProperties(p);
001078        /* p->iAgg = -1; // Not required */
001079        p->pLeft = p->pRight = 0;
001080        p->pAggInfo = 0;
001081        memset(&p->x, 0, sizeof(p->x));
001082        memset(&p->y, 0, sizeof(p->y));
001083        p->op2 = 0;
001084        p->iTable = 0;
001085        p->iColumn = 0;
001086        p->u.zToken = (char*)&p[1];
001087        memcpy(p->u.zToken, t.z, t.n);
001088        p->u.zToken[t.n] = 0;
001089        p->w.iOfst = (int)(t.z - pParse->zTail);
001090        if( sqlite3Isquote(p->u.zToken[0]) ){
001091          sqlite3DequoteExpr(p);
001092        }
001093  #if SQLITE_MAX_EXPR_DEPTH>0
001094        p->nHeight = 1;
001095  #endif  
001096        if( IN_RENAME_OBJECT ){
001097          return (Expr*)sqlite3RenameTokenMap(pParse, (void*)p, &t);
001098        }
001099      }
001100      return p;
001101    }
001102  
001103  }
001104  
001105  expr(A) ::= term(A).
001106  expr(A) ::= LP expr(X) RP. {A = X;}
001107  expr(A) ::= idj(X).          {A=tokenExpr(pParse,TK_ID,X); /*A-overwrites-X*/}
001108  expr(A) ::= nm(X) DOT nm(Y). {
001109    Expr *temp1 = tokenExpr(pParse,TK_ID,X);
001110    Expr *temp2 = tokenExpr(pParse,TK_ID,Y);
001111    A = sqlite3PExpr(pParse, TK_DOT, temp1, temp2);
001112  }
001113  expr(A) ::= nm(X) DOT nm(Y) DOT nm(Z). {
001114    Expr *temp1 = tokenExpr(pParse,TK_ID,X);
001115    Expr *temp2 = tokenExpr(pParse,TK_ID,Y);
001116    Expr *temp3 = tokenExpr(pParse,TK_ID,Z);
001117    Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3);
001118    if( IN_RENAME_OBJECT ){
001119      sqlite3RenameTokenRemap(pParse, 0, temp1);
001120    }
001121    A = sqlite3PExpr(pParse, TK_DOT, temp1, temp4);
001122  }
001123  term(A) ::= NULL|FLOAT|BLOB(X). {A=tokenExpr(pParse,@X,X); /*A-overwrites-X*/}
001124  term(A) ::= STRING(X).          {A=tokenExpr(pParse,@X,X); /*A-overwrites-X*/}
001125  term(A) ::= INTEGER(X). {
001126    A = sqlite3ExprAlloc(pParse->db, TK_INTEGER, &X, 1);
001127    if( A ) A->w.iOfst = (int)(X.z - pParse->zTail);
001128  }
001129  expr(A) ::= VARIABLE(X).     {
001130    if( !(X.z[0]=='#' && sqlite3Isdigit(X.z[1])) ){
001131      u32 n = X.n;
001132      A = tokenExpr(pParse, TK_VARIABLE, X);
001133      sqlite3ExprAssignVarNumber(pParse, A, n);
001134    }else{
001135      /* When doing a nested parse, one can include terms in an expression
001136      ** that look like this:   #1 #2 ...  These terms refer to registers
001137      ** in the virtual machine.  #N is the N-th register. */
001138      Token t = X; /*A-overwrites-X*/
001139      assert( t.n>=2 );
001140      if( pParse->nested==0 ){
001141        sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &t);
001142        A = 0;
001143      }else{
001144        A = sqlite3PExpr(pParse, TK_REGISTER, 0, 0);
001145        if( A ) sqlite3GetInt32(&t.z[1], &A->iTable);
001146      }
001147    }
001148  }
001149  expr(A) ::= expr(A) COLLATE ids(C). {
001150    A = sqlite3ExprAddCollateToken(pParse, A, &C, 1);
001151  }
001152  %ifndef SQLITE_OMIT_CAST
001153  expr(A) ::= CAST LP expr(E) AS typetoken(T) RP. {
001154    A = sqlite3ExprAlloc(pParse->db, TK_CAST, &T, 1);
001155    sqlite3ExprAttachSubtrees(pParse->db, A, E, 0);
001156  }
001157  %endif  SQLITE_OMIT_CAST
001158  
001159  
001160  expr(A) ::= idj(X) LP distinct(D) exprlist(Y) RP. {
001161    A = sqlite3ExprFunction(pParse, Y, &X, D);
001162  }
001163  expr(A) ::= idj(X) LP distinct(D) exprlist(Y) ORDER BY sortlist(O) RP. {
001164    A = sqlite3ExprFunction(pParse, Y, &X, D);
001165    sqlite3ExprAddFunctionOrderBy(pParse, A, O);
001166  }
001167  expr(A) ::= idj(X) LP STAR RP. {
001168    A = sqlite3ExprFunction(pParse, 0, &X, 0);
001169  }
001170  
001171  %ifndef SQLITE_OMIT_WINDOWFUNC
001172  expr(A) ::= idj(X) LP distinct(D) exprlist(Y) RP filter_over(Z). {
001173    A = sqlite3ExprFunction(pParse, Y, &X, D);
001174    sqlite3WindowAttach(pParse, A, Z);
001175  }
001176  expr(A) ::= idj(X) LP distinct(D) exprlist(Y) ORDER BY sortlist(O) RP filter_over(Z). {
001177    A = sqlite3ExprFunction(pParse, Y, &X, D);
001178    sqlite3WindowAttach(pParse, A, Z);
001179    sqlite3ExprAddFunctionOrderBy(pParse, A, O);
001180  }
001181  expr(A) ::= idj(X) LP STAR RP filter_over(Z). {
001182    A = sqlite3ExprFunction(pParse, 0, &X, 0);
001183    sqlite3WindowAttach(pParse, A, Z);
001184  }
001185  %endif
001186  
001187  term(A) ::= CTIME_KW(OP). {
001188    A = sqlite3ExprFunction(pParse, 0, &OP, 0);
001189  }
001190  
001191  expr(A) ::= LP nexprlist(X) COMMA expr(Y) RP. {
001192    ExprList *pList = sqlite3ExprListAppend(pParse, X, Y);
001193    A = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
001194    if( A ){
001195      A->x.pList = pList;
001196      if( ALWAYS(pList->nExpr) ){
001197        A->flags |= pList->a[0].pExpr->flags & EP_Propagate;
001198      }
001199    }else{
001200      sqlite3ExprListDelete(pParse->db, pList);
001201    }
001202  }
001203  
001204  expr(A) ::= expr(A) AND expr(Y).        {A=sqlite3ExprAnd(pParse,A,Y);}
001205  expr(A) ::= expr(A) OR(OP) expr(Y).     {A=sqlite3PExpr(pParse,@OP,A,Y);}
001206  expr(A) ::= expr(A) LT|GT|GE|LE(OP) expr(Y).
001207                                          {A=sqlite3PExpr(pParse,@OP,A,Y);}
001208  expr(A) ::= expr(A) EQ|NE(OP) expr(Y).  {A=sqlite3PExpr(pParse,@OP,A,Y);}
001209  expr(A) ::= expr(A) BITAND|BITOR|LSHIFT|RSHIFT(OP) expr(Y).
001210                                          {A=sqlite3PExpr(pParse,@OP,A,Y);}
001211  expr(A) ::= expr(A) PLUS|MINUS(OP) expr(Y).
001212                                          {A=sqlite3PExpr(pParse,@OP,A,Y);}
001213  expr(A) ::= expr(A) STAR|SLASH|REM(OP) expr(Y).
001214                                          {A=sqlite3PExpr(pParse,@OP,A,Y);}
001215  expr(A) ::= expr(A) CONCAT(OP) expr(Y). {A=sqlite3PExpr(pParse,@OP,A,Y);}
001216  %type likeop {Token}
001217  likeop(A) ::= LIKE_KW|MATCH(A).
001218  likeop(A) ::= NOT LIKE_KW|MATCH(X). {A=X; A.n|=0x80000000; /*A-overwrite-X*/}
001219  expr(A) ::= expr(A) likeop(OP) expr(Y).  [LIKE_KW]  {
001220    ExprList *pList;
001221    int bNot = OP.n & 0x80000000;
001222    OP.n &= 0x7fffffff;
001223    pList = sqlite3ExprListAppend(pParse,0, Y);
001224    pList = sqlite3ExprListAppend(pParse,pList, A);
001225    A = sqlite3ExprFunction(pParse, pList, &OP, 0);
001226    if( bNot ) A = sqlite3PExpr(pParse, TK_NOT, A, 0);
001227    if( A ) A->flags |= EP_InfixFunc;
001228  }
001229  expr(A) ::= expr(A) likeop(OP) expr(Y) ESCAPE expr(E).  [LIKE_KW]  {
001230    ExprList *pList;
001231    int bNot = OP.n & 0x80000000;
001232    OP.n &= 0x7fffffff;
001233    pList = sqlite3ExprListAppend(pParse,0, Y);
001234    pList = sqlite3ExprListAppend(pParse,pList, A);
001235    pList = sqlite3ExprListAppend(pParse,pList, E);
001236    A = sqlite3ExprFunction(pParse, pList, &OP, 0);
001237    if( bNot ) A = sqlite3PExpr(pParse, TK_NOT, A, 0);
001238    if( A ) A->flags |= EP_InfixFunc;
001239  }
001240  
001241  expr(A) ::= expr(A) ISNULL|NOTNULL(E).   {A = sqlite3PExpr(pParse,@E,A,0);}
001242  expr(A) ::= expr(A) NOT NULL.    {A = sqlite3PExpr(pParse,TK_NOTNULL,A,0);}
001243  
001244  %include {
001245    /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
001246    ** unary TK_ISNULL or TK_NOTNULL expression. */
001247    static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
001248      sqlite3 *db = pParse->db;
001249      if( pA && pY && pY->op==TK_NULL && !IN_RENAME_OBJECT ){
001250        pA->op = (u8)op;
001251        sqlite3ExprDelete(db, pA->pRight);
001252        pA->pRight = 0;
001253      }
001254    }
001255  }
001256  
001257  //    expr1 IS expr2
001258  //    expr1 IS NOT expr2
001259  //
001260  // If expr2 is NULL then code as TK_ISNULL or TK_NOTNULL.  If expr2
001261  // is any other expression, code as TK_IS or TK_ISNOT.
001262  // 
001263  expr(A) ::= expr(A) IS expr(Y).     {
001264    A = sqlite3PExpr(pParse,TK_IS,A,Y);
001265    binaryToUnaryIfNull(pParse, Y, A, TK_ISNULL);
001266  }
001267  expr(A) ::= expr(A) IS NOT expr(Y). {
001268    A = sqlite3PExpr(pParse,TK_ISNOT,A,Y);
001269    binaryToUnaryIfNull(pParse, Y, A, TK_NOTNULL);
001270  }
001271  expr(A) ::= expr(A) IS NOT DISTINCT FROM expr(Y).     {
001272    A = sqlite3PExpr(pParse,TK_IS,A,Y);
001273    binaryToUnaryIfNull(pParse, Y, A, TK_ISNULL);
001274  }
001275  expr(A) ::= expr(A) IS DISTINCT FROM expr(Y). {
001276    A = sqlite3PExpr(pParse,TK_ISNOT,A,Y);
001277    binaryToUnaryIfNull(pParse, Y, A, TK_NOTNULL);
001278  }
001279  
001280  expr(A) ::= NOT(B) expr(X).  
001281                {A = sqlite3PExpr(pParse, @B, X, 0);/*A-overwrites-B*/}
001282  expr(A) ::= BITNOT(B) expr(X).
001283                {A = sqlite3PExpr(pParse, @B, X, 0);/*A-overwrites-B*/}
001284  expr(A) ::= PLUS|MINUS(B) expr(X). [BITNOT] {
001285    Expr *p = X;
001286    u8 op = @B + (TK_UPLUS-TK_PLUS);
001287    assert( TK_UPLUS>TK_PLUS );
001288    assert( TK_UMINUS == TK_MINUS + (TK_UPLUS - TK_PLUS) );
001289    if( p && p->op==TK_UPLUS ){
001290      p->op = op;
001291      A = p;
001292    }else{
001293      A = sqlite3PExpr(pParse, op, p, 0);
001294      /*A-overwrites-B*/
001295    }
001296  }
001297  
001298  expr(A) ::= expr(B) PTR(C) expr(D). {
001299    ExprList *pList = sqlite3ExprListAppend(pParse, 0, B);
001300    pList = sqlite3ExprListAppend(pParse, pList, D);
001301    A = sqlite3ExprFunction(pParse, pList, &C, 0);
001302  }
001303  
001304  %type between_op {int}
001305  between_op(A) ::= BETWEEN.     {A = 0;}
001306  between_op(A) ::= NOT BETWEEN. {A = 1;}
001307  expr(A) ::= expr(A) between_op(N) expr(X) AND expr(Y). [BETWEEN] {
001308    ExprList *pList = sqlite3ExprListAppend(pParse,0, X);
001309    pList = sqlite3ExprListAppend(pParse,pList, Y);
001310    A = sqlite3PExpr(pParse, TK_BETWEEN, A, 0);
001311    if( A ){
001312      A->x.pList = pList;
001313    }else{
001314      sqlite3ExprListDelete(pParse->db, pList);
001315    } 
001316    if( N ) A = sqlite3PExpr(pParse, TK_NOT, A, 0);
001317  }
001318  %ifndef SQLITE_OMIT_SUBQUERY
001319    %type in_op {int}
001320    in_op(A) ::= IN.      {A = 0;}
001321    in_op(A) ::= NOT IN.  {A = 1;}
001322    expr(A) ::= expr(A) in_op(N) LP exprlist(Y) RP. [IN] {
001323      if( Y==0 ){
001324        /* Expressions of the form
001325        **
001326        **      expr1 IN ()
001327        **      expr1 NOT IN ()
001328        **
001329        ** simplify to constants 0 (false) and 1 (true), respectively,
001330        ** regardless of the value of expr1.
001331        */
001332        sqlite3ExprUnmapAndDelete(pParse, A);
001333        A = sqlite3Expr(pParse->db, TK_STRING, N ? "true" : "false");
001334        if( A ) sqlite3ExprIdToTrueFalse(A);
001335      }else{
001336        Expr *pRHS = Y->a[0].pExpr;
001337        if( Y->nExpr==1 && sqlite3ExprIsConstant(pParse,pRHS) && A->op!=TK_VECTOR ){
001338          Y->a[0].pExpr = 0;
001339          sqlite3ExprListDelete(pParse->db, Y);
001340          pRHS = sqlite3PExpr(pParse, TK_UPLUS, pRHS, 0);
001341          A = sqlite3PExpr(pParse, TK_EQ, A, pRHS);
001342        }else if( Y->nExpr==1 && pRHS->op==TK_SELECT ){
001343          A = sqlite3PExpr(pParse, TK_IN, A, 0);
001344          sqlite3PExprAddSelect(pParse, A, pRHS->x.pSelect);
001345          pRHS->x.pSelect = 0;
001346          sqlite3ExprListDelete(pParse->db, Y);
001347        }else{
001348          A = sqlite3PExpr(pParse, TK_IN, A, 0);
001349          if( A==0 ){
001350            sqlite3ExprListDelete(pParse->db, Y);
001351          }else if( A->pLeft->op==TK_VECTOR ){
001352            int nExpr = A->pLeft->x.pList->nExpr;
001353            Select *pSelectRHS = sqlite3ExprListToValues(pParse, nExpr, Y);
001354            if( pSelectRHS ){
001355              parserDoubleLinkSelect(pParse, pSelectRHS);
001356              sqlite3PExprAddSelect(pParse, A, pSelectRHS);
001357            }
001358          }else{
001359            A->x.pList = Y;
001360            sqlite3ExprSetHeightAndFlags(pParse, A);
001361          }
001362        }
001363        if( N ) A = sqlite3PExpr(pParse, TK_NOT, A, 0);
001364      }
001365    }
001366    expr(A) ::= LP select(X) RP. {
001367      A = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
001368      sqlite3PExprAddSelect(pParse, A, X);
001369    }
001370    expr(A) ::= expr(A) in_op(N) LP select(Y) RP.  [IN] {
001371      A = sqlite3PExpr(pParse, TK_IN, A, 0);
001372      sqlite3PExprAddSelect(pParse, A, Y);
001373      if( N ) A = sqlite3PExpr(pParse, TK_NOT, A, 0);
001374    }
001375    expr(A) ::= expr(A) in_op(N) nm(Y) dbnm(Z) paren_exprlist(E). [IN] {
001376      SrcList *pSrc = sqlite3SrcListAppend(pParse, 0,&Y,&Z);
001377      Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0);
001378      if( E )  sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, E);
001379      A = sqlite3PExpr(pParse, TK_IN, A, 0);
001380      sqlite3PExprAddSelect(pParse, A, pSelect);
001381      if( N ) A = sqlite3PExpr(pParse, TK_NOT, A, 0);
001382    }
001383    expr(A) ::= EXISTS LP select(Y) RP. {
001384      Expr *p;
001385      p = A = sqlite3PExpr(pParse, TK_EXISTS, 0, 0);
001386      sqlite3PExprAddSelect(pParse, p, Y);
001387    }
001388  %endif SQLITE_OMIT_SUBQUERY
001389  
001390  /* CASE expressions */
001391  expr(A) ::= CASE case_operand(X) case_exprlist(Y) case_else(Z) END. {
001392    A = sqlite3PExpr(pParse, TK_CASE, X, 0);
001393    if( A ){
001394      A->x.pList = Z ? sqlite3ExprListAppend(pParse,Y,Z) : Y;
001395      sqlite3ExprSetHeightAndFlags(pParse, A);
001396    }else{
001397      sqlite3ExprListDelete(pParse->db, Y);
001398      sqlite3ExprDelete(pParse->db, Z);
001399    }
001400  }
001401  %type case_exprlist {ExprList*}
001402  %destructor case_exprlist {sqlite3ExprListDelete(pParse->db, $$);}
001403  case_exprlist(A) ::= case_exprlist(A) WHEN expr(Y) THEN expr(Z). {
001404    A = sqlite3ExprListAppend(pParse,A, Y);
001405    A = sqlite3ExprListAppend(pParse,A, Z);
001406  }
001407  case_exprlist(A) ::= WHEN expr(Y) THEN expr(Z). {
001408    A = sqlite3ExprListAppend(pParse,0, Y);
001409    A = sqlite3ExprListAppend(pParse,A, Z);
001410  }
001411  %type case_else {Expr*}
001412  %destructor case_else {sqlite3ExprDelete(pParse->db, $$);}
001413  case_else(A) ::=  ELSE expr(X).         {A = X;}
001414  case_else(A) ::=  .                     {A = 0;} 
001415  %type case_operand {Expr*}
001416  %destructor case_operand {sqlite3ExprDelete(pParse->db, $$);}
001417  case_operand(A) ::= expr(A).
001418  case_operand(A) ::= .                   {A = 0;} 
001419  
001420  %type exprlist {ExprList*}
001421  %destructor exprlist {sqlite3ExprListDelete(pParse->db, $$);}
001422  %type nexprlist {ExprList*}
001423  %destructor nexprlist {sqlite3ExprListDelete(pParse->db, $$);}
001424  
001425  exprlist(A) ::= nexprlist(A).
001426  exprlist(A) ::= .                            {A = 0;}
001427  nexprlist(A) ::= nexprlist(A) COMMA expr(Y).
001428      {A = sqlite3ExprListAppend(pParse,A,Y);}
001429  nexprlist(A) ::= expr(Y).
001430      {A = sqlite3ExprListAppend(pParse,0,Y); /*A-overwrites-Y*/}
001431  
001432  %ifndef SQLITE_OMIT_SUBQUERY
001433  /* A paren_exprlist is an optional expression list contained inside
001434  ** of parenthesis */
001435  %type paren_exprlist {ExprList*}
001436  %destructor paren_exprlist {sqlite3ExprListDelete(pParse->db, $$);}
001437  paren_exprlist(A) ::= .   {A = 0;}
001438  paren_exprlist(A) ::= LP exprlist(X) RP.  {A = X;}
001439  %endif SQLITE_OMIT_SUBQUERY
001440  
001441  
001442  ///////////////////////////// The CREATE INDEX command ///////////////////////
001443  //
001444  cmd ::= createkw(S) uniqueflag(U) INDEX ifnotexists(NE) nm(X) dbnm(D)
001445          ON nm(Y) LP sortlist(Z) RP where_opt(W). {
001446    sqlite3CreateIndex(pParse, &X, &D, 
001447                       sqlite3SrcListAppend(pParse,0,&Y,0), Z, U,
001448                        &S, W, SQLITE_SO_ASC, NE, SQLITE_IDXTYPE_APPDEF);
001449    if( IN_RENAME_OBJECT && pParse->pNewIndex ){
001450      sqlite3RenameTokenMap(pParse, pParse->pNewIndex->zName, &Y);
001451    }
001452  }
001453  
001454  %type uniqueflag {int}
001455  uniqueflag(A) ::= UNIQUE.  {A = OE_Abort;}
001456  uniqueflag(A) ::= .        {A = OE_None;}
001457  
001458  
001459  // The eidlist non-terminal (Expression Id List) generates an ExprList
001460  // from a list of identifiers.  The identifier names are in ExprList.a[].zName.
001461  // This list is stored in an ExprList rather than an IdList so that it
001462  // can be easily sent to sqlite3ColumnsExprList().
001463  //
001464  // eidlist is grouped with CREATE INDEX because it used to be the non-terminal
001465  // used for the arguments to an index.  That is just an historical accident.
001466  //
001467  // IMPORTANT COMPATIBILITY NOTE:  Some prior versions of SQLite accepted
001468  // COLLATE clauses and ASC or DESC keywords on ID lists in inappropriate
001469  // places - places that might have been stored in the sqlite_schema table.
001470  // Those extra features were ignored.  But because they might be in some
001471  // (busted) old databases, we need to continue parsing them when loading
001472  // historical schemas.
001473  //
001474  %type eidlist {ExprList*}
001475  %destructor eidlist {sqlite3ExprListDelete(pParse->db, $$);}
001476  %type eidlist_opt {ExprList*}
001477  %destructor eidlist_opt {sqlite3ExprListDelete(pParse->db, $$);}
001478  
001479  %include {
001480    /* Add a single new term to an ExprList that is used to store a
001481    ** list of identifiers.  Report an error if the ID list contains
001482    ** a COLLATE clause or an ASC or DESC keyword, except ignore the
001483    ** error while parsing a legacy schema.
001484    */
001485    static ExprList *parserAddExprIdListTerm(
001486      Parse *pParse,
001487      ExprList *pPrior,
001488      Token *pIdToken,
001489      int hasCollate,
001490      int sortOrder
001491    ){
001492      ExprList *p = sqlite3ExprListAppend(pParse, pPrior, 0);
001493      if( (hasCollate || sortOrder!=SQLITE_SO_UNDEFINED)
001494          && pParse->db->init.busy==0
001495      ){
001496        sqlite3ErrorMsg(pParse, "syntax error after column name \"%.*s\"",
001497                           pIdToken->n, pIdToken->z);
001498      }
001499      sqlite3ExprListSetName(pParse, p, pIdToken, 1);
001500      return p;
001501    }
001502  } // end %include
001503  
001504  eidlist_opt(A) ::= .                         {A = 0;}
001505  eidlist_opt(A) ::= LP eidlist(X) RP.         {A = X;}
001506  eidlist(A) ::= eidlist(A) COMMA nm(Y) collate(C) sortorder(Z).  {
001507    A = parserAddExprIdListTerm(pParse, A, &Y, C, Z);
001508  }
001509  eidlist(A) ::= nm(Y) collate(C) sortorder(Z). {
001510    A = parserAddExprIdListTerm(pParse, 0, &Y, C, Z); /*A-overwrites-Y*/
001511  }
001512  
001513  %type collate {int}
001514  collate(C) ::= .              {C = 0;}
001515  collate(C) ::= COLLATE ids.   {C = 1;}
001516  
001517  
001518  ///////////////////////////// The DROP INDEX command /////////////////////////
001519  //
001520  cmd ::= DROP INDEX ifexists(E) fullname(X).   {sqlite3DropIndex(pParse, X, E);}
001521  
001522  ///////////////////////////// The VACUUM command /////////////////////////////
001523  //
001524  %if !SQLITE_OMIT_VACUUM && !SQLITE_OMIT_ATTACH
001525  %type vinto {Expr*}
001526  %destructor vinto {sqlite3ExprDelete(pParse->db, $$);}
001527  cmd ::= VACUUM vinto(Y).                {sqlite3Vacuum(pParse,0,Y);}
001528  cmd ::= VACUUM nm(X) vinto(Y).          {sqlite3Vacuum(pParse,&X,Y);}
001529  vinto(A) ::= INTO expr(X).              {A = X;}
001530  vinto(A) ::= .                          {A = 0;}
001531  %endif
001532  
001533  ///////////////////////////// The PRAGMA command /////////////////////////////
001534  //
001535  %ifndef SQLITE_OMIT_PRAGMA
001536  cmd ::= PRAGMA nm(X) dbnm(Z).                {sqlite3Pragma(pParse,&X,&Z,0,0);}
001537  cmd ::= PRAGMA nm(X) dbnm(Z) EQ nmnum(Y).    {sqlite3Pragma(pParse,&X,&Z,&Y,0);}
001538  cmd ::= PRAGMA nm(X) dbnm(Z) LP nmnum(Y) RP. {sqlite3Pragma(pParse,&X,&Z,&Y,0);}
001539  cmd ::= PRAGMA nm(X) dbnm(Z) EQ minus_num(Y). 
001540                                               {sqlite3Pragma(pParse,&X,&Z,&Y,1);}
001541  cmd ::= PRAGMA nm(X) dbnm(Z) LP minus_num(Y) RP.
001542                                               {sqlite3Pragma(pParse,&X,&Z,&Y,1);}
001543  
001544  nmnum(A) ::= plus_num(A).
001545  nmnum(A) ::= nm(A).
001546  nmnum(A) ::= ON(A).
001547  nmnum(A) ::= DELETE(A).
001548  nmnum(A) ::= DEFAULT(A).
001549  %endif SQLITE_OMIT_PRAGMA
001550  %token_class number INTEGER|FLOAT.
001551  plus_num(A) ::= PLUS number(X).       {A = X;}
001552  plus_num(A) ::= number(A).
001553  minus_num(A) ::= MINUS number(X).     {A = X;}
001554  //////////////////////////// The CREATE TRIGGER command /////////////////////
001555  
001556  %ifndef SQLITE_OMIT_TRIGGER
001557  
001558  cmd ::= createkw trigger_decl(A) BEGIN trigger_cmd_list(S) END(Z). {
001559    Token all;
001560    all.z = A.z;
001561    all.n = (int)(Z.z - A.z) + Z.n;
001562    sqlite3FinishTrigger(pParse, S, &all);
001563  }
001564  
001565  trigger_decl(A) ::= temp(T) TRIGGER ifnotexists(NOERR) nm(B) dbnm(Z) 
001566                      trigger_time(C) trigger_event(D)
001567                      ON fullname(E) foreach_clause when_clause(G). {
001568    sqlite3BeginTrigger(pParse, &B, &Z, C, D.a, D.b, E, G, T, NOERR);
001569    A = (Z.n==0?B:Z); /*A-overwrites-T*/
001570  }
001571  
001572  %type trigger_time {int}
001573  trigger_time(A) ::= BEFORE|AFTER(X).  { A = @X; /*A-overwrites-X*/ }
001574  trigger_time(A) ::= INSTEAD OF.  { A = TK_INSTEAD;}
001575  trigger_time(A) ::= .            { A = TK_BEFORE; }
001576  
001577  %type trigger_event {struct TrigEvent}
001578  %destructor trigger_event {sqlite3IdListDelete(pParse->db, $$.b);}
001579  trigger_event(A) ::= DELETE|INSERT(X).   {A.a = @X; /*A-overwrites-X*/ A.b = 0;}
001580  trigger_event(A) ::= UPDATE(X).          {A.a = @X; /*A-overwrites-X*/ A.b = 0;}
001581  trigger_event(A) ::= UPDATE OF idlist(X).{A.a = TK_UPDATE; A.b = X;}
001582  
001583  foreach_clause ::= .
001584  foreach_clause ::= FOR EACH ROW.
001585  
001586  %type when_clause {Expr*}
001587  %destructor when_clause {sqlite3ExprDelete(pParse->db, $$);}
001588  when_clause(A) ::= .             { A = 0; }
001589  when_clause(A) ::= WHEN expr(X). { A = X; }
001590  
001591  %type trigger_cmd_list {TriggerStep*}
001592  %destructor trigger_cmd_list {sqlite3DeleteTriggerStep(pParse->db, $$);}
001593  trigger_cmd_list(A) ::= trigger_cmd_list(A) trigger_cmd(X) SEMI. {
001594    assert( A!=0 );
001595    A->pLast->pNext = X;
001596    A->pLast = X;
001597  }
001598  trigger_cmd_list(A) ::= trigger_cmd(A) SEMI. { 
001599    assert( A!=0 );
001600    A->pLast = A;
001601  }
001602  
001603  // Disallow qualified table names on INSERT, UPDATE, and DELETE statements
001604  // within a trigger.  The table to INSERT, UPDATE, or DELETE is always in 
001605  // the same database as the table that the trigger fires on.
001606  //
001607  %type trnm {Token}
001608  trnm(A) ::= nm(A).
001609  trnm(A) ::= nm DOT nm(X). {
001610    A = X;
001611    sqlite3ErrorMsg(pParse, 
001612          "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
001613          "statements within triggers");
001614  }
001615  
001616  // Disallow the INDEX BY and NOT INDEXED clauses on UPDATE and DELETE
001617  // statements within triggers.  We make a specific error message for this
001618  // since it is an exception to the default grammar rules.
001619  //
001620  tridxby ::= .
001621  tridxby ::= INDEXED BY nm. {
001622    sqlite3ErrorMsg(pParse,
001623          "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
001624          "within triggers");
001625  }
001626  tridxby ::= NOT INDEXED. {
001627    sqlite3ErrorMsg(pParse,
001628          "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
001629          "within triggers");
001630  }
001631  
001632  
001633  
001634  %type trigger_cmd {TriggerStep*}
001635  %destructor trigger_cmd {sqlite3DeleteTriggerStep(pParse->db, $$);}
001636  // UPDATE 
001637  trigger_cmd(A) ::=
001638     UPDATE(B) orconf(R) trnm(X) tridxby SET setlist(Y) from(F) where_opt(Z) scanpt(E).  
001639     {A = sqlite3TriggerUpdateStep(pParse, &X, F, Y, Z, R, B.z, E);}
001640  
001641  // INSERT
001642  trigger_cmd(A) ::= scanpt(B) insert_cmd(R) INTO
001643                        trnm(X) idlist_opt(F) select(S) upsert(U) scanpt(Z). {
001644     A = sqlite3TriggerInsertStep(pParse,&X,F,S,R,U,B,Z);/*A-overwrites-R*/
001645  }
001646  // DELETE
001647  trigger_cmd(A) ::= DELETE(B) FROM trnm(X) tridxby where_opt(Y) scanpt(E).
001648     {A = sqlite3TriggerDeleteStep(pParse, &X, Y, B.z, E);}
001649  
001650  // SELECT
001651  trigger_cmd(A) ::= scanpt(B) select(X) scanpt(E).
001652     {A = sqlite3TriggerSelectStep(pParse->db, X, B, E); /*A-overwrites-X*/}
001653  
001654  // The special RAISE expression that may occur in trigger programs
001655  expr(A) ::= RAISE LP IGNORE RP.  {
001656    A = sqlite3PExpr(pParse, TK_RAISE, 0, 0); 
001657    if( A ){
001658      A->affExpr = OE_Ignore;
001659    }
001660  }
001661  expr(A) ::= RAISE LP raisetype(T) COMMA nm(Z) RP.  {
001662    A = sqlite3ExprAlloc(pParse->db, TK_RAISE, &Z, 1);
001663    if( A ) {
001664      A->affExpr = (char)T;
001665    }
001666  }
001667  %endif  !SQLITE_OMIT_TRIGGER
001668  
001669  %type raisetype {int}
001670  raisetype(A) ::= ROLLBACK.  {A = OE_Rollback;}
001671  raisetype(A) ::= ABORT.     {A = OE_Abort;}
001672  raisetype(A) ::= FAIL.      {A = OE_Fail;}
001673  
001674  
001675  ////////////////////////  DROP TRIGGER statement //////////////////////////////
001676  %ifndef SQLITE_OMIT_TRIGGER
001677  cmd ::= DROP TRIGGER ifexists(NOERR) fullname(X). {
001678    sqlite3DropTrigger(pParse,X,NOERR);
001679  }
001680  %endif  !SQLITE_OMIT_TRIGGER
001681  
001682  //////////////////////// ATTACH DATABASE file AS name /////////////////////////
001683  %ifndef SQLITE_OMIT_ATTACH
001684  cmd ::= ATTACH database_kw_opt expr(F) AS expr(D) key_opt(K). {
001685    sqlite3Attach(pParse, F, D, K);
001686  }
001687  cmd ::= DETACH database_kw_opt expr(D). {
001688    sqlite3Detach(pParse, D);
001689  }
001690  
001691  %type key_opt {Expr*}
001692  %destructor key_opt {sqlite3ExprDelete(pParse->db, $$);}
001693  key_opt(A) ::= .                     { A = 0; }
001694  key_opt(A) ::= KEY expr(X).          { A = X; }
001695  
001696  database_kw_opt ::= DATABASE.
001697  database_kw_opt ::= .
001698  %endif SQLITE_OMIT_ATTACH
001699  
001700  ////////////////////////// REINDEX collation //////////////////////////////////
001701  %ifndef SQLITE_OMIT_REINDEX
001702  cmd ::= REINDEX.                {sqlite3Reindex(pParse, 0, 0);}
001703  cmd ::= REINDEX nm(X) dbnm(Y).  {sqlite3Reindex(pParse, &X, &Y);}
001704  %endif  SQLITE_OMIT_REINDEX
001705  
001706  /////////////////////////////////// ANALYZE ///////////////////////////////////
001707  %ifndef SQLITE_OMIT_ANALYZE
001708  cmd ::= ANALYZE.                {sqlite3Analyze(pParse, 0, 0);}
001709  cmd ::= ANALYZE nm(X) dbnm(Y).  {sqlite3Analyze(pParse, &X, &Y);}
001710  %endif
001711  
001712  //////////////////////// ALTER TABLE table ... ////////////////////////////////
001713  %ifndef SQLITE_OMIT_ALTERTABLE 
001714  %ifndef SQLITE_OMIT_VIRTUALTABLE
001715  cmd ::= ALTER TABLE fullname(X) RENAME TO nm(Z). {
001716    sqlite3AlterRenameTable(pParse,X,&Z);
001717  }
001718  cmd ::= ALTER TABLE add_column_fullname
001719          ADD kwcolumn_opt columnname(Y) carglist. {
001720    Y.n = (int)(pParse->sLastToken.z-Y.z) + pParse->sLastToken.n;
001721    sqlite3AlterFinishAddColumn(pParse, &Y);
001722  }
001723  cmd ::= ALTER TABLE fullname(X) DROP kwcolumn_opt nm(Y). {
001724    sqlite3AlterDropColumn(pParse, X, &Y);
001725  }
001726  
001727  add_column_fullname ::= fullname(X). {
001728    disableLookaside(pParse);
001729    sqlite3AlterBeginAddColumn(pParse, X);
001730  }
001731  cmd ::= ALTER TABLE fullname(X) RENAME kwcolumn_opt nm(Y) TO nm(Z). {
001732    sqlite3AlterRenameColumn(pParse, X, &Y, &Z);
001733  }
001734  
001735  kwcolumn_opt ::= .
001736  kwcolumn_opt ::= COLUMNKW.
001737  
001738  %endif SQLITE_OMIT_VIRTUALTABLE
001739  %endif SQLITE_OMIT_ALTERTABLE
001740  
001741  //////////////////////// CREATE VIRTUAL TABLE ... /////////////////////////////
001742  %ifndef SQLITE_OMIT_VIRTUALTABLE
001743  cmd ::= create_vtab.                       {sqlite3VtabFinishParse(pParse,0);}
001744  cmd ::= create_vtab LP vtabarglist RP(X).  {sqlite3VtabFinishParse(pParse,&X);}
001745  create_vtab ::= createkw VIRTUAL TABLE ifnotexists(E)
001746                  nm(X) dbnm(Y) USING nm(Z). {
001747      sqlite3VtabBeginParse(pParse, &X, &Y, &Z, E);
001748  }
001749  vtabarglist ::= vtabarg.
001750  vtabarglist ::= vtabarglist COMMA vtabarg.
001751  vtabarg ::= .                       {sqlite3VtabArgInit(pParse);}
001752  vtabarg ::= vtabarg vtabargtoken.
001753  vtabargtoken ::= ANY(X).            {sqlite3VtabArgExtend(pParse,&X);}
001754  vtabargtoken ::= lp anylist RP(X).  {sqlite3VtabArgExtend(pParse,&X);}
001755  lp ::= LP(X).                       {sqlite3VtabArgExtend(pParse,&X);}
001756  anylist ::= .
001757  anylist ::= anylist LP anylist RP.
001758  anylist ::= anylist ANY.
001759  %endif  SQLITE_OMIT_VIRTUALTABLE
001760  
001761  
001762  //////////////////////// COMMON TABLE EXPRESSIONS ////////////////////////////
001763  %type wqlist {With*}
001764  %destructor wqlist {sqlite3WithDelete(pParse->db, $$);}
001765  %type wqitem {Cte*}
001766  // %destructor wqitem {sqlite3CteDelete(pParse->db, $$);} // not reachable
001767  
001768  with ::= .
001769  %ifndef SQLITE_OMIT_CTE
001770  with ::= WITH wqlist(W).              { sqlite3WithPush(pParse, W, 1); }
001771  with ::= WITH RECURSIVE wqlist(W).    { sqlite3WithPush(pParse, W, 1); }
001772  
001773  %type wqas {u8}
001774  wqas(A)   ::= AS.                  {A = M10d_Any;}
001775  wqas(A)   ::= AS MATERIALIZED.     {A = M10d_Yes;}
001776  wqas(A)   ::= AS NOT MATERIALIZED. {A = M10d_No;}
001777  wqitem(A) ::= withnm(X) eidlist_opt(Y) wqas(M) LP select(Z) RP. {
001778    A = sqlite3CteNew(pParse, &X, Y, Z, M); /*A-overwrites-X*/
001779  }
001780  withnm(A) ::= nm(A). {pParse->bHasWith = 1;}
001781  wqlist(A) ::= wqitem(X). {
001782    A = sqlite3WithAdd(pParse, 0, X); /*A-overwrites-X*/
001783  }
001784  wqlist(A) ::= wqlist(A) COMMA wqitem(X). {
001785    A = sqlite3WithAdd(pParse, A, X);
001786  }
001787  %endif  SQLITE_OMIT_CTE
001788  
001789  //////////////////////// WINDOW FUNCTION EXPRESSIONS /////////////////////////
001790  // These must be at the end of this file. Specifically, the rules that
001791  // introduce tokens WINDOW, OVER and FILTER must appear last. This causes 
001792  // the integer values assigned to these tokens to be larger than all other 
001793  // tokens that may be output by the tokenizer except TK_SPACE and TK_ILLEGAL.
001794  //
001795  %ifndef SQLITE_OMIT_WINDOWFUNC
001796  %type windowdefn_list {Window*}
001797  %destructor windowdefn_list {sqlite3WindowListDelete(pParse->db, $$);}
001798  windowdefn_list(A) ::= windowdefn(A).
001799  windowdefn_list(A) ::= windowdefn_list(Y) COMMA windowdefn(Z). {
001800    assert( Z!=0 );
001801    sqlite3WindowChain(pParse, Z, Y);
001802    Z->pNextWin = Y;
001803    A = Z;
001804  }
001805  
001806  %type windowdefn {Window*}
001807  %destructor windowdefn {sqlite3WindowDelete(pParse->db, $$);}
001808  windowdefn(A) ::= nm(X) AS LP window(Y) RP. {
001809    if( ALWAYS(Y) ){
001810      Y->zName = sqlite3DbStrNDup(pParse->db, X.z, X.n);
001811    }
001812    A = Y;
001813  }
001814  
001815  %type window {Window*}
001816  %destructor window {sqlite3WindowDelete(pParse->db, $$);}
001817  
001818  %type frame_opt {Window*}
001819  %destructor frame_opt {sqlite3WindowDelete(pParse->db, $$);}
001820  
001821  %type part_opt {ExprList*}
001822  %destructor part_opt {sqlite3ExprListDelete(pParse->db, $$);}
001823  
001824  %type filter_clause {Expr*}
001825  %destructor filter_clause {sqlite3ExprDelete(pParse->db, $$);}
001826  
001827  %type over_clause {Window*}
001828  %destructor over_clause {sqlite3WindowDelete(pParse->db, $$);}
001829  
001830  %type filter_over {Window*}
001831  %destructor filter_over {sqlite3WindowDelete(pParse->db, $$);}
001832  
001833  %type range_or_rows {int}
001834  
001835  %type frame_bound {struct FrameBound}
001836  %destructor frame_bound {sqlite3ExprDelete(pParse->db, $$.pExpr);}
001837  %type frame_bound_s {struct FrameBound}
001838  %destructor frame_bound_s {sqlite3ExprDelete(pParse->db, $$.pExpr);}
001839  %type frame_bound_e {struct FrameBound}
001840  %destructor frame_bound_e {sqlite3ExprDelete(pParse->db, $$.pExpr);}
001841  
001842  window(A) ::= PARTITION BY nexprlist(X) orderby_opt(Y) frame_opt(Z). {
001843    A = sqlite3WindowAssemble(pParse, Z, X, Y, 0);
001844  }
001845  window(A) ::= nm(W) PARTITION BY nexprlist(X) orderby_opt(Y) frame_opt(Z). {
001846    A = sqlite3WindowAssemble(pParse, Z, X, Y, &W);
001847  }
001848  window(A) ::= ORDER BY sortlist(Y) frame_opt(Z). {
001849    A = sqlite3WindowAssemble(pParse, Z, 0, Y, 0);
001850  }
001851  window(A) ::= nm(W) ORDER BY sortlist(Y) frame_opt(Z). {
001852    A = sqlite3WindowAssemble(pParse, Z, 0, Y, &W);
001853  }
001854  window(A) ::= frame_opt(A).
001855  window(A) ::= nm(W) frame_opt(Z). {
001856    A = sqlite3WindowAssemble(pParse, Z, 0, 0, &W);
001857  }
001858  
001859  frame_opt(A) ::= .                             { 
001860    A = sqlite3WindowAlloc(pParse, 0, TK_UNBOUNDED, 0, TK_CURRENT, 0, 0);
001861  }
001862  frame_opt(A) ::= range_or_rows(X) frame_bound_s(Y) frame_exclude_opt(Z). { 
001863    A = sqlite3WindowAlloc(pParse, X, Y.eType, Y.pExpr, TK_CURRENT, 0, Z);
001864  }
001865  frame_opt(A) ::= range_or_rows(X) BETWEEN frame_bound_s(Y) AND
001866                            frame_bound_e(Z) frame_exclude_opt(W). { 
001867    A = sqlite3WindowAlloc(pParse, X, Y.eType, Y.pExpr, Z.eType, Z.pExpr, W);
001868  }
001869  
001870  range_or_rows(A) ::= RANGE|ROWS|GROUPS(X).   {A = @X; /*A-overwrites-X*/}
001871  
001872  frame_bound_s(A) ::= frame_bound(X).         {A = X;}
001873  frame_bound_s(A) ::= UNBOUNDED(X) PRECEDING. {A.eType = @X; A.pExpr = 0;}
001874  frame_bound_e(A) ::= frame_bound(X).         {A = X;}
001875  frame_bound_e(A) ::= UNBOUNDED(X) FOLLOWING. {A.eType = @X; A.pExpr = 0;}
001876  
001877  frame_bound(A) ::= expr(X) PRECEDING|FOLLOWING(Y).
001878                                               {A.eType = @Y; A.pExpr = X;}
001879  frame_bound(A) ::= CURRENT(X) ROW.           {A.eType = @X; A.pExpr = 0;}
001880  
001881  %type frame_exclude_opt {u8}
001882  frame_exclude_opt(A) ::= . {A = 0;}
001883  frame_exclude_opt(A) ::= EXCLUDE frame_exclude(X). {A = X;}
001884  
001885  %type frame_exclude {u8}
001886  frame_exclude(A) ::= NO(X) OTHERS.   {A = @X; /*A-overwrites-X*/}
001887  frame_exclude(A) ::= CURRENT(X) ROW. {A = @X; /*A-overwrites-X*/}
001888  frame_exclude(A) ::= GROUP|TIES(X).  {A = @X; /*A-overwrites-X*/}
001889  
001890  
001891  %type window_clause {Window*}
001892  %destructor window_clause {sqlite3WindowListDelete(pParse->db, $$);}
001893  window_clause(A) ::= WINDOW windowdefn_list(B). { A = B; }
001894  
001895  filter_over(A) ::= filter_clause(F) over_clause(O). {
001896    if( O ){
001897      O->pFilter = F;
001898    }else{
001899      sqlite3ExprDelete(pParse->db, F);
001900    }
001901    A = O;
001902  }
001903  filter_over(A) ::= over_clause(O). {
001904    A = O;
001905  }
001906  filter_over(A) ::= filter_clause(F). {
001907    A = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
001908    if( A ){
001909      A->eFrmType = TK_FILTER;
001910      A->pFilter = F;
001911    }else{
001912      sqlite3ExprDelete(pParse->db, F);
001913    }
001914  }
001915  
001916  over_clause(A) ::= OVER LP window(Z) RP. {
001917    A = Z;
001918    assert( A!=0 );
001919  }
001920  over_clause(A) ::= OVER nm(Z). {
001921    A = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
001922    if( A ){
001923      A->zName = sqlite3DbStrNDup(pParse->db, Z.z, Z.n);
001924    }
001925  }
001926  
001927  filter_clause(A) ::= FILTER LP WHERE expr(X) RP.  { A = X; }
001928  %endif /* SQLITE_OMIT_WINDOWFUNC */
001929  
001930  /*
001931  ** The code generator needs some extra TK_ token values for tokens that
001932  ** are synthesized and do not actually appear in the grammar:
001933  */
001934  %token
001935    COLUMN          /* Reference to a table column */
001936    AGG_FUNCTION    /* An aggregate function */
001937    AGG_COLUMN      /* An aggregated column */
001938    TRUEFALSE       /* True or false keyword */
001939    ISNOT           /* Combination of IS and NOT */
001940    FUNCTION        /* A function invocation */
001941    UPLUS           /* Unary plus */
001942    UMINUS          /* Unary minus */
001943    TRUTH           /* IS TRUE or IS FALSE or IS NOT TRUE or IS NOT FALSE */
001944    REGISTER        /* Reference to a VDBE register */
001945    VECTOR          /* Vector */
001946    SELECT_COLUMN   /* Choose a single column from a multi-column SELECT */
001947    IF_NULL_ROW     /* the if-null-row operator */
001948    ASTERISK        /* The "*" in count(*) and similar */
001949    SPAN            /* The span operator */
001950    ERROR           /* An expression containing an error */
001951  .
001952  
001953  term(A) ::= QNUMBER(X). {
001954    A=tokenExpr(pParse,@X,X);
001955    sqlite3DequoteNumber(pParse, A);
001956  }
001957  
001958  /* There must be no more than 255 tokens defined above.  If this grammar
001959  ** is extended with new rules and tokens, they must either be so few in
001960  ** number that TK_SPAN is no more than 255, or else the new tokens must
001961  ** appear after this line.
001962  */
001963  %include {
001964  #if TK_SPAN>255
001965  # error too many tokens in the grammar
001966  #endif
001967  }
001968  
001969  /*
001970  ** The TK_SPACE and TK_ILLEGAL tokens must be the last two tokens.  The
001971  ** parser depends on this.  Those tokens are not used in any grammar rule.
001972  ** They are only used by the tokenizer.  Declare them last so that they
001973  ** are guaranteed to be the last two tokens
001974  */
001975  %token SPACE ILLEGAL.