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