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  /*
000103  ** Disable lookaside memory allocation for objects that might be
000104  ** shared across database connections.
000105  */
000106  static void disableLookaside(Parse *pParse){
000107    pParse->disableLookaside++;
000108    pParse->db->lookaside.bDisable++;
000109  }
000110  
000111  } // end %include
000112  
000113  // Input is a single SQL command
000114  input ::= cmdlist.
000115  cmdlist ::= cmdlist ecmd.
000116  cmdlist ::= ecmd.
000117  ecmd ::= SEMI.
000118  ecmd ::= cmdx SEMI.
000119  %ifndef SQLITE_OMIT_EXPLAIN
000120  ecmd ::= explain cmdx.
000121  explain ::= EXPLAIN.              { pParse->explain = 1; }
000122  explain ::= EXPLAIN QUERY PLAN.   { pParse->explain = 2; }
000123  %endif  SQLITE_OMIT_EXPLAIN
000124  cmdx ::= cmd.           { sqlite3FinishCoding(pParse); }
000125  
000126  ///////////////////// Begin and end transactions. ////////////////////////////
000127  //
000128  
000129  cmd ::= BEGIN transtype(Y) trans_opt.  {sqlite3BeginTransaction(pParse, Y);}
000130  trans_opt ::= .
000131  trans_opt ::= TRANSACTION.
000132  trans_opt ::= TRANSACTION nm.
000133  %type transtype {int}
000134  transtype(A) ::= .             {A = TK_DEFERRED;}
000135  transtype(A) ::= DEFERRED(X).  {A = @X; /*A-overwrites-X*/}
000136  transtype(A) ::= IMMEDIATE(X). {A = @X; /*A-overwrites-X*/}
000137  transtype(A) ::= EXCLUSIVE(X). {A = @X; /*A-overwrites-X*/}
000138  cmd ::= COMMIT|END(X) trans_opt.   {sqlite3EndTransaction(pParse,@X);}
000139  cmd ::= ROLLBACK(X) trans_opt.     {sqlite3EndTransaction(pParse,@X);}
000140  
000141  savepoint_opt ::= SAVEPOINT.
000142  savepoint_opt ::= .
000143  cmd ::= SAVEPOINT nm(X). {
000144    sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &X);
000145  }
000146  cmd ::= RELEASE savepoint_opt nm(X). {
000147    sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &X);
000148  }
000149  cmd ::= ROLLBACK trans_opt TO savepoint_opt nm(X). {
000150    sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &X);
000151  }
000152  
000153  ///////////////////// The CREATE TABLE statement ////////////////////////////
000154  //
000155  cmd ::= create_table create_table_args.
000156  create_table ::= createkw temp(T) TABLE ifnotexists(E) nm(Y) dbnm(Z). {
000157     sqlite3StartTable(pParse,&Y,&Z,T,0,0,E);
000158  }
000159  createkw(A) ::= CREATE(A).  {disableLookaside(pParse);}
000160  
000161  %type ifnotexists {int}
000162  ifnotexists(A) ::= .              {A = 0;}
000163  ifnotexists(A) ::= IF NOT EXISTS. {A = 1;}
000164  %type temp {int}
000165  %ifndef SQLITE_OMIT_TEMPDB
000166  temp(A) ::= TEMP.  {A = 1;}
000167  %endif  SQLITE_OMIT_TEMPDB
000168  temp(A) ::= .      {A = 0;}
000169  create_table_args ::= LP columnlist conslist_opt(X) RP(E) table_options(F). {
000170    sqlite3EndTable(pParse,&X,&E,F,0);
000171  }
000172  create_table_args ::= AS select(S). {
000173    sqlite3EndTable(pParse,0,0,0,S);
000174    sqlite3SelectDelete(pParse->db, S);
000175  }
000176  %type table_options {int}
000177  table_options(A) ::= .    {A = 0;}
000178  table_options(A) ::= WITHOUT nm(X). {
000179    if( X.n==5 && sqlite3_strnicmp(X.z,"rowid",5)==0 ){
000180      A = TF_WithoutRowid | TF_NoVisibleRowid;
000181    }else{
000182      A = 0;
000183      sqlite3ErrorMsg(pParse, "unknown table option: %.*s", X.n, X.z);
000184    }
000185  }
000186  columnlist ::= columnlist COMMA columnname carglist.
000187  columnlist ::= columnname carglist.
000188  columnname(A) ::= nm(A) typetoken(Y). {sqlite3AddColumn(pParse,&A,&Y);}
000189  
000190  // Declare some tokens early in order to influence their values, to 
000191  // improve performance and reduce the executable size.  The goal here is
000192  // to get the "jump" operations in ISNULL through ESCAPE to have numeric
000193  // values that are early enough so that all jump operations are clustered
000194  // at the beginning, but also so that the comparison tokens NE through GE
000195  // are as large as possible so that they are near to FUNCTION, which is a
000196  // token synthesized by addopcodes.tcl.
000197  //
000198  %token ABORT ACTION AFTER ANALYZE ASC ATTACH BEFORE BEGIN BY CASCADE CAST.
000199  %token CONFLICT DATABASE DEFERRED DESC DETACH EACH END EXCLUSIVE EXPLAIN FAIL.
000200  %token OR AND NOT IS MATCH LIKE_KW BETWEEN IN ISNULL NOTNULL NE EQ.
000201  %token GT LE LT GE ESCAPE.
000202  
000203  // The following directive causes tokens ABORT, AFTER, ASC, etc. to
000204  // fallback to ID if they will not parse as their original value.
000205  // This obviates the need for the "id" nonterminal.
000206  //
000207  %fallback ID
000208    ABORT ACTION AFTER ANALYZE ASC ATTACH BEFORE BEGIN BY CASCADE CAST COLUMNKW
000209    CONFLICT DATABASE DEFERRED DESC DETACH DO
000210    EACH END EXCLUSIVE EXPLAIN FAIL FOR
000211    IGNORE IMMEDIATE INITIALLY INSTEAD LIKE_KW MATCH NO PLAN
000212    QUERY KEY OF OFFSET PRAGMA RAISE RECURSIVE RELEASE REPLACE RESTRICT ROW
000213    ROLLBACK SAVEPOINT TEMP TRIGGER VACUUM VIEW VIRTUAL WITH WITHOUT
000214  %ifdef SQLITE_OMIT_COMPOUND_SELECT
000215    EXCEPT INTERSECT UNION
000216  %endif SQLITE_OMIT_COMPOUND_SELECT
000217    REINDEX RENAME CTIME_KW IF
000218    .
000219  %wildcard ANY.
000220  
000221  // Define operator precedence early so that this is the first occurrence
000222  // of the operator tokens in the grammer.  Keeping the operators together
000223  // causes them to be assigned integer values that are close together,
000224  // which keeps parser tables smaller.
000225  //
000226  // The token values assigned to these symbols is determined by the order
000227  // in which lemon first sees them.  It must be the case that ISNULL/NOTNULL,
000228  // NE/EQ, GT/LE, and GE/LT are separated by only a single value.  See
000229  // the sqlite3ExprIfFalse() routine for additional information on this
000230  // constraint.
000231  //
000232  %left OR.
000233  %left AND.
000234  %right NOT.
000235  %left IS MATCH LIKE_KW BETWEEN IN ISNULL NOTNULL NE EQ.
000236  %left GT LE LT GE.
000237  %right ESCAPE.
000238  %left BITAND BITOR LSHIFT RSHIFT.
000239  %left PLUS MINUS.
000240  %left STAR SLASH REM.
000241  %left CONCAT.
000242  %left COLLATE.
000243  %right BITNOT.
000244  %nonassoc ON.
000245  
000246  // An IDENTIFIER can be a generic identifier, or one of several
000247  // keywords.  Any non-standard keyword can also be an identifier.
000248  //
000249  %token_class id  ID|INDEXED.
000250  
000251  
000252  // And "ids" is an identifer-or-string.
000253  //
000254  %token_class ids  ID|STRING.
000255  
000256  // The name of a column or table can be any of the following:
000257  //
000258  %type nm {Token}
000259  nm(A) ::= id(A).
000260  nm(A) ::= STRING(A).
000261  nm(A) ::= JOIN_KW(A).
000262  
000263  // A typetoken is really zero or more tokens that form a type name such
000264  // as can be found after the column name in a CREATE TABLE statement.
000265  // Multiple tokens are concatenated to form the value of the typetoken.
000266  //
000267  %type typetoken {Token}
000268  typetoken(A) ::= .   {A.n = 0; A.z = 0;}
000269  typetoken(A) ::= typename(A).
000270  typetoken(A) ::= typename(A) LP signed RP(Y). {
000271    A.n = (int)(&Y.z[Y.n] - A.z);
000272  }
000273  typetoken(A) ::= typename(A) LP signed COMMA signed RP(Y). {
000274    A.n = (int)(&Y.z[Y.n] - A.z);
000275  }
000276  %type typename {Token}
000277  typename(A) ::= ids(A).
000278  typename(A) ::= typename(A) ids(Y). {A.n=Y.n+(int)(Y.z-A.z);}
000279  signed ::= plus_num.
000280  signed ::= minus_num.
000281  
000282  // The scanpt non-terminal takes a value which is a pointer to the
000283  // input text just past the last token that has been shifted into
000284  // the parser.  By surrounding some phrase in the grammar with two
000285  // scanpt non-terminals, we can capture the input text for that phrase.
000286  // For example:
000287  //
000288  //      something ::= .... scanpt(A) phrase scanpt(Z).
000289  //
000290  // The text that is parsed as "phrase" is a string starting at A
000291  // and containing (int)(Z-A) characters.  There might be some extra
000292  // whitespace on either end of the text, but that can be removed in
000293  // post-processing, if needed.
000294  //
000295  %type scanpt {const char*}
000296  scanpt(A) ::= . {
000297    assert( yyLookahead!=YYNOCODE );
000298    A = yyLookaheadToken.z;
000299  }
000300  
000301  // "carglist" is a list of additional constraints that come after the
000302  // column name and column type in a CREATE TABLE statement.
000303  //
000304  carglist ::= carglist ccons.
000305  carglist ::= .
000306  ccons ::= CONSTRAINT nm(X).           {pParse->constraintName = X;}
000307  ccons ::= DEFAULT scanpt(A) term(X) scanpt(Z).
000308                              {sqlite3AddDefaultValue(pParse,X,A,Z);}
000309  ccons ::= DEFAULT LP(A) expr(X) RP(Z).
000310                              {sqlite3AddDefaultValue(pParse,X,A.z+1,Z.z);}
000311  ccons ::= DEFAULT PLUS(A) term(X) scanpt(Z).
000312                              {sqlite3AddDefaultValue(pParse,X,A.z,Z);}
000313  ccons ::= DEFAULT MINUS(A) term(X) scanpt(Z).      {
000314    Expr *p = sqlite3PExpr(pParse, TK_UMINUS, X, 0);
000315    sqlite3AddDefaultValue(pParse,p,A.z,Z);
000316  }
000317  ccons ::= DEFAULT scanpt id(X).       {
000318    Expr *p = tokenExpr(pParse, TK_STRING, X);
000319    if( p ){
000320      sqlite3ExprIdToTrueFalse(p);
000321      testcase( p->op==TK_TRUEFALSE && sqlite3ExprTruthValue(p) );
000322    }
000323    sqlite3AddDefaultValue(pParse,p,X.z,X.z+X.n);
000324  }
000325  
000326  // In addition to the type name, we also care about the primary key and
000327  // UNIQUE constraints.
000328  //
000329  ccons ::= NULL onconf.
000330  ccons ::= NOT NULL onconf(R).    {sqlite3AddNotNull(pParse, R);}
000331  ccons ::= PRIMARY KEY sortorder(Z) onconf(R) autoinc(I).
000332                                   {sqlite3AddPrimaryKey(pParse,0,R,I,Z);}
000333  ccons ::= UNIQUE onconf(R).      {sqlite3CreateIndex(pParse,0,0,0,0,R,0,0,0,0,
000334                                     SQLITE_IDXTYPE_UNIQUE);}
000335  ccons ::= CHECK LP expr(X) RP.   {sqlite3AddCheckConstraint(pParse,X);}
000336  ccons ::= REFERENCES nm(T) eidlist_opt(TA) refargs(R).
000337                                   {sqlite3CreateForeignKey(pParse,0,&T,TA,R);}
000338  ccons ::= defer_subclause(D).    {sqlite3DeferForeignKey(pParse,D);}
000339  ccons ::= COLLATE ids(C).        {sqlite3AddCollateType(pParse, &C);}
000340  
000341  // The optional AUTOINCREMENT keyword
000342  %type autoinc {int}
000343  autoinc(X) ::= .          {X = 0;}
000344  autoinc(X) ::= AUTOINCR.  {X = 1;}
000345  
000346  // The next group of rules parses the arguments to a REFERENCES clause
000347  // that determine if the referential integrity checking is deferred or
000348  // or immediate and which determine what action to take if a ref-integ
000349  // check fails.
000350  //
000351  %type refargs {int}
000352  refargs(A) ::= .                  { A = OE_None*0x0101; /* EV: R-19803-45884 */}
000353  refargs(A) ::= refargs(A) refarg(Y). { A = (A & ~Y.mask) | Y.value; }
000354  %type refarg {struct {int value; int mask;}}
000355  refarg(A) ::= MATCH nm.              { A.value = 0;     A.mask = 0x000000; }
000356  refarg(A) ::= ON INSERT refact.      { A.value = 0;     A.mask = 0x000000; }
000357  refarg(A) ::= ON DELETE refact(X).   { A.value = X;     A.mask = 0x0000ff; }
000358  refarg(A) ::= ON UPDATE refact(X).   { A.value = X<<8;  A.mask = 0x00ff00; }
000359  %type refact {int}
000360  refact(A) ::= SET NULL.              { A = OE_SetNull;  /* EV: R-33326-45252 */}
000361  refact(A) ::= SET DEFAULT.           { A = OE_SetDflt;  /* EV: R-33326-45252 */}
000362  refact(A) ::= CASCADE.               { A = OE_Cascade;  /* EV: R-33326-45252 */}
000363  refact(A) ::= RESTRICT.              { A = OE_Restrict; /* EV: R-33326-45252 */}
000364  refact(A) ::= NO ACTION.             { A = OE_None;     /* EV: R-33326-45252 */}
000365  %type defer_subclause {int}
000366  defer_subclause(A) ::= NOT DEFERRABLE init_deferred_pred_opt.     {A = 0;}
000367  defer_subclause(A) ::= DEFERRABLE init_deferred_pred_opt(X).      {A = X;}
000368  %type init_deferred_pred_opt {int}
000369  init_deferred_pred_opt(A) ::= .                       {A = 0;}
000370  init_deferred_pred_opt(A) ::= INITIALLY DEFERRED.     {A = 1;}
000371  init_deferred_pred_opt(A) ::= INITIALLY IMMEDIATE.    {A = 0;}
000372  
000373  conslist_opt(A) ::= .                         {A.n = 0; A.z = 0;}
000374  conslist_opt(A) ::= COMMA(A) conslist.
000375  conslist ::= conslist tconscomma tcons.
000376  conslist ::= tcons.
000377  tconscomma ::= COMMA.            {pParse->constraintName.n = 0;}
000378  tconscomma ::= .
000379  tcons ::= CONSTRAINT nm(X).      {pParse->constraintName = X;}
000380  tcons ::= PRIMARY KEY LP sortlist(X) autoinc(I) RP onconf(R).
000381                                   {sqlite3AddPrimaryKey(pParse,X,R,I,0);}
000382  tcons ::= UNIQUE LP sortlist(X) RP onconf(R).
000383                                   {sqlite3CreateIndex(pParse,0,0,0,X,R,0,0,0,0,
000384                                         SQLITE_IDXTYPE_UNIQUE);}
000385  tcons ::= CHECK LP expr(E) RP onconf.
000386                                   {sqlite3AddCheckConstraint(pParse,E);}
000387  tcons ::= FOREIGN KEY LP eidlist(FA) RP
000388            REFERENCES nm(T) eidlist_opt(TA) refargs(R) defer_subclause_opt(D). {
000389      sqlite3CreateForeignKey(pParse, FA, &T, TA, R);
000390      sqlite3DeferForeignKey(pParse, D);
000391  }
000392  %type defer_subclause_opt {int}
000393  defer_subclause_opt(A) ::= .                    {A = 0;}
000394  defer_subclause_opt(A) ::= defer_subclause(A).
000395  
000396  // The following is a non-standard extension that allows us to declare the
000397  // default behavior when there is a constraint conflict.
000398  //
000399  %type onconf {int}
000400  %type orconf {int}
000401  %type resolvetype {int}
000402  onconf(A) ::= .                              {A = OE_Default;}
000403  onconf(A) ::= ON CONFLICT resolvetype(X).    {A = X;}
000404  orconf(A) ::= .                              {A = OE_Default;}
000405  orconf(A) ::= OR resolvetype(X).             {A = X;}
000406  resolvetype(A) ::= raisetype(A).
000407  resolvetype(A) ::= IGNORE.                   {A = OE_Ignore;}
000408  resolvetype(A) ::= REPLACE.                  {A = OE_Replace;}
000409  
000410  ////////////////////////// The DROP TABLE /////////////////////////////////////
000411  //
000412  cmd ::= DROP TABLE ifexists(E) fullname(X). {
000413    sqlite3DropTable(pParse, X, 0, E);
000414  }
000415  %type ifexists {int}
000416  ifexists(A) ::= IF EXISTS.   {A = 1;}
000417  ifexists(A) ::= .            {A = 0;}
000418  
000419  ///////////////////// The CREATE VIEW statement /////////////////////////////
000420  //
000421  %ifndef SQLITE_OMIT_VIEW
000422  cmd ::= createkw(X) temp(T) VIEW ifnotexists(E) nm(Y) dbnm(Z) eidlist_opt(C)
000423            AS select(S). {
000424    sqlite3CreateView(pParse, &X, &Y, &Z, C, S, T, E);
000425  }
000426  cmd ::= DROP VIEW ifexists(E) fullname(X). {
000427    sqlite3DropTable(pParse, X, 1, E);
000428  }
000429  %endif  SQLITE_OMIT_VIEW
000430  
000431  //////////////////////// The SELECT statement /////////////////////////////////
000432  //
000433  cmd ::= select(X).  {
000434    SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
000435    sqlite3Select(pParse, X, &dest);
000436    sqlite3SelectDelete(pParse->db, X);
000437  }
000438  
000439  %type select {Select*}
000440  %destructor select {sqlite3SelectDelete(pParse->db, $$);}
000441  %type selectnowith {Select*}
000442  %destructor selectnowith {sqlite3SelectDelete(pParse->db, $$);}
000443  %type oneselect {Select*}
000444  %destructor oneselect {sqlite3SelectDelete(pParse->db, $$);}
000445  
000446  %include {
000447    /*
000448    ** For a compound SELECT statement, make sure p->pPrior->pNext==p for
000449    ** all elements in the list.  And make sure list length does not exceed
000450    ** SQLITE_LIMIT_COMPOUND_SELECT.
000451    */
000452    static void parserDoubleLinkSelect(Parse *pParse, Select *p){
000453      if( p->pPrior ){
000454        Select *pNext = 0, *pLoop;
000455        int mxSelect, cnt = 0;
000456        for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
000457          pLoop->pNext = pNext;
000458          pLoop->selFlags |= SF_Compound;
000459        }
000460        if( (p->selFlags & SF_MultiValue)==0 && 
000461          (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 &&
000462          cnt>mxSelect
000463        ){
000464          sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
000465        }
000466      }
000467    }
000468  }
000469  
000470  %ifndef SQLITE_OMIT_CTE
000471  select(A) ::= WITH wqlist(W) selectnowith(X). {
000472    Select *p = X;
000473    if( p ){
000474      p->pWith = W;
000475      parserDoubleLinkSelect(pParse, p);
000476    }else{
000477      sqlite3WithDelete(pParse->db, W);
000478    }
000479    A = p;
000480  }
000481  select(A) ::= WITH RECURSIVE wqlist(W) selectnowith(X). {
000482    Select *p = X;
000483    if( p ){
000484      p->pWith = W;
000485      parserDoubleLinkSelect(pParse, p);
000486    }else{
000487      sqlite3WithDelete(pParse->db, W);
000488    }
000489    A = p;
000490  }
000491  %endif /* SQLITE_OMIT_CTE */
000492  select(A) ::= selectnowith(X). {
000493    Select *p = X;
000494    if( p ){
000495      parserDoubleLinkSelect(pParse, p);
000496    }
000497    A = p; /*A-overwrites-X*/
000498  }
000499  
000500  selectnowith(A) ::= oneselect(A).
000501  %ifndef SQLITE_OMIT_COMPOUND_SELECT
000502  selectnowith(A) ::= selectnowith(A) multiselect_op(Y) oneselect(Z).  {
000503    Select *pRhs = Z;
000504    Select *pLhs = A;
000505    if( pRhs && pRhs->pPrior ){
000506      SrcList *pFrom;
000507      Token x;
000508      x.n = 0;
000509      parserDoubleLinkSelect(pParse, pRhs);
000510      pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
000511      pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0);
000512    }
000513    if( pRhs ){
000514      pRhs->op = (u8)Y;
000515      pRhs->pPrior = pLhs;
000516      if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue;
000517      pRhs->selFlags &= ~SF_MultiValue;
000518      if( Y!=TK_ALL ) pParse->hasCompound = 1;
000519    }else{
000520      sqlite3SelectDelete(pParse->db, pLhs);
000521    }
000522    A = pRhs;
000523  }
000524  %type multiselect_op {int}
000525  multiselect_op(A) ::= UNION(OP).             {A = @OP; /*A-overwrites-OP*/}
000526  multiselect_op(A) ::= UNION ALL.             {A = TK_ALL;}
000527  multiselect_op(A) ::= EXCEPT|INTERSECT(OP).  {A = @OP; /*A-overwrites-OP*/}
000528  %endif SQLITE_OMIT_COMPOUND_SELECT
000529  oneselect(A) ::= SELECT(S) distinct(D) selcollist(W) from(X) where_opt(Y)
000530                   groupby_opt(P) having_opt(Q) orderby_opt(Z) limit_opt(L). {
000531  #if SELECTTRACE_ENABLED
000532    Token s = S; /*A-overwrites-S*/
000533  #endif
000534    A = sqlite3SelectNew(pParse,W,X,Y,P,Q,Z,D,L);
000535  #if SELECTTRACE_ENABLED
000536    /* Populate the Select.zSelName[] string that is used to help with
000537    ** query planner debugging, to differentiate between multiple Select
000538    ** objects in a complex query.
000539    **
000540    ** If the SELECT keyword is immediately followed by a C-style comment
000541    ** then extract the first few alphanumeric characters from within that
000542    ** comment to be the zSelName value.  Otherwise, the label is #N where
000543    ** is an integer that is incremented with each SELECT statement seen.
000544    */
000545    if( A!=0 ){
000546      const char *z = s.z+6;
000547      int i;
000548      sqlite3_snprintf(sizeof(A->zSelName), A->zSelName,"#%d",++pParse->nSelect);
000549      while( z[0]==' ' ) z++;
000550      if( z[0]=='/' && z[1]=='*' ){
000551        z += 2;
000552        while( z[0]==' ' ) z++;
000553        for(i=0; sqlite3Isalnum(z[i]); i++){}
000554        sqlite3_snprintf(sizeof(A->zSelName), A->zSelName, "%.*s", i, z);
000555      }
000556    }
000557  #endif /* SELECTRACE_ENABLED */
000558  }
000559  oneselect(A) ::= values(A).
000560  
000561  %type values {Select*}
000562  %destructor values {sqlite3SelectDelete(pParse->db, $$);}
000563  values(A) ::= VALUES LP nexprlist(X) RP. {
000564    A = sqlite3SelectNew(pParse,X,0,0,0,0,0,SF_Values,0);
000565  }
000566  values(A) ::= values(A) COMMA LP exprlist(Y) RP. {
000567    Select *pRight, *pLeft = A;
000568    pRight = sqlite3SelectNew(pParse,Y,0,0,0,0,0,SF_Values|SF_MultiValue,0);
000569    if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue;
000570    if( pRight ){
000571      pRight->op = TK_ALL;
000572      pRight->pPrior = pLeft;
000573      A = pRight;
000574    }else{
000575      A = pLeft;
000576    }
000577  }
000578  
000579  // The "distinct" nonterminal is true (1) if the DISTINCT keyword is
000580  // present and false (0) if it is not.
000581  //
000582  %type distinct {int}
000583  distinct(A) ::= DISTINCT.   {A = SF_Distinct;}
000584  distinct(A) ::= ALL.        {A = SF_All;}
000585  distinct(A) ::= .           {A = 0;}
000586  
000587  // selcollist is a list of expressions that are to become the return
000588  // values of the SELECT statement.  The "*" in statements like
000589  // "SELECT * FROM ..." is encoded as a special expression with an
000590  // opcode of TK_ASTERISK.
000591  //
000592  %type selcollist {ExprList*}
000593  %destructor selcollist {sqlite3ExprListDelete(pParse->db, $$);}
000594  %type sclp {ExprList*}
000595  %destructor sclp {sqlite3ExprListDelete(pParse->db, $$);}
000596  sclp(A) ::= selcollist(A) COMMA.
000597  sclp(A) ::= .                                {A = 0;}
000598  selcollist(A) ::= sclp(A) scanpt(B) expr(X) scanpt(Z) as(Y).     {
000599     A = sqlite3ExprListAppend(pParse, A, X);
000600     if( Y.n>0 ) sqlite3ExprListSetName(pParse, A, &Y, 1);
000601     sqlite3ExprListSetSpan(pParse,A,B,Z);
000602  }
000603  selcollist(A) ::= sclp(A) scanpt STAR. {
000604    Expr *p = sqlite3Expr(pParse->db, TK_ASTERISK, 0);
000605    A = sqlite3ExprListAppend(pParse, A, p);
000606  }
000607  selcollist(A) ::= sclp(A) scanpt nm(X) DOT STAR. {
000608    Expr *pRight = sqlite3PExpr(pParse, TK_ASTERISK, 0, 0);
000609    Expr *pLeft = sqlite3ExprAlloc(pParse->db, TK_ID, &X, 1);
000610    Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
000611    A = sqlite3ExprListAppend(pParse,A, pDot);
000612  }
000613  
000614  // An option "AS <id>" phrase that can follow one of the expressions that
000615  // define the result set, or one of the tables in the FROM clause.
000616  //
000617  %type as {Token}
000618  as(X) ::= AS nm(Y).    {X = Y;}
000619  as(X) ::= ids(X).
000620  as(X) ::= .            {X.n = 0; X.z = 0;}
000621  
000622  
000623  %type seltablist {SrcList*}
000624  %destructor seltablist {sqlite3SrcListDelete(pParse->db, $$);}
000625  %type stl_prefix {SrcList*}
000626  %destructor stl_prefix {sqlite3SrcListDelete(pParse->db, $$);}
000627  %type from {SrcList*}
000628  %destructor from {sqlite3SrcListDelete(pParse->db, $$);}
000629  
000630  // A complete FROM clause.
000631  //
000632  from(A) ::= .                {A = sqlite3DbMallocZero(pParse->db, sizeof(*A));}
000633  from(A) ::= FROM seltablist(X). {
000634    A = X;
000635    sqlite3SrcListShiftJoinType(A);
000636  }
000637  
000638  // "seltablist" is a "Select Table List" - the content of the FROM clause
000639  // in a SELECT statement.  "stl_prefix" is a prefix of this list.
000640  //
000641  stl_prefix(A) ::= seltablist(A) joinop(Y).    {
000642     if( ALWAYS(A && A->nSrc>0) ) A->a[A->nSrc-1].fg.jointype = (u8)Y;
000643  }
000644  stl_prefix(A) ::= .                           {A = 0;}
000645  seltablist(A) ::= stl_prefix(A) nm(Y) dbnm(D) as(Z) indexed_opt(I)
000646                    on_opt(N) using_opt(U). {
000647    A = sqlite3SrcListAppendFromTerm(pParse,A,&Y,&D,&Z,0,N,U);
000648    sqlite3SrcListIndexedBy(pParse, A, &I);
000649  }
000650  seltablist(A) ::= stl_prefix(A) nm(Y) dbnm(D) LP exprlist(E) RP as(Z)
000651                    on_opt(N) using_opt(U). {
000652    A = sqlite3SrcListAppendFromTerm(pParse,A,&Y,&D,&Z,0,N,U);
000653    sqlite3SrcListFuncArgs(pParse, A, E);
000654  }
000655  %ifndef SQLITE_OMIT_SUBQUERY
000656    seltablist(A) ::= stl_prefix(A) LP select(S) RP
000657                      as(Z) on_opt(N) using_opt(U). {
000658      A = sqlite3SrcListAppendFromTerm(pParse,A,0,0,&Z,S,N,U);
000659    }
000660    seltablist(A) ::= stl_prefix(A) LP seltablist(F) RP
000661                      as(Z) on_opt(N) using_opt(U). {
000662      if( A==0 && Z.n==0 && N==0 && U==0 ){
000663        A = F;
000664      }else if( F->nSrc==1 ){
000665        A = sqlite3SrcListAppendFromTerm(pParse,A,0,0,&Z,0,N,U);
000666        if( A ){
000667          struct SrcList_item *pNew = &A->a[A->nSrc-1];
000668          struct SrcList_item *pOld = F->a;
000669          pNew->zName = pOld->zName;
000670          pNew->zDatabase = pOld->zDatabase;
000671          pNew->pSelect = pOld->pSelect;
000672          pOld->zName = pOld->zDatabase = 0;
000673          pOld->pSelect = 0;
000674        }
000675        sqlite3SrcListDelete(pParse->db, F);
000676      }else{
000677        Select *pSubquery;
000678        sqlite3SrcListShiftJoinType(F);
000679        pSubquery = sqlite3SelectNew(pParse,0,F,0,0,0,0,SF_NestedFrom,0);
000680        A = sqlite3SrcListAppendFromTerm(pParse,A,0,0,&Z,pSubquery,N,U);
000681      }
000682    }
000683  %endif  SQLITE_OMIT_SUBQUERY
000684  
000685  %type dbnm {Token}
000686  dbnm(A) ::= .          {A.z=0; A.n=0;}
000687  dbnm(A) ::= DOT nm(X). {A = X;}
000688  
000689  %type fullname {SrcList*}
000690  %destructor fullname {sqlite3SrcListDelete(pParse->db, $$);}
000691  fullname(A) ::= nm(X).  
000692     {A = sqlite3SrcListAppend(pParse->db,0,&X,0); /*A-overwrites-X*/}
000693  fullname(A) ::= nm(X) DOT nm(Y).  
000694     {A = sqlite3SrcListAppend(pParse->db,0,&X,&Y); /*A-overwrites-X*/}
000695  
000696  %type xfullname {SrcList*}
000697  %destructor xfullname {sqlite3SrcListDelete(pParse->db, $$);}
000698  xfullname(A) ::= nm(X).  
000699     {A = sqlite3SrcListAppend(pParse->db,0,&X,0); /*A-overwrites-X*/}
000700  xfullname(A) ::= nm(X) DOT nm(Y).  
000701     {A = sqlite3SrcListAppend(pParse->db,0,&X,&Y); /*A-overwrites-X*/}
000702  xfullname(A) ::= nm(X) DOT nm(Y) AS nm(Z).  {
000703     A = sqlite3SrcListAppend(pParse->db,0,&X,&Y); /*A-overwrites-X*/
000704     if( A ) A->a[0].zAlias = sqlite3NameFromToken(pParse->db, &Z);
000705  }
000706  xfullname(A) ::= nm(X) AS nm(Z). {  
000707     A = sqlite3SrcListAppend(pParse->db,0,&X,0); /*A-overwrites-X*/
000708     if( A ) A->a[0].zAlias = sqlite3NameFromToken(pParse->db, &Z);
000709  }
000710  
000711  %type joinop {int}
000712  joinop(X) ::= COMMA|JOIN.              { X = JT_INNER; }
000713  joinop(X) ::= JOIN_KW(A) JOIN.
000714                    {X = sqlite3JoinType(pParse,&A,0,0);  /*X-overwrites-A*/}
000715  joinop(X) ::= JOIN_KW(A) nm(B) JOIN.
000716                    {X = sqlite3JoinType(pParse,&A,&B,0); /*X-overwrites-A*/}
000717  joinop(X) ::= JOIN_KW(A) nm(B) nm(C) JOIN.
000718                    {X = sqlite3JoinType(pParse,&A,&B,&C);/*X-overwrites-A*/}
000719  
000720  // There is a parsing abiguity in an upsert statement that uses a
000721  // SELECT on the RHS of a the INSERT:
000722  //
000723  //      INSERT INTO tab SELECT * FROM aaa JOIN bbb ON CONFLICT ...
000724  //                                        here ----^^
000725  //
000726  // When the ON token is encountered, the parser does not know if it is
000727  // the beginning of an ON CONFLICT clause, or the beginning of an ON
000728  // clause associated with the JOIN.  The conflict is resolved in favor
000729  // of the JOIN.  If an ON CONFLICT clause is intended, insert a dummy
000730  // WHERE clause in between, like this:
000731  //
000732  //      INSERT INTO tab SELECT * FROM aaa JOIN bbb WHERE true ON CONFLICT ...
000733  //
000734  // The [AND] and [OR] precedence marks in the rules for on_opt cause the
000735  // ON in this context to always be interpreted as belonging to the JOIN.
000736  //
000737  %type on_opt {Expr*}
000738  %destructor on_opt {sqlite3ExprDelete(pParse->db, $$);}
000739  on_opt(N) ::= ON expr(E).  {N = E;}
000740  on_opt(N) ::= .     [OR]   {N = 0;}
000741  
000742  // Note that this block abuses the Token type just a little. If there is
000743  // no "INDEXED BY" clause, the returned token is empty (z==0 && n==0). If
000744  // there is an INDEXED BY clause, then the token is populated as per normal,
000745  // with z pointing to the token data and n containing the number of bytes
000746  // in the token.
000747  //
000748  // If there is a "NOT INDEXED" clause, then (z==0 && n==1), which is 
000749  // normally illegal. The sqlite3SrcListIndexedBy() function 
000750  // recognizes and interprets this as a special case.
000751  //
000752  %type indexed_opt {Token}
000753  indexed_opt(A) ::= .                 {A.z=0; A.n=0;}
000754  indexed_opt(A) ::= INDEXED BY nm(X). {A = X;}
000755  indexed_opt(A) ::= NOT INDEXED.      {A.z=0; A.n=1;}
000756  
000757  %type using_opt {IdList*}
000758  %destructor using_opt {sqlite3IdListDelete(pParse->db, $$);}
000759  using_opt(U) ::= USING LP idlist(L) RP.  {U = L;}
000760  using_opt(U) ::= .                        {U = 0;}
000761  
000762  
000763  %type orderby_opt {ExprList*}
000764  %destructor orderby_opt {sqlite3ExprListDelete(pParse->db, $$);}
000765  
000766  // the sortlist non-terminal stores a list of expression where each
000767  // expression is optionally followed by ASC or DESC to indicate the
000768  // sort order.
000769  //
000770  %type sortlist {ExprList*}
000771  %destructor sortlist {sqlite3ExprListDelete(pParse->db, $$);}
000772  
000773  orderby_opt(A) ::= .                          {A = 0;}
000774  orderby_opt(A) ::= ORDER BY sortlist(X).      {A = X;}
000775  sortlist(A) ::= sortlist(A) COMMA expr(Y) sortorder(Z). {
000776    A = sqlite3ExprListAppend(pParse,A,Y);
000777    sqlite3ExprListSetSortOrder(A,Z);
000778  }
000779  sortlist(A) ::= expr(Y) sortorder(Z). {
000780    A = sqlite3ExprListAppend(pParse,0,Y); /*A-overwrites-Y*/
000781    sqlite3ExprListSetSortOrder(A,Z);
000782  }
000783  
000784  %type sortorder {int}
000785  
000786  sortorder(A) ::= ASC.           {A = SQLITE_SO_ASC;}
000787  sortorder(A) ::= DESC.          {A = SQLITE_SO_DESC;}
000788  sortorder(A) ::= .              {A = SQLITE_SO_UNDEFINED;}
000789  
000790  %type groupby_opt {ExprList*}
000791  %destructor groupby_opt {sqlite3ExprListDelete(pParse->db, $$);}
000792  groupby_opt(A) ::= .                      {A = 0;}
000793  groupby_opt(A) ::= GROUP BY nexprlist(X). {A = X;}
000794  
000795  %type having_opt {Expr*}
000796  %destructor having_opt {sqlite3ExprDelete(pParse->db, $$);}
000797  having_opt(A) ::= .                {A = 0;}
000798  having_opt(A) ::= HAVING expr(X).  {A = X;}
000799  
000800  %type limit_opt {Expr*}
000801  
000802  // The destructor for limit_opt will never fire in the current grammar.
000803  // The limit_opt non-terminal only occurs at the end of a single production
000804  // rule for SELECT statements.  As soon as the rule that create the 
000805  // limit_opt non-terminal reduces, the SELECT statement rule will also
000806  // reduce.  So there is never a limit_opt non-terminal on the stack 
000807  // except as a transient.  So there is never anything to destroy.
000808  //
000809  //%destructor limit_opt {sqlite3ExprDelete(pParse->db, $$);}
000810  limit_opt(A) ::= .       {A = 0;}
000811  limit_opt(A) ::= LIMIT expr(X).
000812                           {A = sqlite3PExpr(pParse,TK_LIMIT,X,0);}
000813  limit_opt(A) ::= LIMIT expr(X) OFFSET expr(Y). 
000814                           {A = sqlite3PExpr(pParse,TK_LIMIT,X,Y);}
000815  limit_opt(A) ::= LIMIT expr(X) COMMA expr(Y). 
000816                           {A = sqlite3PExpr(pParse,TK_LIMIT,Y,X);}
000817  
000818  /////////////////////////// The DELETE statement /////////////////////////////
000819  //
000820  %ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
000821  cmd ::= with DELETE FROM xfullname(X) indexed_opt(I) where_opt(W) 
000822          orderby_opt(O) limit_opt(L). {
000823    sqlite3SrcListIndexedBy(pParse, X, &I);
000824    sqlite3DeleteFrom(pParse,X,W,O,L);
000825  }
000826  %endif
000827  %ifndef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
000828  cmd ::= with DELETE FROM xfullname(X) indexed_opt(I) where_opt(W). {
000829    sqlite3SrcListIndexedBy(pParse, X, &I);
000830    sqlite3DeleteFrom(pParse,X,W,0,0);
000831  }
000832  %endif
000833  
000834  %type where_opt {Expr*}
000835  %destructor where_opt {sqlite3ExprDelete(pParse->db, $$);}
000836  
000837  where_opt(A) ::= .                    {A = 0;}
000838  where_opt(A) ::= WHERE expr(X).       {A = X;}
000839  
000840  ////////////////////////// The UPDATE command ////////////////////////////////
000841  //
000842  %ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
000843  cmd ::= with UPDATE orconf(R) xfullname(X) indexed_opt(I) SET setlist(Y)
000844          where_opt(W) orderby_opt(O) limit_opt(L).  {
000845    sqlite3SrcListIndexedBy(pParse, X, &I);
000846    sqlite3ExprListCheckLength(pParse,Y,"set list"); 
000847    sqlite3Update(pParse,X,Y,W,R,O,L,0);
000848  }
000849  %endif
000850  %ifndef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
000851  cmd ::= with UPDATE orconf(R) xfullname(X) indexed_opt(I) SET setlist(Y)
000852          where_opt(W).  {
000853    sqlite3SrcListIndexedBy(pParse, X, &I);
000854    sqlite3ExprListCheckLength(pParse,Y,"set list"); 
000855    sqlite3Update(pParse,X,Y,W,R,0,0,0);
000856  }
000857  %endif
000858  
000859  %type setlist {ExprList*}
000860  %destructor setlist {sqlite3ExprListDelete(pParse->db, $$);}
000861  
000862  setlist(A) ::= setlist(A) COMMA nm(X) EQ expr(Y). {
000863    A = sqlite3ExprListAppend(pParse, A, Y);
000864    sqlite3ExprListSetName(pParse, A, &X, 1);
000865  }
000866  setlist(A) ::= setlist(A) COMMA LP idlist(X) RP EQ expr(Y). {
000867    A = sqlite3ExprListAppendVector(pParse, A, X, Y);
000868  }
000869  setlist(A) ::= nm(X) EQ expr(Y). {
000870    A = sqlite3ExprListAppend(pParse, 0, Y);
000871    sqlite3ExprListSetName(pParse, A, &X, 1);
000872  }
000873  setlist(A) ::= LP idlist(X) RP EQ expr(Y). {
000874    A = sqlite3ExprListAppendVector(pParse, 0, X, Y);
000875  }
000876  
000877  ////////////////////////// The INSERT command /////////////////////////////////
000878  //
000879  cmd ::= with insert_cmd(R) INTO xfullname(X) idlist_opt(F) select(S)
000880          upsert(U). {
000881    sqlite3Insert(pParse, X, S, F, R, U);
000882  }
000883  cmd ::= with insert_cmd(R) INTO xfullname(X) idlist_opt(F) DEFAULT VALUES.
000884  {
000885    sqlite3Insert(pParse, X, 0, F, R, 0);
000886  }
000887  
000888  %type upsert {Upsert*}
000889  
000890  // Because upsert only occurs at the tip end of the INSERT rule for cmd,
000891  // there is never a case where the value of the upsert pointer will not
000892  // be destroyed by the cmd action.  So comment-out the destructor to
000893  // avoid unreachable code.
000894  //%destructor upsert {sqlite3UpsertDelete(pParse->db,$$);}
000895  upsert(A) ::= . { A = 0; }
000896  upsert(A) ::= ON CONFLICT LP sortlist(T) RP where_opt(TW)
000897                DO UPDATE SET setlist(Z) where_opt(W).
000898                { A = sqlite3UpsertNew(pParse->db,T,TW,Z,W);}
000899  upsert(A) ::= ON CONFLICT LP sortlist(T) RP where_opt(TW) DO NOTHING.
000900                { A = sqlite3UpsertNew(pParse->db,T,TW,0,0); }
000901  upsert(A) ::= ON CONFLICT DO NOTHING.
000902                { A = sqlite3UpsertNew(pParse->db,0,0,0,0); }
000903  
000904  %type insert_cmd {int}
000905  insert_cmd(A) ::= INSERT orconf(R).   {A = R;}
000906  insert_cmd(A) ::= REPLACE.            {A = OE_Replace;}
000907  
000908  %type idlist_opt {IdList*}
000909  %destructor idlist_opt {sqlite3IdListDelete(pParse->db, $$);}
000910  %type idlist {IdList*}
000911  %destructor idlist {sqlite3IdListDelete(pParse->db, $$);}
000912  
000913  idlist_opt(A) ::= .                       {A = 0;}
000914  idlist_opt(A) ::= LP idlist(X) RP.    {A = X;}
000915  idlist(A) ::= idlist(A) COMMA nm(Y).
000916      {A = sqlite3IdListAppend(pParse->db,A,&Y);}
000917  idlist(A) ::= nm(Y).
000918      {A = sqlite3IdListAppend(pParse->db,0,&Y); /*A-overwrites-Y*/}
000919  
000920  /////////////////////////// Expression Processing /////////////////////////////
000921  //
000922  
000923  %type expr {Expr*}
000924  %destructor expr {sqlite3ExprDelete(pParse->db, $$);}
000925  %type term {Expr*}
000926  %destructor term {sqlite3ExprDelete(pParse->db, $$);}
000927  
000928  %include {
000929  
000930    /* Construct a new Expr object from a single identifier.  Use the
000931    ** new Expr to populate pOut.  Set the span of pOut to be the identifier
000932    ** that created the expression.
000933    */
000934    static Expr *tokenExpr(Parse *pParse, int op, Token t){
000935      Expr *p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr)+t.n+1);
000936      if( p ){
000937        memset(p, 0, sizeof(Expr));
000938        p->op = (u8)op;
000939        p->flags = EP_Leaf;
000940        p->iAgg = -1;
000941        p->u.zToken = (char*)&p[1];
000942        memcpy(p->u.zToken, t.z, t.n);
000943        p->u.zToken[t.n] = 0;
000944        if( sqlite3Isquote(p->u.zToken[0]) ){
000945          if( p->u.zToken[0]=='"' ) p->flags |= EP_DblQuoted;
000946          sqlite3Dequote(p->u.zToken);
000947        }
000948  #if SQLITE_MAX_EXPR_DEPTH>0
000949        p->nHeight = 1;
000950  #endif  
000951      }
000952      return p;
000953    }
000954  }
000955  
000956  expr(A) ::= term(A).
000957  expr(A) ::= LP expr(X) RP. {A = X;}
000958  expr(A) ::= id(X).          {A=tokenExpr(pParse,TK_ID,X); /*A-overwrites-X*/}
000959  expr(A) ::= JOIN_KW(X).     {A=tokenExpr(pParse,TK_ID,X); /*A-overwrites-X*/}
000960  expr(A) ::= nm(X) DOT nm(Y). {
000961    Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &X, 1);
000962    Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &Y, 1);
000963    A = sqlite3PExpr(pParse, TK_DOT, temp1, temp2);
000964  }
000965  expr(A) ::= nm(X) DOT nm(Y) DOT nm(Z). {
000966    Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &X, 1);
000967    Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &Y, 1);
000968    Expr *temp3 = sqlite3ExprAlloc(pParse->db, TK_ID, &Z, 1);
000969    Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3);
000970    A = sqlite3PExpr(pParse, TK_DOT, temp1, temp4);
000971  }
000972  term(A) ::= NULL|FLOAT|BLOB(X). {A=tokenExpr(pParse,@X,X); /*A-overwrites-X*/}
000973  term(A) ::= STRING(X).          {A=tokenExpr(pParse,@X,X); /*A-overwrites-X*/}
000974  term(A) ::= INTEGER(X). {
000975    A = sqlite3ExprAlloc(pParse->db, TK_INTEGER, &X, 1);
000976  }
000977  expr(A) ::= VARIABLE(X).     {
000978    if( !(X.z[0]=='#' && sqlite3Isdigit(X.z[1])) ){
000979      u32 n = X.n;
000980      A = tokenExpr(pParse, TK_VARIABLE, X);
000981      sqlite3ExprAssignVarNumber(pParse, A, n);
000982    }else{
000983      /* When doing a nested parse, one can include terms in an expression
000984      ** that look like this:   #1 #2 ...  These terms refer to registers
000985      ** in the virtual machine.  #N is the N-th register. */
000986      Token t = X; /*A-overwrites-X*/
000987      assert( t.n>=2 );
000988      if( pParse->nested==0 ){
000989        sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &t);
000990        A = 0;
000991      }else{
000992        A = sqlite3PExpr(pParse, TK_REGISTER, 0, 0);
000993        if( A ) sqlite3GetInt32(&t.z[1], &A->iTable);
000994      }
000995    }
000996  }
000997  expr(A) ::= expr(A) COLLATE ids(C). {
000998    A = sqlite3ExprAddCollateToken(pParse, A, &C, 1);
000999  }
001000  %ifndef SQLITE_OMIT_CAST
001001  expr(A) ::= CAST LP expr(E) AS typetoken(T) RP. {
001002    A = sqlite3ExprAlloc(pParse->db, TK_CAST, &T, 1);
001003    sqlite3ExprAttachSubtrees(pParse->db, A, E, 0);
001004  }
001005  %endif  SQLITE_OMIT_CAST
001006  expr(A) ::= id(X) LP distinct(D) exprlist(Y) RP. {
001007    if( Y && Y->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
001008      sqlite3ErrorMsg(pParse, "too many arguments on function %T", &X);
001009    }
001010    A = sqlite3ExprFunction(pParse, Y, &X);
001011    if( D==SF_Distinct && A ){
001012      A->flags |= EP_Distinct;
001013    }
001014  }
001015  expr(A) ::= id(X) LP STAR RP. {
001016    A = sqlite3ExprFunction(pParse, 0, &X);
001017  }
001018  term(A) ::= CTIME_KW(OP). {
001019    A = sqlite3ExprFunction(pParse, 0, &OP);
001020  }
001021  
001022  expr(A) ::= LP nexprlist(X) COMMA expr(Y) RP. {
001023    ExprList *pList = sqlite3ExprListAppend(pParse, X, Y);
001024    A = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
001025    if( A ){
001026      A->x.pList = pList;
001027    }else{
001028      sqlite3ExprListDelete(pParse->db, pList);
001029    }
001030  }
001031  
001032  expr(A) ::= expr(A) AND(OP) expr(Y).    {A=sqlite3PExpr(pParse,@OP,A,Y);}
001033  expr(A) ::= expr(A) OR(OP) expr(Y).     {A=sqlite3PExpr(pParse,@OP,A,Y);}
001034  expr(A) ::= expr(A) LT|GT|GE|LE(OP) expr(Y).
001035                                          {A=sqlite3PExpr(pParse,@OP,A,Y);}
001036  expr(A) ::= expr(A) EQ|NE(OP) expr(Y).  {A=sqlite3PExpr(pParse,@OP,A,Y);}
001037  expr(A) ::= expr(A) BITAND|BITOR|LSHIFT|RSHIFT(OP) expr(Y).
001038                                          {A=sqlite3PExpr(pParse,@OP,A,Y);}
001039  expr(A) ::= expr(A) PLUS|MINUS(OP) expr(Y).
001040                                          {A=sqlite3PExpr(pParse,@OP,A,Y);}
001041  expr(A) ::= expr(A) STAR|SLASH|REM(OP) expr(Y).
001042                                          {A=sqlite3PExpr(pParse,@OP,A,Y);}
001043  expr(A) ::= expr(A) CONCAT(OP) expr(Y). {A=sqlite3PExpr(pParse,@OP,A,Y);}
001044  %type likeop {Token}
001045  likeop(A) ::= LIKE_KW|MATCH(A).
001046  likeop(A) ::= NOT LIKE_KW|MATCH(X). {A=X; A.n|=0x80000000; /*A-overwrite-X*/}
001047  expr(A) ::= expr(A) likeop(OP) expr(Y).  [LIKE_KW]  {
001048    ExprList *pList;
001049    int bNot = OP.n & 0x80000000;
001050    OP.n &= 0x7fffffff;
001051    pList = sqlite3ExprListAppend(pParse,0, Y);
001052    pList = sqlite3ExprListAppend(pParse,pList, A);
001053    A = sqlite3ExprFunction(pParse, pList, &OP);
001054    if( bNot ) A = sqlite3PExpr(pParse, TK_NOT, A, 0);
001055    if( A ) A->flags |= EP_InfixFunc;
001056  }
001057  expr(A) ::= expr(A) likeop(OP) expr(Y) ESCAPE expr(E).  [LIKE_KW]  {
001058    ExprList *pList;
001059    int bNot = OP.n & 0x80000000;
001060    OP.n &= 0x7fffffff;
001061    pList = sqlite3ExprListAppend(pParse,0, Y);
001062    pList = sqlite3ExprListAppend(pParse,pList, A);
001063    pList = sqlite3ExprListAppend(pParse,pList, E);
001064    A = sqlite3ExprFunction(pParse, pList, &OP);
001065    if( bNot ) A = sqlite3PExpr(pParse, TK_NOT, A, 0);
001066    if( A ) A->flags |= EP_InfixFunc;
001067  }
001068  
001069  expr(A) ::= expr(A) ISNULL|NOTNULL(E).   {A = sqlite3PExpr(pParse,@E,A,0);}
001070  expr(A) ::= expr(A) NOT NULL.    {A = sqlite3PExpr(pParse,TK_NOTNULL,A,0);}
001071  
001072  %include {
001073    /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
001074    ** unary TK_ISNULL or TK_NOTNULL expression. */
001075    static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
001076      sqlite3 *db = pParse->db;
001077      if( pA && pY && pY->op==TK_NULL ){
001078        pA->op = (u8)op;
001079        sqlite3ExprDelete(db, pA->pRight);
001080        pA->pRight = 0;
001081      }
001082    }
001083  }
001084  
001085  //    expr1 IS expr2
001086  //    expr1 IS NOT expr2
001087  //
001088  // If expr2 is NULL then code as TK_ISNULL or TK_NOTNULL.  If expr2
001089  // is any other expression, code as TK_IS or TK_ISNOT.
001090  // 
001091  expr(A) ::= expr(A) IS expr(Y).     {
001092    A = sqlite3PExpr(pParse,TK_IS,A,Y);
001093    binaryToUnaryIfNull(pParse, Y, A, TK_ISNULL);
001094  }
001095  expr(A) ::= expr(A) IS NOT expr(Y). {
001096    A = sqlite3PExpr(pParse,TK_ISNOT,A,Y);
001097    binaryToUnaryIfNull(pParse, Y, A, TK_NOTNULL);
001098  }
001099  
001100  expr(A) ::= NOT(B) expr(X).  
001101                {A = sqlite3PExpr(pParse, @B, X, 0);/*A-overwrites-B*/}
001102  expr(A) ::= BITNOT(B) expr(X).
001103                {A = sqlite3PExpr(pParse, @B, X, 0);/*A-overwrites-B*/}
001104  expr(A) ::= MINUS expr(X). [BITNOT]
001105                {A = sqlite3PExpr(pParse, TK_UMINUS, X, 0);}
001106  expr(A) ::= PLUS expr(X). [BITNOT]
001107                {A = sqlite3PExpr(pParse, TK_UPLUS, X, 0);}
001108  
001109  %type between_op {int}
001110  between_op(A) ::= BETWEEN.     {A = 0;}
001111  between_op(A) ::= NOT BETWEEN. {A = 1;}
001112  expr(A) ::= expr(A) between_op(N) expr(X) AND expr(Y). [BETWEEN] {
001113    ExprList *pList = sqlite3ExprListAppend(pParse,0, X);
001114    pList = sqlite3ExprListAppend(pParse,pList, Y);
001115    A = sqlite3PExpr(pParse, TK_BETWEEN, A, 0);
001116    if( A ){
001117      A->x.pList = pList;
001118    }else{
001119      sqlite3ExprListDelete(pParse->db, pList);
001120    } 
001121    if( N ) A = sqlite3PExpr(pParse, TK_NOT, A, 0);
001122  }
001123  %ifndef SQLITE_OMIT_SUBQUERY
001124    %type in_op {int}
001125    in_op(A) ::= IN.      {A = 0;}
001126    in_op(A) ::= NOT IN.  {A = 1;}
001127    expr(A) ::= expr(A) in_op(N) LP exprlist(Y) RP. [IN] {
001128      if( Y==0 ){
001129        /* Expressions of the form
001130        **
001131        **      expr1 IN ()
001132        **      expr1 NOT IN ()
001133        **
001134        ** simplify to constants 0 (false) and 1 (true), respectively,
001135        ** regardless of the value of expr1.
001136        */
001137        sqlite3ExprDelete(pParse->db, A);
001138        A = sqlite3ExprAlloc(pParse->db, TK_INTEGER,&sqlite3IntTokens[N],1);
001139      }else if( Y->nExpr==1 ){
001140        /* Expressions of the form:
001141        **
001142        **      expr1 IN (?1)
001143        **      expr1 NOT IN (?2)
001144        **
001145        ** with exactly one value on the RHS can be simplified to something
001146        ** like this:
001147        **
001148        **      expr1 == ?1
001149        **      expr1 <> ?2
001150        **
001151        ** But, the RHS of the == or <> is marked with the EP_Generic flag
001152        ** so that it may not contribute to the computation of comparison
001153        ** affinity or the collating sequence to use for comparison.  Otherwise,
001154        ** the semantics would be subtly different from IN or NOT IN.
001155        */
001156        Expr *pRHS = Y->a[0].pExpr;
001157        Y->a[0].pExpr = 0;
001158        sqlite3ExprListDelete(pParse->db, Y);
001159        /* pRHS cannot be NULL because a malloc error would have been detected
001160        ** before now and control would have never reached this point */
001161        if( ALWAYS(pRHS) ){
001162          pRHS->flags &= ~EP_Collate;
001163          pRHS->flags |= EP_Generic;
001164        }
001165        A = sqlite3PExpr(pParse, N ? TK_NE : TK_EQ, A, pRHS);
001166      }else{
001167        A = sqlite3PExpr(pParse, TK_IN, A, 0);
001168        if( A ){
001169          A->x.pList = Y;
001170          sqlite3ExprSetHeightAndFlags(pParse, A);
001171        }else{
001172          sqlite3ExprListDelete(pParse->db, Y);
001173        }
001174        if( N ) A = sqlite3PExpr(pParse, TK_NOT, A, 0);
001175      }
001176    }
001177    expr(A) ::= LP select(X) RP. {
001178      A = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
001179      sqlite3PExprAddSelect(pParse, A, X);
001180    }
001181    expr(A) ::= expr(A) in_op(N) LP select(Y) RP.  [IN] {
001182      A = sqlite3PExpr(pParse, TK_IN, A, 0);
001183      sqlite3PExprAddSelect(pParse, A, Y);
001184      if( N ) A = sqlite3PExpr(pParse, TK_NOT, A, 0);
001185    }
001186    expr(A) ::= expr(A) in_op(N) nm(Y) dbnm(Z) paren_exprlist(E). [IN] {
001187      SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&Y,&Z);
001188      Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0);
001189      if( E )  sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, E);
001190      A = sqlite3PExpr(pParse, TK_IN, A, 0);
001191      sqlite3PExprAddSelect(pParse, A, pSelect);
001192      if( N ) A = sqlite3PExpr(pParse, TK_NOT, A, 0);
001193    }
001194    expr(A) ::= EXISTS LP select(Y) RP. {
001195      Expr *p;
001196      p = A = sqlite3PExpr(pParse, TK_EXISTS, 0, 0);
001197      sqlite3PExprAddSelect(pParse, p, Y);
001198    }
001199  %endif SQLITE_OMIT_SUBQUERY
001200  
001201  /* CASE expressions */
001202  expr(A) ::= CASE case_operand(X) case_exprlist(Y) case_else(Z) END. {
001203    A = sqlite3PExpr(pParse, TK_CASE, X, 0);
001204    if( A ){
001205      A->x.pList = Z ? sqlite3ExprListAppend(pParse,Y,Z) : Y;
001206      sqlite3ExprSetHeightAndFlags(pParse, A);
001207    }else{
001208      sqlite3ExprListDelete(pParse->db, Y);
001209      sqlite3ExprDelete(pParse->db, Z);
001210    }
001211  }
001212  %type case_exprlist {ExprList*}
001213  %destructor case_exprlist {sqlite3ExprListDelete(pParse->db, $$);}
001214  case_exprlist(A) ::= case_exprlist(A) WHEN expr(Y) THEN expr(Z). {
001215    A = sqlite3ExprListAppend(pParse,A, Y);
001216    A = sqlite3ExprListAppend(pParse,A, Z);
001217  }
001218  case_exprlist(A) ::= WHEN expr(Y) THEN expr(Z). {
001219    A = sqlite3ExprListAppend(pParse,0, Y);
001220    A = sqlite3ExprListAppend(pParse,A, Z);
001221  }
001222  %type case_else {Expr*}
001223  %destructor case_else {sqlite3ExprDelete(pParse->db, $$);}
001224  case_else(A) ::=  ELSE expr(X).         {A = X;}
001225  case_else(A) ::=  .                     {A = 0;} 
001226  %type case_operand {Expr*}
001227  %destructor case_operand {sqlite3ExprDelete(pParse->db, $$);}
001228  case_operand(A) ::= expr(X).            {A = X; /*A-overwrites-X*/} 
001229  case_operand(A) ::= .                   {A = 0;} 
001230  
001231  %type exprlist {ExprList*}
001232  %destructor exprlist {sqlite3ExprListDelete(pParse->db, $$);}
001233  %type nexprlist {ExprList*}
001234  %destructor nexprlist {sqlite3ExprListDelete(pParse->db, $$);}
001235  
001236  exprlist(A) ::= nexprlist(A).
001237  exprlist(A) ::= .                            {A = 0;}
001238  nexprlist(A) ::= nexprlist(A) COMMA expr(Y).
001239      {A = sqlite3ExprListAppend(pParse,A,Y);}
001240  nexprlist(A) ::= expr(Y).
001241      {A = sqlite3ExprListAppend(pParse,0,Y); /*A-overwrites-Y*/}
001242  
001243  %ifndef SQLITE_OMIT_SUBQUERY
001244  /* A paren_exprlist is an optional expression list contained inside
001245  ** of parenthesis */
001246  %type paren_exprlist {ExprList*}
001247  %destructor paren_exprlist {sqlite3ExprListDelete(pParse->db, $$);}
001248  paren_exprlist(A) ::= .   {A = 0;}
001249  paren_exprlist(A) ::= LP exprlist(X) RP.  {A = X;}
001250  %endif SQLITE_OMIT_SUBQUERY
001251  
001252  
001253  ///////////////////////////// The CREATE INDEX command ///////////////////////
001254  //
001255  cmd ::= createkw(S) uniqueflag(U) INDEX ifnotexists(NE) nm(X) dbnm(D)
001256          ON nm(Y) LP sortlist(Z) RP where_opt(W). {
001257    sqlite3CreateIndex(pParse, &X, &D, 
001258                       sqlite3SrcListAppend(pParse->db,0,&Y,0), Z, U,
001259                        &S, W, SQLITE_SO_ASC, NE, SQLITE_IDXTYPE_APPDEF);
001260  }
001261  
001262  %type uniqueflag {int}
001263  uniqueflag(A) ::= UNIQUE.  {A = OE_Abort;}
001264  uniqueflag(A) ::= .        {A = OE_None;}
001265  
001266  
001267  // The eidlist non-terminal (Expression Id List) generates an ExprList
001268  // from a list of identifiers.  The identifier names are in ExprList.a[].zName.
001269  // This list is stored in an ExprList rather than an IdList so that it
001270  // can be easily sent to sqlite3ColumnsExprList().
001271  //
001272  // eidlist is grouped with CREATE INDEX because it used to be the non-terminal
001273  // used for the arguments to an index.  That is just an historical accident.
001274  //
001275  // IMPORTANT COMPATIBILITY NOTE:  Some prior versions of SQLite accepted
001276  // COLLATE clauses and ASC or DESC keywords on ID lists in inappropriate
001277  // places - places that might have been stored in the sqlite_master schema.
001278  // Those extra features were ignored.  But because they might be in some
001279  // (busted) old databases, we need to continue parsing them when loading
001280  // historical schemas.
001281  //
001282  %type eidlist {ExprList*}
001283  %destructor eidlist {sqlite3ExprListDelete(pParse->db, $$);}
001284  %type eidlist_opt {ExprList*}
001285  %destructor eidlist_opt {sqlite3ExprListDelete(pParse->db, $$);}
001286  
001287  %include {
001288    /* Add a single new term to an ExprList that is used to store a
001289    ** list of identifiers.  Report an error if the ID list contains
001290    ** a COLLATE clause or an ASC or DESC keyword, except ignore the
001291    ** error while parsing a legacy schema.
001292    */
001293    static ExprList *parserAddExprIdListTerm(
001294      Parse *pParse,
001295      ExprList *pPrior,
001296      Token *pIdToken,
001297      int hasCollate,
001298      int sortOrder
001299    ){
001300      ExprList *p = sqlite3ExprListAppend(pParse, pPrior, 0);
001301      if( (hasCollate || sortOrder!=SQLITE_SO_UNDEFINED)
001302          && pParse->db->init.busy==0
001303      ){
001304        sqlite3ErrorMsg(pParse, "syntax error after column name \"%.*s\"",
001305                           pIdToken->n, pIdToken->z);
001306      }
001307      sqlite3ExprListSetName(pParse, p, pIdToken, 1);
001308      return p;
001309    }
001310  } // end %include
001311  
001312  eidlist_opt(A) ::= .                         {A = 0;}
001313  eidlist_opt(A) ::= LP eidlist(X) RP.         {A = X;}
001314  eidlist(A) ::= eidlist(A) COMMA nm(Y) collate(C) sortorder(Z).  {
001315    A = parserAddExprIdListTerm(pParse, A, &Y, C, Z);
001316  }
001317  eidlist(A) ::= nm(Y) collate(C) sortorder(Z). {
001318    A = parserAddExprIdListTerm(pParse, 0, &Y, C, Z); /*A-overwrites-Y*/
001319  }
001320  
001321  %type collate {int}
001322  collate(C) ::= .              {C = 0;}
001323  collate(C) ::= COLLATE ids.   {C = 1;}
001324  
001325  
001326  ///////////////////////////// The DROP INDEX command /////////////////////////
001327  //
001328  cmd ::= DROP INDEX ifexists(E) fullname(X).   {sqlite3DropIndex(pParse, X, E);}
001329  
001330  ///////////////////////////// The VACUUM command /////////////////////////////
001331  //
001332  %ifndef SQLITE_OMIT_VACUUM
001333  %ifndef SQLITE_OMIT_ATTACH
001334  cmd ::= VACUUM.                {sqlite3Vacuum(pParse,0);}
001335  cmd ::= VACUUM nm(X).          {sqlite3Vacuum(pParse,&X);}
001336  %endif  SQLITE_OMIT_ATTACH
001337  %endif  SQLITE_OMIT_VACUUM
001338  
001339  ///////////////////////////// The PRAGMA command /////////////////////////////
001340  //
001341  %ifndef SQLITE_OMIT_PRAGMA
001342  cmd ::= PRAGMA nm(X) dbnm(Z).                {sqlite3Pragma(pParse,&X,&Z,0,0);}
001343  cmd ::= PRAGMA nm(X) dbnm(Z) EQ nmnum(Y).    {sqlite3Pragma(pParse,&X,&Z,&Y,0);}
001344  cmd ::= PRAGMA nm(X) dbnm(Z) LP nmnum(Y) RP. {sqlite3Pragma(pParse,&X,&Z,&Y,0);}
001345  cmd ::= PRAGMA nm(X) dbnm(Z) EQ minus_num(Y). 
001346                                               {sqlite3Pragma(pParse,&X,&Z,&Y,1);}
001347  cmd ::= PRAGMA nm(X) dbnm(Z) LP minus_num(Y) RP.
001348                                               {sqlite3Pragma(pParse,&X,&Z,&Y,1);}
001349  
001350  nmnum(A) ::= plus_num(A).
001351  nmnum(A) ::= nm(A).
001352  nmnum(A) ::= ON(A).
001353  nmnum(A) ::= DELETE(A).
001354  nmnum(A) ::= DEFAULT(A).
001355  %endif SQLITE_OMIT_PRAGMA
001356  %token_class number INTEGER|FLOAT.
001357  plus_num(A) ::= PLUS number(X).       {A = X;}
001358  plus_num(A) ::= number(A).
001359  minus_num(A) ::= MINUS number(X).     {A = X;}
001360  //////////////////////////// The CREATE TRIGGER command /////////////////////
001361  
001362  %ifndef SQLITE_OMIT_TRIGGER
001363  
001364  cmd ::= createkw trigger_decl(A) BEGIN trigger_cmd_list(S) END(Z). {
001365    Token all;
001366    all.z = A.z;
001367    all.n = (int)(Z.z - A.z) + Z.n;
001368    sqlite3FinishTrigger(pParse, S, &all);
001369  }
001370  
001371  trigger_decl(A) ::= temp(T) TRIGGER ifnotexists(NOERR) nm(B) dbnm(Z) 
001372                      trigger_time(C) trigger_event(D)
001373                      ON fullname(E) foreach_clause when_clause(G). {
001374    sqlite3BeginTrigger(pParse, &B, &Z, C, D.a, D.b, E, G, T, NOERR);
001375    A = (Z.n==0?B:Z); /*A-overwrites-T*/
001376  }
001377  
001378  %type trigger_time {int}
001379  trigger_time(A) ::= BEFORE|AFTER(X).  { A = @X; /*A-overwrites-X*/ }
001380  trigger_time(A) ::= INSTEAD OF.  { A = TK_INSTEAD;}
001381  trigger_time(A) ::= .            { A = TK_BEFORE; }
001382  
001383  %type trigger_event {struct TrigEvent}
001384  %destructor trigger_event {sqlite3IdListDelete(pParse->db, $$.b);}
001385  trigger_event(A) ::= DELETE|INSERT(X).   {A.a = @X; /*A-overwrites-X*/ A.b = 0;}
001386  trigger_event(A) ::= UPDATE(X).          {A.a = @X; /*A-overwrites-X*/ A.b = 0;}
001387  trigger_event(A) ::= UPDATE OF idlist(X).{A.a = TK_UPDATE; A.b = X;}
001388  
001389  foreach_clause ::= .
001390  foreach_clause ::= FOR EACH ROW.
001391  
001392  %type when_clause {Expr*}
001393  %destructor when_clause {sqlite3ExprDelete(pParse->db, $$);}
001394  when_clause(A) ::= .             { A = 0; }
001395  when_clause(A) ::= WHEN expr(X). { A = X; }
001396  
001397  %type trigger_cmd_list {TriggerStep*}
001398  %destructor trigger_cmd_list {sqlite3DeleteTriggerStep(pParse->db, $$);}
001399  trigger_cmd_list(A) ::= trigger_cmd_list(A) trigger_cmd(X) SEMI. {
001400    assert( A!=0 );
001401    A->pLast->pNext = X;
001402    A->pLast = X;
001403  }
001404  trigger_cmd_list(A) ::= trigger_cmd(A) SEMI. { 
001405    assert( A!=0 );
001406    A->pLast = A;
001407  }
001408  
001409  // Disallow qualified table names on INSERT, UPDATE, and DELETE statements
001410  // within a trigger.  The table to INSERT, UPDATE, or DELETE is always in 
001411  // the same database as the table that the trigger fires on.
001412  //
001413  %type trnm {Token}
001414  trnm(A) ::= nm(A).
001415  trnm(A) ::= nm DOT nm(X). {
001416    A = X;
001417    sqlite3ErrorMsg(pParse, 
001418          "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
001419          "statements within triggers");
001420  }
001421  
001422  // Disallow the INDEX BY and NOT INDEXED clauses on UPDATE and DELETE
001423  // statements within triggers.  We make a specific error message for this
001424  // since it is an exception to the default grammar rules.
001425  //
001426  tridxby ::= .
001427  tridxby ::= INDEXED BY nm. {
001428    sqlite3ErrorMsg(pParse,
001429          "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
001430          "within triggers");
001431  }
001432  tridxby ::= NOT INDEXED. {
001433    sqlite3ErrorMsg(pParse,
001434          "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
001435          "within triggers");
001436  }
001437  
001438  
001439  
001440  %type trigger_cmd {TriggerStep*}
001441  %destructor trigger_cmd {sqlite3DeleteTriggerStep(pParse->db, $$);}
001442  // UPDATE 
001443  trigger_cmd(A) ::=
001444     UPDATE(B) orconf(R) trnm(X) tridxby SET setlist(Y) where_opt(Z) scanpt(E).  
001445     {A = sqlite3TriggerUpdateStep(pParse->db, &X, Y, Z, R, B.z, E);}
001446  
001447  // INSERT
001448  trigger_cmd(A) ::= scanpt(B) insert_cmd(R) INTO
001449                        trnm(X) idlist_opt(F) select(S) upsert(U) scanpt(Z). {
001450     A = sqlite3TriggerInsertStep(pParse->db,&X,F,S,R,U,B,Z);/*A-overwrites-R*/
001451  }
001452  // DELETE
001453  trigger_cmd(A) ::= DELETE(B) FROM trnm(X) tridxby where_opt(Y) scanpt(E).
001454     {A = sqlite3TriggerDeleteStep(pParse->db, &X, Y, B.z, E);}
001455  
001456  // SELECT
001457  trigger_cmd(A) ::= scanpt(B) select(X) scanpt(E).
001458     {A = sqlite3TriggerSelectStep(pParse->db, X, B, E); /*A-overwrites-X*/}
001459  
001460  // The special RAISE expression that may occur in trigger programs
001461  expr(A) ::= RAISE LP IGNORE RP.  {
001462    A = sqlite3PExpr(pParse, TK_RAISE, 0, 0); 
001463    if( A ){
001464      A->affinity = OE_Ignore;
001465    }
001466  }
001467  expr(A) ::= RAISE LP raisetype(T) COMMA nm(Z) RP.  {
001468    A = sqlite3ExprAlloc(pParse->db, TK_RAISE, &Z, 1); 
001469    if( A ) {
001470      A->affinity = (char)T;
001471    }
001472  }
001473  %endif  !SQLITE_OMIT_TRIGGER
001474  
001475  %type raisetype {int}
001476  raisetype(A) ::= ROLLBACK.  {A = OE_Rollback;}
001477  raisetype(A) ::= ABORT.     {A = OE_Abort;}
001478  raisetype(A) ::= FAIL.      {A = OE_Fail;}
001479  
001480  
001481  ////////////////////////  DROP TRIGGER statement //////////////////////////////
001482  %ifndef SQLITE_OMIT_TRIGGER
001483  cmd ::= DROP TRIGGER ifexists(NOERR) fullname(X). {
001484    sqlite3DropTrigger(pParse,X,NOERR);
001485  }
001486  %endif  !SQLITE_OMIT_TRIGGER
001487  
001488  //////////////////////// ATTACH DATABASE file AS name /////////////////////////
001489  %ifndef SQLITE_OMIT_ATTACH
001490  cmd ::= ATTACH database_kw_opt expr(F) AS expr(D) key_opt(K). {
001491    sqlite3Attach(pParse, F, D, K);
001492  }
001493  cmd ::= DETACH database_kw_opt expr(D). {
001494    sqlite3Detach(pParse, D);
001495  }
001496  
001497  %type key_opt {Expr*}
001498  %destructor key_opt {sqlite3ExprDelete(pParse->db, $$);}
001499  key_opt(A) ::= .                     { A = 0; }
001500  key_opt(A) ::= KEY expr(X).          { A = X; }
001501  
001502  database_kw_opt ::= DATABASE.
001503  database_kw_opt ::= .
001504  %endif SQLITE_OMIT_ATTACH
001505  
001506  ////////////////////////// REINDEX collation //////////////////////////////////
001507  %ifndef SQLITE_OMIT_REINDEX
001508  cmd ::= REINDEX.                {sqlite3Reindex(pParse, 0, 0);}
001509  cmd ::= REINDEX nm(X) dbnm(Y).  {sqlite3Reindex(pParse, &X, &Y);}
001510  %endif  SQLITE_OMIT_REINDEX
001511  
001512  /////////////////////////////////// ANALYZE ///////////////////////////////////
001513  %ifndef SQLITE_OMIT_ANALYZE
001514  cmd ::= ANALYZE.                {sqlite3Analyze(pParse, 0, 0);}
001515  cmd ::= ANALYZE nm(X) dbnm(Y).  {sqlite3Analyze(pParse, &X, &Y);}
001516  %endif
001517  
001518  //////////////////////// ALTER TABLE table ... ////////////////////////////////
001519  %ifndef SQLITE_OMIT_ALTERTABLE
001520  cmd ::= ALTER TABLE fullname(X) RENAME TO nm(Z). {
001521    sqlite3AlterRenameTable(pParse,X,&Z);
001522  }
001523  cmd ::= ALTER TABLE add_column_fullname
001524          ADD kwcolumn_opt columnname(Y) carglist. {
001525    Y.n = (int)(pParse->sLastToken.z-Y.z) + pParse->sLastToken.n;
001526    sqlite3AlterFinishAddColumn(pParse, &Y);
001527  }
001528  add_column_fullname ::= fullname(X). {
001529    disableLookaside(pParse);
001530    sqlite3AlterBeginAddColumn(pParse, X);
001531  }
001532  kwcolumn_opt ::= .
001533  kwcolumn_opt ::= COLUMNKW.
001534  %endif  SQLITE_OMIT_ALTERTABLE
001535  
001536  //////////////////////// CREATE VIRTUAL TABLE ... /////////////////////////////
001537  %ifndef SQLITE_OMIT_VIRTUALTABLE
001538  cmd ::= create_vtab.                       {sqlite3VtabFinishParse(pParse,0);}
001539  cmd ::= create_vtab LP vtabarglist RP(X).  {sqlite3VtabFinishParse(pParse,&X);}
001540  create_vtab ::= createkw VIRTUAL TABLE ifnotexists(E)
001541                  nm(X) dbnm(Y) USING nm(Z). {
001542      sqlite3VtabBeginParse(pParse, &X, &Y, &Z, E);
001543  }
001544  vtabarglist ::= vtabarg.
001545  vtabarglist ::= vtabarglist COMMA vtabarg.
001546  vtabarg ::= .                       {sqlite3VtabArgInit(pParse);}
001547  vtabarg ::= vtabarg vtabargtoken.
001548  vtabargtoken ::= ANY(X).            {sqlite3VtabArgExtend(pParse,&X);}
001549  vtabargtoken ::= lp anylist RP(X).  {sqlite3VtabArgExtend(pParse,&X);}
001550  lp ::= LP(X).                       {sqlite3VtabArgExtend(pParse,&X);}
001551  anylist ::= .
001552  anylist ::= anylist LP anylist RP.
001553  anylist ::= anylist ANY.
001554  %endif  SQLITE_OMIT_VIRTUALTABLE
001555  
001556  
001557  //////////////////////// COMMON TABLE EXPRESSIONS ////////////////////////////
001558  %type wqlist {With*}
001559  %destructor wqlist {sqlite3WithDelete(pParse->db, $$);}
001560  
001561  with ::= .
001562  %ifndef SQLITE_OMIT_CTE
001563  with ::= WITH wqlist(W).              { sqlite3WithPush(pParse, W, 1); }
001564  with ::= WITH RECURSIVE wqlist(W).    { sqlite3WithPush(pParse, W, 1); }
001565  
001566  wqlist(A) ::= nm(X) eidlist_opt(Y) AS LP select(Z) RP. {
001567    A = sqlite3WithAdd(pParse, 0, &X, Y, Z); /*A-overwrites-X*/
001568  }
001569  wqlist(A) ::= wqlist(A) COMMA nm(X) eidlist_opt(Y) AS LP select(Z) RP. {
001570    A = sqlite3WithAdd(pParse, A, &X, Y, Z);
001571  }
001572  %endif  SQLITE_OMIT_CTE