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