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