xref: /sqlite-3.40.0/src/parse.y (revision 37874d7d)
1 /*
2 ** 2001 September 15
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 ** This file contains SQLite's grammar for SQL.  Process this file
13 ** using the lemon parser generator to generate C code that runs
14 ** the parser.  Lemon will also generate a header file containing
15 ** numeric codes for all of the tokens.
16 */
17 
18 // All token codes are small integers with #defines that begin with "TK_"
19 %token_prefix TK_
20 
21 // The type of the data attached to each token is Token.  This is also the
22 // default type for non-terminals.
23 //
24 %token_type {Token}
25 %default_type {Token}
26 
27 // An extra argument to the constructor for the parser, which is available
28 // to all actions.
29 %extra_context {Parse *pParse}
30 
31 // This code runs whenever there is a syntax error
32 //
33 %syntax_error {
34   UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
35   if( TOKEN.z[0] ){
36     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
37   }else{
38     sqlite3ErrorMsg(pParse, "incomplete input");
39   }
40 }
41 %stack_overflow {
42   sqlite3ErrorMsg(pParse, "parser stack overflow");
43 }
44 
45 // The name of the generated procedure that implements the parser
46 // is as follows:
47 %name sqlite3Parser
48 
49 // The following text is included near the beginning of the C source
50 // code file that implements the parser.
51 //
52 %include {
53 #include "sqliteInt.h"
54 
55 /*
56 ** Disable all error recovery processing in the parser push-down
57 ** automaton.
58 */
59 #define YYNOERRORRECOVERY 1
60 
61 /*
62 ** Make yytestcase() the same as testcase()
63 */
64 #define yytestcase(X) testcase(X)
65 
66 /*
67 ** Indicate that sqlite3ParserFree() will never be called with a null
68 ** pointer.
69 */
70 #define YYPARSEFREENEVERNULL 1
71 
72 /*
73 ** In the amalgamation, the parse.c file generated by lemon and the
74 ** tokenize.c file are concatenated.  In that case, sqlite3RunParser()
75 ** has access to the the size of the yyParser object and so the parser
76 ** engine can be allocated from stack.  In that case, only the
77 ** sqlite3ParserInit() and sqlite3ParserFinalize() routines are invoked
78 ** and the sqlite3ParserAlloc() and sqlite3ParserFree() routines can be
79 ** omitted.
80 */
81 #ifdef SQLITE_AMALGAMATION
82 # define sqlite3Parser_ENGINEALWAYSONSTACK 1
83 #endif
84 
85 /*
86 ** Alternative datatype for the argument to the malloc() routine passed
87 ** into sqlite3ParserAlloc().  The default is size_t.
88 */
89 #define YYMALLOCARGTYPE  u64
90 
91 /*
92 ** An instance of the following structure describes the event of a
93 ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
94 ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
95 **
96 **      UPDATE ON (a,b,c)
97 **
98 ** Then the "b" IdList records the list "a,b,c".
99 */
100 struct TrigEvent { int a; IdList * b; };
101 
102 struct FrameBound     { int eType; Expr *pExpr; };
103 
104 /*
105 ** Disable lookaside memory allocation for objects that might be
106 ** shared across database connections.
107 */
108 static void disableLookaside(Parse *pParse){
109   pParse->disableLookaside++;
110   pParse->db->lookaside.bDisable++;
111 }
112 
113 } // end %include
114 
115 // Input is a single SQL command
116 input ::= cmdlist.
117 cmdlist ::= cmdlist ecmd.
118 cmdlist ::= ecmd.
119 ecmd ::= SEMI.
120 ecmd ::= cmdx SEMI.
121 %ifndef SQLITE_OMIT_EXPLAIN
122 ecmd ::= explain cmdx.
123 explain ::= EXPLAIN.              { pParse->explain = 1; }
124 explain ::= EXPLAIN QUERY PLAN.   { pParse->explain = 2; }
125 %endif  SQLITE_OMIT_EXPLAIN
126 cmdx ::= cmd.           { sqlite3FinishCoding(pParse); }
127 
128 ///////////////////// Begin and end transactions. ////////////////////////////
129 //
130 
131 cmd ::= BEGIN transtype(Y) trans_opt.  {sqlite3BeginTransaction(pParse, Y);}
132 trans_opt ::= .
133 trans_opt ::= TRANSACTION.
134 trans_opt ::= TRANSACTION nm.
135 %type transtype {int}
136 transtype(A) ::= .             {A = TK_DEFERRED;}
137 transtype(A) ::= DEFERRED(X).  {A = @X; /*A-overwrites-X*/}
138 transtype(A) ::= IMMEDIATE(X). {A = @X; /*A-overwrites-X*/}
139 transtype(A) ::= EXCLUSIVE(X). {A = @X; /*A-overwrites-X*/}
140 cmd ::= COMMIT|END(X) trans_opt.   {sqlite3EndTransaction(pParse,@X);}
141 cmd ::= ROLLBACK(X) trans_opt.     {sqlite3EndTransaction(pParse,@X);}
142 
143 savepoint_opt ::= SAVEPOINT.
144 savepoint_opt ::= .
145 cmd ::= SAVEPOINT nm(X). {
146   sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &X);
147 }
148 cmd ::= RELEASE savepoint_opt nm(X). {
149   sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &X);
150 }
151 cmd ::= ROLLBACK trans_opt TO savepoint_opt nm(X). {
152   sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &X);
153 }
154 
155 ///////////////////// The CREATE TABLE statement ////////////////////////////
156 //
157 cmd ::= create_table create_table_args.
158 create_table ::= createkw temp(T) TABLE ifnotexists(E) nm(Y) dbnm(Z). {
159    sqlite3StartTable(pParse,&Y,&Z,T,0,0,E);
160 }
161 createkw(A) ::= CREATE(A).  {disableLookaside(pParse);}
162 
163 %type ifnotexists {int}
164 ifnotexists(A) ::= .              {A = 0;}
165 ifnotexists(A) ::= IF NOT EXISTS. {A = 1;}
166 %type temp {int}
167 %ifndef SQLITE_OMIT_TEMPDB
168 temp(A) ::= TEMP.  {A = 1;}
169 %endif  SQLITE_OMIT_TEMPDB
170 temp(A) ::= .      {A = 0;}
171 create_table_args ::= LP columnlist conslist_opt(X) RP(E) table_options(F). {
172   sqlite3EndTable(pParse,&X,&E,F,0);
173 }
174 create_table_args ::= AS select(S). {
175   sqlite3EndTable(pParse,0,0,0,S);
176   sqlite3SelectDelete(pParse->db, S);
177 }
178 %type table_options {int}
179 table_options(A) ::= .    {A = 0;}
180 table_options(A) ::= WITHOUT nm(X). {
181   if( X.n==5 && sqlite3_strnicmp(X.z,"rowid",5)==0 ){
182     A = TF_WithoutRowid | TF_NoVisibleRowid;
183   }else{
184     A = 0;
185     sqlite3ErrorMsg(pParse, "unknown table option: %.*s", X.n, X.z);
186   }
187 }
188 columnlist ::= columnlist COMMA columnname carglist.
189 columnlist ::= columnname carglist.
190 columnname(A) ::= nm(A) typetoken(Y). {sqlite3AddColumn(pParse,&A,&Y);}
191 
192 // Declare some tokens early in order to influence their values, to
193 // improve performance and reduce the executable size.  The goal here is
194 // to get the "jump" operations in ISNULL through ESCAPE to have numeric
195 // values that are early enough so that all jump operations are clustered
196 // at the beginning.
197 //
198 %token ABORT ACTION AFTER ANALYZE ASC ATTACH BEFORE BEGIN BY CASCADE CAST.
199 %token CONFLICT DATABASE DEFERRED DESC DETACH EACH END EXCLUSIVE EXPLAIN FAIL.
200 %token OR AND NOT IS MATCH LIKE_KW BETWEEN IN ISNULL NOTNULL NE EQ.
201 %token GT LE LT GE ESCAPE.
202 
203 // The following directive causes tokens ABORT, AFTER, ASC, etc. to
204 // fallback to ID if they will not parse as their original value.
205 // This obviates the need for the "id" nonterminal.
206 //
207 %fallback ID
208   ABORT ACTION AFTER ANALYZE ASC ATTACH BEFORE BEGIN BY CASCADE CAST COLUMNKW
209   CONFLICT DATABASE DEFERRED DESC DETACH DO
210   EACH END EXCLUSIVE EXPLAIN FAIL FOR
211   IGNORE IMMEDIATE INITIALLY INSTEAD LIKE_KW MATCH NO PLAN
212   QUERY KEY OF OFFSET PRAGMA RAISE RECURSIVE RELEASE REPLACE RESTRICT ROW ROWS
213   ROLLBACK SAVEPOINT TEMP TRIGGER VACUUM VIEW VIRTUAL WITH WITHOUT
214   NULLS FIRST LAST
215 %ifdef SQLITE_OMIT_COMPOUND_SELECT
216   EXCEPT INTERSECT UNION
217 %endif SQLITE_OMIT_COMPOUND_SELECT
218 %ifndef SQLITE_OMIT_WINDOWFUNC
219   CURRENT FOLLOWING PARTITION PRECEDING RANGE UNBOUNDED
220   EXCLUDE GROUPS OTHERS TIES
221 %endif SQLITE_OMIT_WINDOWFUNC
222   REINDEX RENAME CTIME_KW IF
223   .
224 %wildcard ANY.
225 
226 // Define operator precedence early so that this is the first occurrence
227 // of the operator tokens in the grammer.  Keeping the operators together
228 // causes them to be assigned integer values that are close together,
229 // which keeps parser tables smaller.
230 //
231 // The token values assigned to these symbols is determined by the order
232 // in which lemon first sees them.  It must be the case that ISNULL/NOTNULL,
233 // NE/EQ, GT/LE, and GE/LT are separated by only a single value.  See
234 // the sqlite3ExprIfFalse() routine for additional information on this
235 // constraint.
236 //
237 %left OR.
238 %left AND.
239 %right NOT.
240 %left IS MATCH LIKE_KW BETWEEN IN ISNULL NOTNULL NE EQ.
241 %left GT LE LT GE.
242 %right ESCAPE.
243 %left BITAND BITOR LSHIFT RSHIFT.
244 %left PLUS MINUS.
245 %left STAR SLASH REM.
246 %left CONCAT.
247 %left COLLATE.
248 %right BITNOT.
249 %nonassoc ON.
250 
251 // An IDENTIFIER can be a generic identifier, or one of several
252 // keywords.  Any non-standard keyword can also be an identifier.
253 //
254 %token_class id  ID|INDEXED.
255 
256 
257 // And "ids" is an identifer-or-string.
258 //
259 %token_class ids  ID|STRING.
260 
261 // The name of a column or table can be any of the following:
262 //
263 %type nm {Token}
264 nm(A) ::= id(A).
265 nm(A) ::= STRING(A).
266 nm(A) ::= JOIN_KW(A).
267 
268 // A typetoken is really zero or more tokens that form a type name such
269 // as can be found after the column name in a CREATE TABLE statement.
270 // Multiple tokens are concatenated to form the value of the typetoken.
271 //
272 %type typetoken {Token}
273 typetoken(A) ::= .   {A.n = 0; A.z = 0;}
274 typetoken(A) ::= typename(A).
275 typetoken(A) ::= typename(A) LP signed RP(Y). {
276   A.n = (int)(&Y.z[Y.n] - A.z);
277 }
278 typetoken(A) ::= typename(A) LP signed COMMA signed RP(Y). {
279   A.n = (int)(&Y.z[Y.n] - A.z);
280 }
281 %type typename {Token}
282 typename(A) ::= ids(A).
283 typename(A) ::= typename(A) ids(Y). {A.n=Y.n+(int)(Y.z-A.z);}
284 signed ::= plus_num.
285 signed ::= minus_num.
286 
287 // The scanpt non-terminal takes a value which is a pointer to the
288 // input text just past the last token that has been shifted into
289 // the parser.  By surrounding some phrase in the grammar with two
290 // scanpt non-terminals, we can capture the input text for that phrase.
291 // For example:
292 //
293 //      something ::= .... scanpt(A) phrase scanpt(Z).
294 //
295 // The text that is parsed as "phrase" is a string starting at A
296 // and containing (int)(Z-A) characters.  There might be some extra
297 // whitespace on either end of the text, but that can be removed in
298 // post-processing, if needed.
299 //
300 %type scanpt {const char*}
301 scanpt(A) ::= . {
302   assert( yyLookahead!=YYNOCODE );
303   A = yyLookaheadToken.z;
304 }
305 scantok(A) ::= . {
306   assert( yyLookahead!=YYNOCODE );
307   A = yyLookaheadToken;
308 }
309 
310 // "carglist" is a list of additional constraints that come after the
311 // column name and column type in a CREATE TABLE statement.
312 //
313 carglist ::= carglist ccons.
314 carglist ::= .
315 ccons ::= CONSTRAINT nm(X).           {pParse->constraintName = X;}
316 ccons ::= DEFAULT scantok(A) term(X).
317                             {sqlite3AddDefaultValue(pParse,X,A.z,&A.z[A.n]);}
318 ccons ::= DEFAULT LP(A) expr(X) RP(Z).
319                             {sqlite3AddDefaultValue(pParse,X,A.z+1,Z.z);}
320 ccons ::= DEFAULT PLUS(A) scantok(Z) term(X).
321                             {sqlite3AddDefaultValue(pParse,X,A.z,&Z.z[Z.n]);}
322 ccons ::= DEFAULT MINUS(A) scantok(Z) term(X). {
323   Expr *p = sqlite3PExpr(pParse, TK_UMINUS, X, 0);
324   sqlite3AddDefaultValue(pParse,p,A.z,&Z.z[Z.n]);
325 }
326 ccons ::= DEFAULT scantok id(X).       {
327   Expr *p = tokenExpr(pParse, TK_STRING, X);
328   if( p ){
329     sqlite3ExprIdToTrueFalse(p);
330     testcase( p->op==TK_TRUEFALSE && sqlite3ExprTruthValue(p) );
331   }
332     sqlite3AddDefaultValue(pParse,p,X.z,X.z+X.n);
333 }
334 
335 // In addition to the type name, we also care about the primary key and
336 // UNIQUE constraints.
337 //
338 ccons ::= NULL onconf.
339 ccons ::= NOT NULL onconf(R).    {sqlite3AddNotNull(pParse, R);}
340 ccons ::= PRIMARY KEY sortorder(Z) onconf(R) autoinc(I).
341                                  {sqlite3AddPrimaryKey(pParse,0,R,I,Z);}
342 ccons ::= UNIQUE onconf(R).      {sqlite3CreateIndex(pParse,0,0,0,0,R,0,0,0,0,
343                                    SQLITE_IDXTYPE_UNIQUE);}
344 ccons ::= CHECK LP expr(X) RP.   {sqlite3AddCheckConstraint(pParse,X);}
345 ccons ::= REFERENCES nm(T) eidlist_opt(TA) refargs(R).
346                                  {sqlite3CreateForeignKey(pParse,0,&T,TA,R);}
347 ccons ::= defer_subclause(D).    {sqlite3DeferForeignKey(pParse,D);}
348 ccons ::= COLLATE ids(C).        {sqlite3AddCollateType(pParse, &C);}
349 
350 // The optional AUTOINCREMENT keyword
351 %type autoinc {int}
352 autoinc(X) ::= .          {X = 0;}
353 autoinc(X) ::= AUTOINCR.  {X = 1;}
354 
355 // The next group of rules parses the arguments to a REFERENCES clause
356 // that determine if the referential integrity checking is deferred or
357 // or immediate and which determine what action to take if a ref-integ
358 // check fails.
359 //
360 %type refargs {int}
361 refargs(A) ::= .                  { A = OE_None*0x0101; /* EV: R-19803-45884 */}
362 refargs(A) ::= refargs(A) refarg(Y). { A = (A & ~Y.mask) | Y.value; }
363 %type refarg {struct {int value; int mask;}}
364 refarg(A) ::= MATCH nm.              { A.value = 0;     A.mask = 0x000000; }
365 refarg(A) ::= ON INSERT refact.      { A.value = 0;     A.mask = 0x000000; }
366 refarg(A) ::= ON DELETE refact(X).   { A.value = X;     A.mask = 0x0000ff; }
367 refarg(A) ::= ON UPDATE refact(X).   { A.value = X<<8;  A.mask = 0x00ff00; }
368 %type refact {int}
369 refact(A) ::= SET NULL.              { A = OE_SetNull;  /* EV: R-33326-45252 */}
370 refact(A) ::= SET DEFAULT.           { A = OE_SetDflt;  /* EV: R-33326-45252 */}
371 refact(A) ::= CASCADE.               { A = OE_Cascade;  /* EV: R-33326-45252 */}
372 refact(A) ::= RESTRICT.              { A = OE_Restrict; /* EV: R-33326-45252 */}
373 refact(A) ::= NO ACTION.             { A = OE_None;     /* EV: R-33326-45252 */}
374 %type defer_subclause {int}
375 defer_subclause(A) ::= NOT DEFERRABLE init_deferred_pred_opt.     {A = 0;}
376 defer_subclause(A) ::= DEFERRABLE init_deferred_pred_opt(X).      {A = X;}
377 %type init_deferred_pred_opt {int}
378 init_deferred_pred_opt(A) ::= .                       {A = 0;}
379 init_deferred_pred_opt(A) ::= INITIALLY DEFERRED.     {A = 1;}
380 init_deferred_pred_opt(A) ::= INITIALLY IMMEDIATE.    {A = 0;}
381 
382 conslist_opt(A) ::= .                         {A.n = 0; A.z = 0;}
383 conslist_opt(A) ::= COMMA(A) conslist.
384 conslist ::= conslist tconscomma tcons.
385 conslist ::= tcons.
386 tconscomma ::= COMMA.            {pParse->constraintName.n = 0;}
387 tconscomma ::= .
388 tcons ::= CONSTRAINT nm(X).      {pParse->constraintName = X;}
389 tcons ::= PRIMARY KEY LP sortlist(X) autoinc(I) RP onconf(R).
390                                  {sqlite3AddPrimaryKey(pParse,X,R,I,0);}
391 tcons ::= UNIQUE LP sortlist(X) RP onconf(R).
392                                  {sqlite3CreateIndex(pParse,0,0,0,X,R,0,0,0,0,
393                                        SQLITE_IDXTYPE_UNIQUE);}
394 tcons ::= CHECK LP expr(E) RP onconf.
395                                  {sqlite3AddCheckConstraint(pParse,E);}
396 tcons ::= FOREIGN KEY LP eidlist(FA) RP
397           REFERENCES nm(T) eidlist_opt(TA) refargs(R) defer_subclause_opt(D). {
398     sqlite3CreateForeignKey(pParse, FA, &T, TA, R);
399     sqlite3DeferForeignKey(pParse, D);
400 }
401 %type defer_subclause_opt {int}
402 defer_subclause_opt(A) ::= .                    {A = 0;}
403 defer_subclause_opt(A) ::= defer_subclause(A).
404 
405 // The following is a non-standard extension that allows us to declare the
406 // default behavior when there is a constraint conflict.
407 //
408 %type onconf {int}
409 %type orconf {int}
410 %type resolvetype {int}
411 onconf(A) ::= .                              {A = OE_Default;}
412 onconf(A) ::= ON CONFLICT resolvetype(X).    {A = X;}
413 orconf(A) ::= .                              {A = OE_Default;}
414 orconf(A) ::= OR resolvetype(X).             {A = X;}
415 resolvetype(A) ::= raisetype(A).
416 resolvetype(A) ::= IGNORE.                   {A = OE_Ignore;}
417 resolvetype(A) ::= REPLACE.                  {A = OE_Replace;}
418 
419 ////////////////////////// The DROP TABLE /////////////////////////////////////
420 //
421 cmd ::= DROP TABLE ifexists(E) fullname(X). {
422   sqlite3DropTable(pParse, X, 0, E);
423 }
424 %type ifexists {int}
425 ifexists(A) ::= IF EXISTS.   {A = 1;}
426 ifexists(A) ::= .            {A = 0;}
427 
428 ///////////////////// The CREATE VIEW statement /////////////////////////////
429 //
430 %ifndef SQLITE_OMIT_VIEW
431 cmd ::= createkw(X) temp(T) VIEW ifnotexists(E) nm(Y) dbnm(Z) eidlist_opt(C)
432           AS select(S). {
433   sqlite3CreateView(pParse, &X, &Y, &Z, C, S, T, E);
434 }
435 cmd ::= DROP VIEW ifexists(E) fullname(X). {
436   sqlite3DropTable(pParse, X, 1, E);
437 }
438 %endif  SQLITE_OMIT_VIEW
439 
440 //////////////////////// The SELECT statement /////////////////////////////////
441 //
442 cmd ::= select(X).  {
443   SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
444   sqlite3Select(pParse, X, &dest);
445   sqlite3SelectDelete(pParse->db, X);
446 }
447 
448 %type select {Select*}
449 %destructor select {sqlite3SelectDelete(pParse->db, $$);}
450 %type selectnowith {Select*}
451 %destructor selectnowith {sqlite3SelectDelete(pParse->db, $$);}
452 %type oneselect {Select*}
453 %destructor oneselect {sqlite3SelectDelete(pParse->db, $$);}
454 
455 %include {
456   /*
457   ** For a compound SELECT statement, make sure p->pPrior->pNext==p for
458   ** all elements in the list.  And make sure list length does not exceed
459   ** SQLITE_LIMIT_COMPOUND_SELECT.
460   */
461   static void parserDoubleLinkSelect(Parse *pParse, Select *p){
462     assert( p!=0 );
463     if( p->pPrior ){
464       Select *pNext = 0, *pLoop;
465       int mxSelect, cnt = 0;
466       for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
467         pLoop->pNext = pNext;
468         pLoop->selFlags |= SF_Compound;
469       }
470       if( (p->selFlags & SF_MultiValue)==0 &&
471         (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 &&
472         cnt>mxSelect
473       ){
474         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
475       }
476     }
477   }
478 }
479 
480 %ifndef SQLITE_OMIT_CTE
481 select(A) ::= WITH wqlist(W) selectnowith(X). {
482   Select *p = X;
483   if( p ){
484     p->pWith = W;
485     parserDoubleLinkSelect(pParse, p);
486   }else{
487     sqlite3WithDelete(pParse->db, W);
488   }
489   A = p;
490 }
491 select(A) ::= WITH RECURSIVE wqlist(W) selectnowith(X). {
492   Select *p = X;
493   if( p ){
494     p->pWith = W;
495     parserDoubleLinkSelect(pParse, p);
496   }else{
497     sqlite3WithDelete(pParse->db, W);
498   }
499   A = p;
500 }
501 %endif /* SQLITE_OMIT_CTE */
502 select(A) ::= selectnowith(X). {
503   Select *p = X;
504   if( p ){
505     parserDoubleLinkSelect(pParse, p);
506   }
507   A = p; /*A-overwrites-X*/
508 }
509 
510 selectnowith(A) ::= oneselect(A).
511 %ifndef SQLITE_OMIT_COMPOUND_SELECT
512 selectnowith(A) ::= selectnowith(A) multiselect_op(Y) oneselect(Z).  {
513   Select *pRhs = Z;
514   Select *pLhs = A;
515   if( pRhs && pRhs->pPrior ){
516     SrcList *pFrom;
517     Token x;
518     x.n = 0;
519     parserDoubleLinkSelect(pParse, pRhs);
520     pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
521     pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0);
522   }
523   if( pRhs ){
524     pRhs->op = (u8)Y;
525     pRhs->pPrior = pLhs;
526     if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue;
527     pRhs->selFlags &= ~SF_MultiValue;
528     if( Y!=TK_ALL ) pParse->hasCompound = 1;
529   }else{
530     sqlite3SelectDelete(pParse->db, pLhs);
531   }
532   A = pRhs;
533 }
534 %type multiselect_op {int}
535 multiselect_op(A) ::= UNION(OP).             {A = @OP; /*A-overwrites-OP*/}
536 multiselect_op(A) ::= UNION ALL.             {A = TK_ALL;}
537 multiselect_op(A) ::= EXCEPT|INTERSECT(OP).  {A = @OP; /*A-overwrites-OP*/}
538 %endif SQLITE_OMIT_COMPOUND_SELECT
539 
540 oneselect(A) ::= SELECT distinct(D) selcollist(W) from(X) where_opt(Y)
541                  groupby_opt(P) having_opt(Q)
542                  orderby_opt(Z) limit_opt(L). {
543   A = sqlite3SelectNew(pParse,W,X,Y,P,Q,Z,D,L);
544 }
545 %ifndef SQLITE_OMIT_WINDOWFUNC
546 oneselect(A) ::= SELECT distinct(D) selcollist(W) from(X) where_opt(Y)
547                  groupby_opt(P) having_opt(Q) window_clause(R)
548                  orderby_opt(Z) limit_opt(L). {
549   A = sqlite3SelectNew(pParse,W,X,Y,P,Q,Z,D,L);
550   if( A ){
551     A->pWinDefn = R;
552   }else{
553     sqlite3WindowListDelete(pParse->db, R);
554   }
555 }
556 %endif
557 
558 
559 oneselect(A) ::= values(A).
560 
561 %type values {Select*}
562 %destructor values {sqlite3SelectDelete(pParse->db, $$);}
563 values(A) ::= VALUES LP nexprlist(X) RP. {
564   A = sqlite3SelectNew(pParse,X,0,0,0,0,0,SF_Values,0);
565 }
566 values(A) ::= values(A) COMMA LP nexprlist(Y) RP. {
567   Select *pRight, *pLeft = A;
568   pRight = sqlite3SelectNew(pParse,Y,0,0,0,0,0,SF_Values|SF_MultiValue,0);
569   if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue;
570   if( pRight ){
571     pRight->op = TK_ALL;
572     pRight->pPrior = pLeft;
573     A = pRight;
574   }else{
575     A = pLeft;
576   }
577 }
578 
579 // The "distinct" nonterminal is true (1) if the DISTINCT keyword is
580 // present and false (0) if it is not.
581 //
582 %type distinct {int}
583 distinct(A) ::= DISTINCT.   {A = SF_Distinct;}
584 distinct(A) ::= ALL.        {A = SF_All;}
585 distinct(A) ::= .           {A = 0;}
586 
587 // selcollist is a list of expressions that are to become the return
588 // values of the SELECT statement.  The "*" in statements like
589 // "SELECT * FROM ..." is encoded as a special expression with an
590 // opcode of TK_ASTERISK.
591 //
592 %type selcollist {ExprList*}
593 %destructor selcollist {sqlite3ExprListDelete(pParse->db, $$);}
594 %type sclp {ExprList*}
595 %destructor sclp {sqlite3ExprListDelete(pParse->db, $$);}
596 sclp(A) ::= selcollist(A) COMMA.
597 sclp(A) ::= .                                {A = 0;}
598 selcollist(A) ::= sclp(A) scanpt(B) expr(X) scanpt(Z) as(Y).     {
599    A = sqlite3ExprListAppend(pParse, A, X);
600    if( Y.n>0 ) sqlite3ExprListSetName(pParse, A, &Y, 1);
601    sqlite3ExprListSetSpan(pParse,A,B,Z);
602 }
603 selcollist(A) ::= sclp(A) scanpt STAR. {
604   Expr *p = sqlite3Expr(pParse->db, TK_ASTERISK, 0);
605   A = sqlite3ExprListAppend(pParse, A, p);
606 }
607 selcollist(A) ::= sclp(A) scanpt nm(X) DOT STAR. {
608   Expr *pRight = sqlite3PExpr(pParse, TK_ASTERISK, 0, 0);
609   Expr *pLeft = sqlite3ExprAlloc(pParse->db, TK_ID, &X, 1);
610   Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
611   A = sqlite3ExprListAppend(pParse,A, pDot);
612 }
613 
614 // An option "AS <id>" phrase that can follow one of the expressions that
615 // define the result set, or one of the tables in the FROM clause.
616 //
617 %type as {Token}
618 as(X) ::= AS nm(Y).    {X = Y;}
619 as(X) ::= ids(X).
620 as(X) ::= .            {X.n = 0; X.z = 0;}
621 
622 
623 %type seltablist {SrcList*}
624 %destructor seltablist {sqlite3SrcListDelete(pParse->db, $$);}
625 %type stl_prefix {SrcList*}
626 %destructor stl_prefix {sqlite3SrcListDelete(pParse->db, $$);}
627 %type from {SrcList*}
628 %destructor from {sqlite3SrcListDelete(pParse->db, $$);}
629 
630 // A complete FROM clause.
631 //
632 from(A) ::= .                {A = sqlite3DbMallocZero(pParse->db, sizeof(*A));}
633 from(A) ::= FROM seltablist(X). {
634   A = X;
635   sqlite3SrcListShiftJoinType(A);
636 }
637 
638 // "seltablist" is a "Select Table List" - the content of the FROM clause
639 // in a SELECT statement.  "stl_prefix" is a prefix of this list.
640 //
641 stl_prefix(A) ::= seltablist(A) joinop(Y).    {
642    if( ALWAYS(A && A->nSrc>0) ) A->a[A->nSrc-1].fg.jointype = (u8)Y;
643 }
644 stl_prefix(A) ::= .                           {A = 0;}
645 seltablist(A) ::= stl_prefix(A) nm(Y) dbnm(D) as(Z) indexed_opt(I)
646                   on_opt(N) using_opt(U). {
647   A = sqlite3SrcListAppendFromTerm(pParse,A,&Y,&D,&Z,0,N,U);
648   sqlite3SrcListIndexedBy(pParse, A, &I);
649 }
650 seltablist(A) ::= stl_prefix(A) nm(Y) dbnm(D) LP exprlist(E) RP as(Z)
651                   on_opt(N) using_opt(U). {
652   A = sqlite3SrcListAppendFromTerm(pParse,A,&Y,&D,&Z,0,N,U);
653   sqlite3SrcListFuncArgs(pParse, A, E);
654 }
655 %ifndef SQLITE_OMIT_SUBQUERY
656   seltablist(A) ::= stl_prefix(A) LP select(S) RP
657                     as(Z) on_opt(N) using_opt(U). {
658     A = sqlite3SrcListAppendFromTerm(pParse,A,0,0,&Z,S,N,U);
659   }
660   seltablist(A) ::= stl_prefix(A) LP seltablist(F) RP
661                     as(Z) on_opt(N) using_opt(U). {
662     if( A==0 && Z.n==0 && N==0 && U==0 ){
663       A = F;
664     }else if( F->nSrc==1 ){
665       A = sqlite3SrcListAppendFromTerm(pParse,A,0,0,&Z,0,N,U);
666       if( A ){
667         struct SrcList_item *pNew = &A->a[A->nSrc-1];
668         struct SrcList_item *pOld = F->a;
669         pNew->zName = pOld->zName;
670         pNew->zDatabase = pOld->zDatabase;
671         pNew->pSelect = pOld->pSelect;
672         if( pOld->fg.isTabFunc ){
673           pNew->u1.pFuncArg = pOld->u1.pFuncArg;
674           pOld->u1.pFuncArg = 0;
675           pOld->fg.isTabFunc = 0;
676           pNew->fg.isTabFunc = 1;
677         }
678         pOld->zName = pOld->zDatabase = 0;
679         pOld->pSelect = 0;
680       }
681       sqlite3SrcListDelete(pParse->db, F);
682     }else{
683       Select *pSubquery;
684       sqlite3SrcListShiftJoinType(F);
685       pSubquery = sqlite3SelectNew(pParse,0,F,0,0,0,0,SF_NestedFrom,0);
686       A = sqlite3SrcListAppendFromTerm(pParse,A,0,0,&Z,pSubquery,N,U);
687     }
688   }
689 %endif  SQLITE_OMIT_SUBQUERY
690 
691 %type dbnm {Token}
692 dbnm(A) ::= .          {A.z=0; A.n=0;}
693 dbnm(A) ::= DOT nm(X). {A = X;}
694 
695 %type fullname {SrcList*}
696 %destructor fullname {sqlite3SrcListDelete(pParse->db, $$);}
697 fullname(A) ::= nm(X).  {
698   A = sqlite3SrcListAppend(pParse,0,&X,0);
699   if( IN_RENAME_OBJECT && A ) sqlite3RenameTokenMap(pParse, A->a[0].zName, &X);
700 }
701 fullname(A) ::= nm(X) DOT nm(Y). {
702   A = sqlite3SrcListAppend(pParse,0,&X,&Y);
703   if( IN_RENAME_OBJECT && A ) sqlite3RenameTokenMap(pParse, A->a[0].zName, &Y);
704 }
705 
706 %type xfullname {SrcList*}
707 %destructor xfullname {sqlite3SrcListDelete(pParse->db, $$);}
708 xfullname(A) ::= nm(X).
709    {A = sqlite3SrcListAppend(pParse,0,&X,0); /*A-overwrites-X*/}
710 xfullname(A) ::= nm(X) DOT nm(Y).
711    {A = sqlite3SrcListAppend(pParse,0,&X,&Y); /*A-overwrites-X*/}
712 xfullname(A) ::= nm(X) DOT nm(Y) AS nm(Z).  {
713    A = sqlite3SrcListAppend(pParse,0,&X,&Y); /*A-overwrites-X*/
714    if( A ) A->a[0].zAlias = sqlite3NameFromToken(pParse->db, &Z);
715 }
716 xfullname(A) ::= nm(X) AS nm(Z). {
717    A = sqlite3SrcListAppend(pParse,0,&X,0); /*A-overwrites-X*/
718    if( A ) A->a[0].zAlias = sqlite3NameFromToken(pParse->db, &Z);
719 }
720 
721 %type joinop {int}
722 joinop(X) ::= COMMA|JOIN.              { X = JT_INNER; }
723 joinop(X) ::= JOIN_KW(A) JOIN.
724                   {X = sqlite3JoinType(pParse,&A,0,0);  /*X-overwrites-A*/}
725 joinop(X) ::= JOIN_KW(A) nm(B) JOIN.
726                   {X = sqlite3JoinType(pParse,&A,&B,0); /*X-overwrites-A*/}
727 joinop(X) ::= JOIN_KW(A) nm(B) nm(C) JOIN.
728                   {X = sqlite3JoinType(pParse,&A,&B,&C);/*X-overwrites-A*/}
729 
730 // There is a parsing abiguity in an upsert statement that uses a
731 // SELECT on the RHS of a the INSERT:
732 //
733 //      INSERT INTO tab SELECT * FROM aaa JOIN bbb ON CONFLICT ...
734 //                                        here ----^^
735 //
736 // When the ON token is encountered, the parser does not know if it is
737 // the beginning of an ON CONFLICT clause, or the beginning of an ON
738 // clause associated with the JOIN.  The conflict is resolved in favor
739 // of the JOIN.  If an ON CONFLICT clause is intended, insert a dummy
740 // WHERE clause in between, like this:
741 //
742 //      INSERT INTO tab SELECT * FROM aaa JOIN bbb WHERE true ON CONFLICT ...
743 //
744 // The [AND] and [OR] precedence marks in the rules for on_opt cause the
745 // ON in this context to always be interpreted as belonging to the JOIN.
746 //
747 %type on_opt {Expr*}
748 %destructor on_opt {sqlite3ExprDelete(pParse->db, $$);}
749 on_opt(N) ::= ON expr(E).  {N = E;}
750 on_opt(N) ::= .     [OR]   {N = 0;}
751 
752 // Note that this block abuses the Token type just a little. If there is
753 // no "INDEXED BY" clause, the returned token is empty (z==0 && n==0). If
754 // there is an INDEXED BY clause, then the token is populated as per normal,
755 // with z pointing to the token data and n containing the number of bytes
756 // in the token.
757 //
758 // If there is a "NOT INDEXED" clause, then (z==0 && n==1), which is
759 // normally illegal. The sqlite3SrcListIndexedBy() function
760 // recognizes and interprets this as a special case.
761 //
762 %type indexed_opt {Token}
763 indexed_opt(A) ::= .                 {A.z=0; A.n=0;}
764 indexed_opt(A) ::= INDEXED BY nm(X). {A = X;}
765 indexed_opt(A) ::= NOT INDEXED.      {A.z=0; A.n=1;}
766 
767 %type using_opt {IdList*}
768 %destructor using_opt {sqlite3IdListDelete(pParse->db, $$);}
769 using_opt(U) ::= USING LP idlist(L) RP.  {U = L;}
770 using_opt(U) ::= .                        {U = 0;}
771 
772 
773 %type orderby_opt {ExprList*}
774 %destructor orderby_opt {sqlite3ExprListDelete(pParse->db, $$);}
775 
776 // the sortlist non-terminal stores a list of expression where each
777 // expression is optionally followed by ASC or DESC to indicate the
778 // sort order.
779 //
780 %type sortlist {ExprList*}
781 %destructor sortlist {sqlite3ExprListDelete(pParse->db, $$);}
782 
783 orderby_opt(A) ::= .                          {A = 0;}
784 orderby_opt(A) ::= ORDER BY sortlist(X).      {A = X;}
785 sortlist(A) ::= sortlist(A) COMMA expr(Y) sortorder(Z) nulls(X). {
786   A = sqlite3ExprListAppend(pParse,A,Y);
787   sqlite3ExprListSetSortOrder(A,Z,X);
788 }
789 sortlist(A) ::= expr(Y) sortorder(Z) nulls(X). {
790   A = sqlite3ExprListAppend(pParse,0,Y); /*A-overwrites-Y*/
791   sqlite3ExprListSetSortOrder(A,Z,X);
792 }
793 
794 %type sortorder {int}
795 
796 sortorder(A) ::= ASC.           {A = SQLITE_SO_ASC;}
797 sortorder(A) ::= DESC.          {A = SQLITE_SO_DESC;}
798 sortorder(A) ::= .              {A = SQLITE_SO_UNDEFINED;}
799 
800 %type nulls {int}
801 nulls(A) ::= NULLS FIRST.       {A = SQLITE_SO_ASC;}
802 nulls(A) ::= NULLS LAST.        {A = SQLITE_SO_DESC;}
803 nulls(A) ::= .                  {A = SQLITE_SO_UNDEFINED;}
804 
805 %type groupby_opt {ExprList*}
806 %destructor groupby_opt {sqlite3ExprListDelete(pParse->db, $$);}
807 groupby_opt(A) ::= .                      {A = 0;}
808 groupby_opt(A) ::= GROUP BY nexprlist(X). {A = X;}
809 
810 %type having_opt {Expr*}
811 %destructor having_opt {sqlite3ExprDelete(pParse->db, $$);}
812 having_opt(A) ::= .                {A = 0;}
813 having_opt(A) ::= HAVING expr(X).  {A = X;}
814 
815 %type limit_opt {Expr*}
816 
817 // The destructor for limit_opt will never fire in the current grammar.
818 // The limit_opt non-terminal only occurs at the end of a single production
819 // rule for SELECT statements.  As soon as the rule that create the
820 // limit_opt non-terminal reduces, the SELECT statement rule will also
821 // reduce.  So there is never a limit_opt non-terminal on the stack
822 // except as a transient.  So there is never anything to destroy.
823 //
824 //%destructor limit_opt {sqlite3ExprDelete(pParse->db, $$);}
825 limit_opt(A) ::= .       {A = 0;}
826 limit_opt(A) ::= LIMIT expr(X).
827                          {A = sqlite3PExpr(pParse,TK_LIMIT,X,0);}
828 limit_opt(A) ::= LIMIT expr(X) OFFSET expr(Y).
829                          {A = sqlite3PExpr(pParse,TK_LIMIT,X,Y);}
830 limit_opt(A) ::= LIMIT expr(X) COMMA expr(Y).
831                          {A = sqlite3PExpr(pParse,TK_LIMIT,Y,X);}
832 
833 /////////////////////////// The DELETE statement /////////////////////////////
834 //
835 %ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
836 cmd ::= with DELETE FROM xfullname(X) indexed_opt(I) where_opt(W)
837         orderby_opt(O) limit_opt(L). {
838   sqlite3SrcListIndexedBy(pParse, X, &I);
839 #ifndef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
840   sqlite3ExprListDelete(pParse->db, O); O = 0;
841   sqlite3ExprDelete(pParse->db, L); L = 0;
842 #endif
843   sqlite3DeleteFrom(pParse,X,W,O,L);
844 }
845 %endif
846 %ifndef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
847 cmd ::= with DELETE FROM xfullname(X) indexed_opt(I) where_opt(W). {
848   sqlite3SrcListIndexedBy(pParse, X, &I);
849   sqlite3DeleteFrom(pParse,X,W,0,0);
850 }
851 %endif
852 
853 %type where_opt {Expr*}
854 %destructor where_opt {sqlite3ExprDelete(pParse->db, $$);}
855 
856 where_opt(A) ::= .                    {A = 0;}
857 where_opt(A) ::= WHERE expr(X).       {A = X;}
858 
859 ////////////////////////// The UPDATE command ////////////////////////////////
860 //
861 %ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
862 cmd ::= with UPDATE orconf(R) xfullname(X) indexed_opt(I) SET setlist(Y)
863         where_opt(W) orderby_opt(O) limit_opt(L).  {
864   sqlite3SrcListIndexedBy(pParse, X, &I);
865   sqlite3ExprListCheckLength(pParse,Y,"set list");
866   sqlite3Update(pParse,X,Y,W,R,O,L,0);
867 }
868 %endif
869 %ifndef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
870 cmd ::= with UPDATE orconf(R) xfullname(X) indexed_opt(I) SET setlist(Y)
871         where_opt(W).  {
872   sqlite3SrcListIndexedBy(pParse, X, &I);
873   sqlite3ExprListCheckLength(pParse,Y,"set list");
874   sqlite3Update(pParse,X,Y,W,R,0,0,0);
875 }
876 %endif
877 
878 %type setlist {ExprList*}
879 %destructor setlist {sqlite3ExprListDelete(pParse->db, $$);}
880 
881 setlist(A) ::= setlist(A) COMMA nm(X) EQ expr(Y). {
882   A = sqlite3ExprListAppend(pParse, A, Y);
883   sqlite3ExprListSetName(pParse, A, &X, 1);
884 }
885 setlist(A) ::= setlist(A) COMMA LP idlist(X) RP EQ expr(Y). {
886   A = sqlite3ExprListAppendVector(pParse, A, X, Y);
887 }
888 setlist(A) ::= nm(X) EQ expr(Y). {
889   A = sqlite3ExprListAppend(pParse, 0, Y);
890   sqlite3ExprListSetName(pParse, A, &X, 1);
891 }
892 setlist(A) ::= LP idlist(X) RP EQ expr(Y). {
893   A = sqlite3ExprListAppendVector(pParse, 0, X, Y);
894 }
895 
896 ////////////////////////// The INSERT command /////////////////////////////////
897 //
898 cmd ::= with insert_cmd(R) INTO xfullname(X) idlist_opt(F) select(S)
899         upsert(U). {
900   sqlite3Insert(pParse, X, S, F, R, U);
901 }
902 cmd ::= with insert_cmd(R) INTO xfullname(X) idlist_opt(F) DEFAULT VALUES.
903 {
904   sqlite3Insert(pParse, X, 0, F, R, 0);
905 }
906 
907 %type upsert {Upsert*}
908 
909 // Because upsert only occurs at the tip end of the INSERT rule for cmd,
910 // there is never a case where the value of the upsert pointer will not
911 // be destroyed by the cmd action.  So comment-out the destructor to
912 // avoid unreachable code.
913 //%destructor upsert {sqlite3UpsertDelete(pParse->db,$$);}
914 upsert(A) ::= . { A = 0; }
915 upsert(A) ::= ON CONFLICT LP sortlist(T) RP where_opt(TW)
916               DO UPDATE SET setlist(Z) where_opt(W).
917               { A = sqlite3UpsertNew(pParse->db,T,TW,Z,W);}
918 upsert(A) ::= ON CONFLICT LP sortlist(T) RP where_opt(TW) DO NOTHING.
919               { A = sqlite3UpsertNew(pParse->db,T,TW,0,0); }
920 upsert(A) ::= ON CONFLICT DO NOTHING.
921               { A = sqlite3UpsertNew(pParse->db,0,0,0,0); }
922 
923 %type insert_cmd {int}
924 insert_cmd(A) ::= INSERT orconf(R).   {A = R;}
925 insert_cmd(A) ::= REPLACE.            {A = OE_Replace;}
926 
927 %type idlist_opt {IdList*}
928 %destructor idlist_opt {sqlite3IdListDelete(pParse->db, $$);}
929 %type idlist {IdList*}
930 %destructor idlist {sqlite3IdListDelete(pParse->db, $$);}
931 
932 idlist_opt(A) ::= .                       {A = 0;}
933 idlist_opt(A) ::= LP idlist(X) RP.    {A = X;}
934 idlist(A) ::= idlist(A) COMMA nm(Y).
935     {A = sqlite3IdListAppend(pParse,A,&Y);}
936 idlist(A) ::= nm(Y).
937     {A = sqlite3IdListAppend(pParse,0,&Y); /*A-overwrites-Y*/}
938 
939 /////////////////////////// Expression Processing /////////////////////////////
940 //
941 
942 %type expr {Expr*}
943 %destructor expr {sqlite3ExprDelete(pParse->db, $$);}
944 %type term {Expr*}
945 %destructor term {sqlite3ExprDelete(pParse->db, $$);}
946 
947 %include {
948 
949   /* Construct a new Expr object from a single identifier.  Use the
950   ** new Expr to populate pOut.  Set the span of pOut to be the identifier
951   ** that created the expression.
952   */
953   static Expr *tokenExpr(Parse *pParse, int op, Token t){
954     Expr *p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr)+t.n+1);
955     if( p ){
956       /* memset(p, 0, sizeof(Expr)); */
957       p->op = (u8)op;
958       p->affExpr = 0;
959       p->flags = EP_Leaf;
960       p->iAgg = -1;
961       p->pLeft = p->pRight = 0;
962       p->x.pList = 0;
963       p->pAggInfo = 0;
964       p->y.pTab = 0;
965       p->op2 = 0;
966       p->iTable = 0;
967       p->iColumn = 0;
968       p->u.zToken = (char*)&p[1];
969       memcpy(p->u.zToken, t.z, t.n);
970       p->u.zToken[t.n] = 0;
971       if( sqlite3Isquote(p->u.zToken[0]) ){
972         sqlite3DequoteExpr(p);
973       }
974 #if SQLITE_MAX_EXPR_DEPTH>0
975       p->nHeight = 1;
976 #endif
977       if( IN_RENAME_OBJECT ){
978         return (Expr*)sqlite3RenameTokenMap(pParse, (void*)p, &t);
979       }
980     }
981     return p;
982   }
983 
984 }
985 
986 expr(A) ::= term(A).
987 expr(A) ::= LP expr(X) RP. {A = X;}
988 expr(A) ::= id(X).          {A=tokenExpr(pParse,TK_ID,X); /*A-overwrites-X*/}
989 expr(A) ::= JOIN_KW(X).     {A=tokenExpr(pParse,TK_ID,X); /*A-overwrites-X*/}
990 expr(A) ::= nm(X) DOT nm(Y). {
991   Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &X, 1);
992   Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &Y, 1);
993   if( IN_RENAME_OBJECT ){
994     sqlite3RenameTokenMap(pParse, (void*)temp2, &Y);
995     sqlite3RenameTokenMap(pParse, (void*)temp1, &X);
996   }
997   A = sqlite3PExpr(pParse, TK_DOT, temp1, temp2);
998 }
999 expr(A) ::= nm(X) DOT nm(Y) DOT nm(Z). {
1000   Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &X, 1);
1001   Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &Y, 1);
1002   Expr *temp3 = sqlite3ExprAlloc(pParse->db, TK_ID, &Z, 1);
1003   Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3);
1004   if( IN_RENAME_OBJECT ){
1005     sqlite3RenameTokenMap(pParse, (void*)temp3, &Z);
1006     sqlite3RenameTokenMap(pParse, (void*)temp2, &Y);
1007   }
1008   A = sqlite3PExpr(pParse, TK_DOT, temp1, temp4);
1009 }
1010 term(A) ::= NULL|FLOAT|BLOB(X). {A=tokenExpr(pParse,@X,X); /*A-overwrites-X*/}
1011 term(A) ::= STRING(X).          {A=tokenExpr(pParse,@X,X); /*A-overwrites-X*/}
1012 term(A) ::= INTEGER(X). {
1013   A = sqlite3ExprAlloc(pParse->db, TK_INTEGER, &X, 1);
1014 }
1015 expr(A) ::= VARIABLE(X).     {
1016   if( !(X.z[0]=='#' && sqlite3Isdigit(X.z[1])) ){
1017     u32 n = X.n;
1018     A = tokenExpr(pParse, TK_VARIABLE, X);
1019     sqlite3ExprAssignVarNumber(pParse, A, n);
1020   }else{
1021     /* When doing a nested parse, one can include terms in an expression
1022     ** that look like this:   #1 #2 ...  These terms refer to registers
1023     ** in the virtual machine.  #N is the N-th register. */
1024     Token t = X; /*A-overwrites-X*/
1025     assert( t.n>=2 );
1026     if( pParse->nested==0 ){
1027       sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &t);
1028       A = 0;
1029     }else{
1030       A = sqlite3PExpr(pParse, TK_REGISTER, 0, 0);
1031       if( A ) sqlite3GetInt32(&t.z[1], &A->iTable);
1032     }
1033   }
1034 }
1035 expr(A) ::= expr(A) COLLATE ids(C). {
1036   A = sqlite3ExprAddCollateToken(pParse, A, &C, 1);
1037 }
1038 %ifndef SQLITE_OMIT_CAST
1039 expr(A) ::= CAST LP expr(E) AS typetoken(T) RP. {
1040   A = sqlite3ExprAlloc(pParse->db, TK_CAST, &T, 1);
1041   sqlite3ExprAttachSubtrees(pParse->db, A, E, 0);
1042 }
1043 %endif  SQLITE_OMIT_CAST
1044 
1045 
1046 expr(A) ::= id(X) LP distinct(D) exprlist(Y) RP. {
1047   A = sqlite3ExprFunction(pParse, Y, &X, D);
1048 }
1049 expr(A) ::= id(X) LP STAR RP. {
1050   A = sqlite3ExprFunction(pParse, 0, &X, 0);
1051 }
1052 
1053 %ifndef SQLITE_OMIT_WINDOWFUNC
1054 expr(A) ::= id(X) LP distinct(D) exprlist(Y) RP filter_over(Z). {
1055   A = sqlite3ExprFunction(pParse, Y, &X, D);
1056   sqlite3WindowAttach(pParse, A, Z);
1057 }
1058 expr(A) ::= id(X) LP STAR RP filter_over(Z). {
1059   A = sqlite3ExprFunction(pParse, 0, &X, 0);
1060   sqlite3WindowAttach(pParse, A, Z);
1061 }
1062 %endif
1063 
1064 term(A) ::= CTIME_KW(OP). {
1065   A = sqlite3ExprFunction(pParse, 0, &OP, 0);
1066 }
1067 
1068 expr(A) ::= LP nexprlist(X) COMMA expr(Y) RP. {
1069   ExprList *pList = sqlite3ExprListAppend(pParse, X, Y);
1070   A = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
1071   if( A ){
1072     A->x.pList = pList;
1073   }else{
1074     sqlite3ExprListDelete(pParse->db, pList);
1075   }
1076 }
1077 
1078 expr(A) ::= expr(A) AND expr(Y).        {A=sqlite3ExprAnd(pParse,A,Y);}
1079 expr(A) ::= expr(A) OR(OP) expr(Y).     {A=sqlite3PExpr(pParse,@OP,A,Y);}
1080 expr(A) ::= expr(A) LT|GT|GE|LE(OP) expr(Y).
1081                                         {A=sqlite3PExpr(pParse,@OP,A,Y);}
1082 expr(A) ::= expr(A) EQ|NE(OP) expr(Y).  {A=sqlite3PExpr(pParse,@OP,A,Y);}
1083 expr(A) ::= expr(A) BITAND|BITOR|LSHIFT|RSHIFT(OP) expr(Y).
1084                                         {A=sqlite3PExpr(pParse,@OP,A,Y);}
1085 expr(A) ::= expr(A) PLUS|MINUS(OP) expr(Y).
1086                                         {A=sqlite3PExpr(pParse,@OP,A,Y);}
1087 expr(A) ::= expr(A) STAR|SLASH|REM(OP) expr(Y).
1088                                         {A=sqlite3PExpr(pParse,@OP,A,Y);}
1089 expr(A) ::= expr(A) CONCAT(OP) expr(Y). {A=sqlite3PExpr(pParse,@OP,A,Y);}
1090 %type likeop {Token}
1091 likeop(A) ::= LIKE_KW|MATCH(A).
1092 likeop(A) ::= NOT LIKE_KW|MATCH(X). {A=X; A.n|=0x80000000; /*A-overwrite-X*/}
1093 expr(A) ::= expr(A) likeop(OP) expr(Y).  [LIKE_KW]  {
1094   ExprList *pList;
1095   int bNot = OP.n & 0x80000000;
1096   OP.n &= 0x7fffffff;
1097   pList = sqlite3ExprListAppend(pParse,0, Y);
1098   pList = sqlite3ExprListAppend(pParse,pList, A);
1099   A = sqlite3ExprFunction(pParse, pList, &OP, 0);
1100   if( bNot ) A = sqlite3PExpr(pParse, TK_NOT, A, 0);
1101   if( A ) A->flags |= EP_InfixFunc;
1102 }
1103 expr(A) ::= expr(A) likeop(OP) expr(Y) ESCAPE expr(E).  [LIKE_KW]  {
1104   ExprList *pList;
1105   int bNot = OP.n & 0x80000000;
1106   OP.n &= 0x7fffffff;
1107   pList = sqlite3ExprListAppend(pParse,0, Y);
1108   pList = sqlite3ExprListAppend(pParse,pList, A);
1109   pList = sqlite3ExprListAppend(pParse,pList, E);
1110   A = sqlite3ExprFunction(pParse, pList, &OP, 0);
1111   if( bNot ) A = sqlite3PExpr(pParse, TK_NOT, A, 0);
1112   if( A ) A->flags |= EP_InfixFunc;
1113 }
1114 
1115 expr(A) ::= expr(A) ISNULL|NOTNULL(E).   {A = sqlite3PExpr(pParse,@E,A,0);}
1116 expr(A) ::= expr(A) NOT NULL.    {A = sqlite3PExpr(pParse,TK_NOTNULL,A,0);}
1117 
1118 %include {
1119   /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
1120   ** unary TK_ISNULL or TK_NOTNULL expression. */
1121   static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
1122     sqlite3 *db = pParse->db;
1123     if( pA && pY && pY->op==TK_NULL && !IN_RENAME_OBJECT ){
1124       pA->op = (u8)op;
1125       sqlite3ExprDelete(db, pA->pRight);
1126       pA->pRight = 0;
1127     }
1128   }
1129 }
1130 
1131 //    expr1 IS expr2
1132 //    expr1 IS NOT expr2
1133 //
1134 // If expr2 is NULL then code as TK_ISNULL or TK_NOTNULL.  If expr2
1135 // is any other expression, code as TK_IS or TK_ISNOT.
1136 //
1137 expr(A) ::= expr(A) IS expr(Y).     {
1138   A = sqlite3PExpr(pParse,TK_IS,A,Y);
1139   binaryToUnaryIfNull(pParse, Y, A, TK_ISNULL);
1140 }
1141 expr(A) ::= expr(A) IS NOT expr(Y). {
1142   A = sqlite3PExpr(pParse,TK_ISNOT,A,Y);
1143   binaryToUnaryIfNull(pParse, Y, A, TK_NOTNULL);
1144 }
1145 
1146 expr(A) ::= NOT(B) expr(X).
1147               {A = sqlite3PExpr(pParse, @B, X, 0);/*A-overwrites-B*/}
1148 expr(A) ::= BITNOT(B) expr(X).
1149               {A = sqlite3PExpr(pParse, @B, X, 0);/*A-overwrites-B*/}
1150 expr(A) ::= PLUS|MINUS(B) expr(X). [BITNOT] {
1151   A = sqlite3PExpr(pParse, @B==TK_PLUS ? TK_UPLUS : TK_UMINUS, X, 0);
1152   /*A-overwrites-B*/
1153 }
1154 
1155 %type between_op {int}
1156 between_op(A) ::= BETWEEN.     {A = 0;}
1157 between_op(A) ::= NOT BETWEEN. {A = 1;}
1158 expr(A) ::= expr(A) between_op(N) expr(X) AND expr(Y). [BETWEEN] {
1159   ExprList *pList = sqlite3ExprListAppend(pParse,0, X);
1160   pList = sqlite3ExprListAppend(pParse,pList, Y);
1161   A = sqlite3PExpr(pParse, TK_BETWEEN, A, 0);
1162   if( A ){
1163     A->x.pList = pList;
1164   }else{
1165     sqlite3ExprListDelete(pParse->db, pList);
1166   }
1167   if( N ) A = sqlite3PExpr(pParse, TK_NOT, A, 0);
1168 }
1169 %ifndef SQLITE_OMIT_SUBQUERY
1170   %type in_op {int}
1171   in_op(A) ::= IN.      {A = 0;}
1172   in_op(A) ::= NOT IN.  {A = 1;}
1173   expr(A) ::= expr(A) in_op(N) LP exprlist(Y) RP. [IN] {
1174     if( Y==0 ){
1175       /* Expressions of the form
1176       **
1177       **      expr1 IN ()
1178       **      expr1 NOT IN ()
1179       **
1180       ** simplify to constants 0 (false) and 1 (true), respectively,
1181       ** regardless of the value of expr1.
1182       */
1183       sqlite3ExprUnmapAndDelete(pParse, A);
1184       A = sqlite3ExprAlloc(pParse->db, TK_INTEGER,&sqlite3IntTokens[N],1);
1185     }else if( Y->nExpr==1 ){
1186       /* Expressions of the form:
1187       **
1188       **      expr1 IN (?1)
1189       **      expr1 NOT IN (?2)
1190       **
1191       ** with exactly one value on the RHS can be simplified to something
1192       ** like this:
1193       **
1194       **      expr1 == ?1
1195       **      expr1 <> ?2
1196       **
1197       ** But, the RHS of the == or <> is marked with the EP_Generic flag
1198       ** so that it may not contribute to the computation of comparison
1199       ** affinity or the collating sequence to use for comparison.  Otherwise,
1200       ** the semantics would be subtly different from IN or NOT IN.
1201       */
1202       Expr *pRHS = Y->a[0].pExpr;
1203       Y->a[0].pExpr = 0;
1204       sqlite3ExprListDelete(pParse->db, Y);
1205       /* pRHS cannot be NULL because a malloc error would have been detected
1206       ** before now and control would have never reached this point */
1207       if( ALWAYS(pRHS) ){
1208         pRHS->flags &= ~EP_Collate;
1209         pRHS->flags |= EP_Generic;
1210       }
1211       A = sqlite3PExpr(pParse, N ? TK_NE : TK_EQ, A, pRHS);
1212     }else{
1213       A = sqlite3PExpr(pParse, TK_IN, A, 0);
1214       if( A ){
1215         A->x.pList = Y;
1216         sqlite3ExprSetHeightAndFlags(pParse, A);
1217       }else{
1218         sqlite3ExprListDelete(pParse->db, Y);
1219       }
1220       if( N ) A = sqlite3PExpr(pParse, TK_NOT, A, 0);
1221     }
1222   }
1223   expr(A) ::= LP select(X) RP. {
1224     A = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
1225     sqlite3PExprAddSelect(pParse, A, X);
1226   }
1227   expr(A) ::= expr(A) in_op(N) LP select(Y) RP.  [IN] {
1228     A = sqlite3PExpr(pParse, TK_IN, A, 0);
1229     sqlite3PExprAddSelect(pParse, A, Y);
1230     if( N ) A = sqlite3PExpr(pParse, TK_NOT, A, 0);
1231   }
1232   expr(A) ::= expr(A) in_op(N) nm(Y) dbnm(Z) paren_exprlist(E). [IN] {
1233     SrcList *pSrc = sqlite3SrcListAppend(pParse, 0,&Y,&Z);
1234     Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0);
1235     if( E )  sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, E);
1236     A = sqlite3PExpr(pParse, TK_IN, A, 0);
1237     sqlite3PExprAddSelect(pParse, A, pSelect);
1238     if( N ) A = sqlite3PExpr(pParse, TK_NOT, A, 0);
1239   }
1240   expr(A) ::= EXISTS LP select(Y) RP. {
1241     Expr *p;
1242     p = A = sqlite3PExpr(pParse, TK_EXISTS, 0, 0);
1243     sqlite3PExprAddSelect(pParse, p, Y);
1244   }
1245 %endif SQLITE_OMIT_SUBQUERY
1246 
1247 /* CASE expressions */
1248 expr(A) ::= CASE case_operand(X) case_exprlist(Y) case_else(Z) END. {
1249   A = sqlite3PExpr(pParse, TK_CASE, X, 0);
1250   if( A ){
1251     A->x.pList = Z ? sqlite3ExprListAppend(pParse,Y,Z) : Y;
1252     sqlite3ExprSetHeightAndFlags(pParse, A);
1253   }else{
1254     sqlite3ExprListDelete(pParse->db, Y);
1255     sqlite3ExprDelete(pParse->db, Z);
1256   }
1257 }
1258 %type case_exprlist {ExprList*}
1259 %destructor case_exprlist {sqlite3ExprListDelete(pParse->db, $$);}
1260 case_exprlist(A) ::= case_exprlist(A) WHEN expr(Y) THEN expr(Z). {
1261   A = sqlite3ExprListAppend(pParse,A, Y);
1262   A = sqlite3ExprListAppend(pParse,A, Z);
1263 }
1264 case_exprlist(A) ::= WHEN expr(Y) THEN expr(Z). {
1265   A = sqlite3ExprListAppend(pParse,0, Y);
1266   A = sqlite3ExprListAppend(pParse,A, Z);
1267 }
1268 %type case_else {Expr*}
1269 %destructor case_else {sqlite3ExprDelete(pParse->db, $$);}
1270 case_else(A) ::=  ELSE expr(X).         {A = X;}
1271 case_else(A) ::=  .                     {A = 0;}
1272 %type case_operand {Expr*}
1273 %destructor case_operand {sqlite3ExprDelete(pParse->db, $$);}
1274 case_operand(A) ::= expr(X).            {A = X; /*A-overwrites-X*/}
1275 case_operand(A) ::= .                   {A = 0;}
1276 
1277 %type exprlist {ExprList*}
1278 %destructor exprlist {sqlite3ExprListDelete(pParse->db, $$);}
1279 %type nexprlist {ExprList*}
1280 %destructor nexprlist {sqlite3ExprListDelete(pParse->db, $$);}
1281 
1282 exprlist(A) ::= nexprlist(A).
1283 exprlist(A) ::= .                            {A = 0;}
1284 nexprlist(A) ::= nexprlist(A) COMMA expr(Y).
1285     {A = sqlite3ExprListAppend(pParse,A,Y);}
1286 nexprlist(A) ::= expr(Y).
1287     {A = sqlite3ExprListAppend(pParse,0,Y); /*A-overwrites-Y*/}
1288 
1289 %ifndef SQLITE_OMIT_SUBQUERY
1290 /* A paren_exprlist is an optional expression list contained inside
1291 ** of parenthesis */
1292 %type paren_exprlist {ExprList*}
1293 %destructor paren_exprlist {sqlite3ExprListDelete(pParse->db, $$);}
1294 paren_exprlist(A) ::= .   {A = 0;}
1295 paren_exprlist(A) ::= LP exprlist(X) RP.  {A = X;}
1296 %endif SQLITE_OMIT_SUBQUERY
1297 
1298 
1299 ///////////////////////////// The CREATE INDEX command ///////////////////////
1300 //
1301 cmd ::= createkw(S) uniqueflag(U) INDEX ifnotexists(NE) nm(X) dbnm(D)
1302         ON nm(Y) LP sortlist(Z) RP where_opt(W). {
1303   sqlite3CreateIndex(pParse, &X, &D,
1304                      sqlite3SrcListAppend(pParse,0,&Y,0), Z, U,
1305                       &S, W, SQLITE_SO_ASC, NE, SQLITE_IDXTYPE_APPDEF);
1306   if( IN_RENAME_OBJECT && pParse->pNewIndex ){
1307     sqlite3RenameTokenMap(pParse, pParse->pNewIndex->zName, &Y);
1308   }
1309 }
1310 
1311 %type uniqueflag {int}
1312 uniqueflag(A) ::= UNIQUE.  {A = OE_Abort;}
1313 uniqueflag(A) ::= .        {A = OE_None;}
1314 
1315 
1316 // The eidlist non-terminal (Expression Id List) generates an ExprList
1317 // from a list of identifiers.  The identifier names are in ExprList.a[].zName.
1318 // This list is stored in an ExprList rather than an IdList so that it
1319 // can be easily sent to sqlite3ColumnsExprList().
1320 //
1321 // eidlist is grouped with CREATE INDEX because it used to be the non-terminal
1322 // used for the arguments to an index.  That is just an historical accident.
1323 //
1324 // IMPORTANT COMPATIBILITY NOTE:  Some prior versions of SQLite accepted
1325 // COLLATE clauses and ASC or DESC keywords on ID lists in inappropriate
1326 // places - places that might have been stored in the sqlite_master schema.
1327 // Those extra features were ignored.  But because they might be in some
1328 // (busted) old databases, we need to continue parsing them when loading
1329 // historical schemas.
1330 //
1331 %type eidlist {ExprList*}
1332 %destructor eidlist {sqlite3ExprListDelete(pParse->db, $$);}
1333 %type eidlist_opt {ExprList*}
1334 %destructor eidlist_opt {sqlite3ExprListDelete(pParse->db, $$);}
1335 
1336 %include {
1337   /* Add a single new term to an ExprList that is used to store a
1338   ** list of identifiers.  Report an error if the ID list contains
1339   ** a COLLATE clause or an ASC or DESC keyword, except ignore the
1340   ** error while parsing a legacy schema.
1341   */
1342   static ExprList *parserAddExprIdListTerm(
1343     Parse *pParse,
1344     ExprList *pPrior,
1345     Token *pIdToken,
1346     int hasCollate,
1347     int sortOrder
1348   ){
1349     ExprList *p = sqlite3ExprListAppend(pParse, pPrior, 0);
1350     if( (hasCollate || sortOrder!=SQLITE_SO_UNDEFINED)
1351         && pParse->db->init.busy==0
1352     ){
1353       sqlite3ErrorMsg(pParse, "syntax error after column name \"%.*s\"",
1354                          pIdToken->n, pIdToken->z);
1355     }
1356     sqlite3ExprListSetName(pParse, p, pIdToken, 1);
1357     return p;
1358   }
1359 } // end %include
1360 
1361 eidlist_opt(A) ::= .                         {A = 0;}
1362 eidlist_opt(A) ::= LP eidlist(X) RP.         {A = X;}
1363 eidlist(A) ::= eidlist(A) COMMA nm(Y) collate(C) sortorder(Z).  {
1364   A = parserAddExprIdListTerm(pParse, A, &Y, C, Z);
1365 }
1366 eidlist(A) ::= nm(Y) collate(C) sortorder(Z). {
1367   A = parserAddExprIdListTerm(pParse, 0, &Y, C, Z); /*A-overwrites-Y*/
1368 }
1369 
1370 %type collate {int}
1371 collate(C) ::= .              {C = 0;}
1372 collate(C) ::= COLLATE ids.   {C = 1;}
1373 
1374 
1375 ///////////////////////////// The DROP INDEX command /////////////////////////
1376 //
1377 cmd ::= DROP INDEX ifexists(E) fullname(X).   {sqlite3DropIndex(pParse, X, E);}
1378 
1379 ///////////////////////////// The VACUUM command /////////////////////////////
1380 //
1381 %ifndef SQLITE_OMIT_VACUUM
1382 %ifndef SQLITE_OMIT_ATTACH
1383 %type vinto {Expr*}
1384 %destructor vinto {sqlite3ExprDelete(pParse->db, $$);}
1385 cmd ::= VACUUM vinto(Y).                {sqlite3Vacuum(pParse,0,Y);}
1386 cmd ::= VACUUM nm(X) vinto(Y).          {sqlite3Vacuum(pParse,&X,Y);}
1387 vinto(A) ::= INTO expr(X).              {A = X;}
1388 vinto(A) ::= .                          {A = 0;}
1389 %endif  SQLITE_OMIT_ATTACH
1390 %endif  SQLITE_OMIT_VACUUM
1391 
1392 ///////////////////////////// The PRAGMA command /////////////////////////////
1393 //
1394 %ifndef SQLITE_OMIT_PRAGMA
1395 cmd ::= PRAGMA nm(X) dbnm(Z).                {sqlite3Pragma(pParse,&X,&Z,0,0);}
1396 cmd ::= PRAGMA nm(X) dbnm(Z) EQ nmnum(Y).    {sqlite3Pragma(pParse,&X,&Z,&Y,0);}
1397 cmd ::= PRAGMA nm(X) dbnm(Z) LP nmnum(Y) RP. {sqlite3Pragma(pParse,&X,&Z,&Y,0);}
1398 cmd ::= PRAGMA nm(X) dbnm(Z) EQ minus_num(Y).
1399                                              {sqlite3Pragma(pParse,&X,&Z,&Y,1);}
1400 cmd ::= PRAGMA nm(X) dbnm(Z) LP minus_num(Y) RP.
1401                                              {sqlite3Pragma(pParse,&X,&Z,&Y,1);}
1402 
1403 nmnum(A) ::= plus_num(A).
1404 nmnum(A) ::= nm(A).
1405 nmnum(A) ::= ON(A).
1406 nmnum(A) ::= DELETE(A).
1407 nmnum(A) ::= DEFAULT(A).
1408 %endif SQLITE_OMIT_PRAGMA
1409 %token_class number INTEGER|FLOAT.
1410 plus_num(A) ::= PLUS number(X).       {A = X;}
1411 plus_num(A) ::= number(A).
1412 minus_num(A) ::= MINUS number(X).     {A = X;}
1413 //////////////////////////// The CREATE TRIGGER command /////////////////////
1414 
1415 %ifndef SQLITE_OMIT_TRIGGER
1416 
1417 cmd ::= createkw trigger_decl(A) BEGIN trigger_cmd_list(S) END(Z). {
1418   Token all;
1419   all.z = A.z;
1420   all.n = (int)(Z.z - A.z) + Z.n;
1421   sqlite3FinishTrigger(pParse, S, &all);
1422 }
1423 
1424 trigger_decl(A) ::= temp(T) TRIGGER ifnotexists(NOERR) nm(B) dbnm(Z)
1425                     trigger_time(C) trigger_event(D)
1426                     ON fullname(E) foreach_clause when_clause(G). {
1427   sqlite3BeginTrigger(pParse, &B, &Z, C, D.a, D.b, E, G, T, NOERR);
1428   A = (Z.n==0?B:Z); /*A-overwrites-T*/
1429 }
1430 
1431 %type trigger_time {int}
1432 trigger_time(A) ::= BEFORE|AFTER(X).  { A = @X; /*A-overwrites-X*/ }
1433 trigger_time(A) ::= INSTEAD OF.  { A = TK_INSTEAD;}
1434 trigger_time(A) ::= .            { A = TK_BEFORE; }
1435 
1436 %type trigger_event {struct TrigEvent}
1437 %destructor trigger_event {sqlite3IdListDelete(pParse->db, $$.b);}
1438 trigger_event(A) ::= DELETE|INSERT(X).   {A.a = @X; /*A-overwrites-X*/ A.b = 0;}
1439 trigger_event(A) ::= UPDATE(X).          {A.a = @X; /*A-overwrites-X*/ A.b = 0;}
1440 trigger_event(A) ::= UPDATE OF idlist(X).{A.a = TK_UPDATE; A.b = X;}
1441 
1442 foreach_clause ::= .
1443 foreach_clause ::= FOR EACH ROW.
1444 
1445 %type when_clause {Expr*}
1446 %destructor when_clause {sqlite3ExprDelete(pParse->db, $$);}
1447 when_clause(A) ::= .             { A = 0; }
1448 when_clause(A) ::= WHEN expr(X). { A = X; }
1449 
1450 %type trigger_cmd_list {TriggerStep*}
1451 %destructor trigger_cmd_list {sqlite3DeleteTriggerStep(pParse->db, $$);}
1452 trigger_cmd_list(A) ::= trigger_cmd_list(A) trigger_cmd(X) SEMI. {
1453   assert( A!=0 );
1454   A->pLast->pNext = X;
1455   A->pLast = X;
1456 }
1457 trigger_cmd_list(A) ::= trigger_cmd(A) SEMI. {
1458   assert( A!=0 );
1459   A->pLast = A;
1460 }
1461 
1462 // Disallow qualified table names on INSERT, UPDATE, and DELETE statements
1463 // within a trigger.  The table to INSERT, UPDATE, or DELETE is always in
1464 // the same database as the table that the trigger fires on.
1465 //
1466 %type trnm {Token}
1467 trnm(A) ::= nm(A).
1468 trnm(A) ::= nm DOT nm(X). {
1469   A = X;
1470   sqlite3ErrorMsg(pParse,
1471         "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
1472         "statements within triggers");
1473 }
1474 
1475 // Disallow the INDEX BY and NOT INDEXED clauses on UPDATE and DELETE
1476 // statements within triggers.  We make a specific error message for this
1477 // since it is an exception to the default grammar rules.
1478 //
1479 tridxby ::= .
1480 tridxby ::= INDEXED BY nm. {
1481   sqlite3ErrorMsg(pParse,
1482         "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
1483         "within triggers");
1484 }
1485 tridxby ::= NOT INDEXED. {
1486   sqlite3ErrorMsg(pParse,
1487         "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
1488         "within triggers");
1489 }
1490 
1491 
1492 
1493 %type trigger_cmd {TriggerStep*}
1494 %destructor trigger_cmd {sqlite3DeleteTriggerStep(pParse->db, $$);}
1495 // UPDATE
1496 trigger_cmd(A) ::=
1497    UPDATE(B) orconf(R) trnm(X) tridxby SET setlist(Y) where_opt(Z) scanpt(E).
1498    {A = sqlite3TriggerUpdateStep(pParse, &X, Y, Z, R, B.z, E);}
1499 
1500 // INSERT
1501 trigger_cmd(A) ::= scanpt(B) insert_cmd(R) INTO
1502                       trnm(X) idlist_opt(F) select(S) upsert(U) scanpt(Z). {
1503    A = sqlite3TriggerInsertStep(pParse,&X,F,S,R,U,B,Z);/*A-overwrites-R*/
1504 }
1505 // DELETE
1506 trigger_cmd(A) ::= DELETE(B) FROM trnm(X) tridxby where_opt(Y) scanpt(E).
1507    {A = sqlite3TriggerDeleteStep(pParse, &X, Y, B.z, E);}
1508 
1509 // SELECT
1510 trigger_cmd(A) ::= scanpt(B) select(X) scanpt(E).
1511    {A = sqlite3TriggerSelectStep(pParse->db, X, B, E); /*A-overwrites-X*/}
1512 
1513 // The special RAISE expression that may occur in trigger programs
1514 expr(A) ::= RAISE LP IGNORE RP.  {
1515   A = sqlite3PExpr(pParse, TK_RAISE, 0, 0);
1516   if( A ){
1517     A->affExpr = OE_Ignore;
1518   }
1519 }
1520 expr(A) ::= RAISE LP raisetype(T) COMMA nm(Z) RP.  {
1521   A = sqlite3ExprAlloc(pParse->db, TK_RAISE, &Z, 1);
1522   if( A ) {
1523     A->affExpr = (char)T;
1524   }
1525 }
1526 %endif  !SQLITE_OMIT_TRIGGER
1527 
1528 %type raisetype {int}
1529 raisetype(A) ::= ROLLBACK.  {A = OE_Rollback;}
1530 raisetype(A) ::= ABORT.     {A = OE_Abort;}
1531 raisetype(A) ::= FAIL.      {A = OE_Fail;}
1532 
1533 
1534 ////////////////////////  DROP TRIGGER statement //////////////////////////////
1535 %ifndef SQLITE_OMIT_TRIGGER
1536 cmd ::= DROP TRIGGER ifexists(NOERR) fullname(X). {
1537   sqlite3DropTrigger(pParse,X,NOERR);
1538 }
1539 %endif  !SQLITE_OMIT_TRIGGER
1540 
1541 //////////////////////// ATTACH DATABASE file AS name /////////////////////////
1542 %ifndef SQLITE_OMIT_ATTACH
1543 cmd ::= ATTACH database_kw_opt expr(F) AS expr(D) key_opt(K). {
1544   sqlite3Attach(pParse, F, D, K);
1545 }
1546 cmd ::= DETACH database_kw_opt expr(D). {
1547   sqlite3Detach(pParse, D);
1548 }
1549 
1550 %type key_opt {Expr*}
1551 %destructor key_opt {sqlite3ExprDelete(pParse->db, $$);}
1552 key_opt(A) ::= .                     { A = 0; }
1553 key_opt(A) ::= KEY expr(X).          { A = X; }
1554 
1555 database_kw_opt ::= DATABASE.
1556 database_kw_opt ::= .
1557 %endif SQLITE_OMIT_ATTACH
1558 
1559 ////////////////////////// REINDEX collation //////////////////////////////////
1560 %ifndef SQLITE_OMIT_REINDEX
1561 cmd ::= REINDEX.                {sqlite3Reindex(pParse, 0, 0);}
1562 cmd ::= REINDEX nm(X) dbnm(Y).  {sqlite3Reindex(pParse, &X, &Y);}
1563 %endif  SQLITE_OMIT_REINDEX
1564 
1565 /////////////////////////////////// ANALYZE ///////////////////////////////////
1566 %ifndef SQLITE_OMIT_ANALYZE
1567 cmd ::= ANALYZE.                {sqlite3Analyze(pParse, 0, 0);}
1568 cmd ::= ANALYZE nm(X) dbnm(Y).  {sqlite3Analyze(pParse, &X, &Y);}
1569 %endif
1570 
1571 //////////////////////// ALTER TABLE table ... ////////////////////////////////
1572 %ifndef SQLITE_OMIT_ALTERTABLE
1573 cmd ::= ALTER TABLE fullname(X) RENAME TO nm(Z). {
1574   sqlite3AlterRenameTable(pParse,X,&Z);
1575 }
1576 cmd ::= ALTER TABLE add_column_fullname
1577         ADD kwcolumn_opt columnname(Y) carglist. {
1578   Y.n = (int)(pParse->sLastToken.z-Y.z) + pParse->sLastToken.n;
1579   sqlite3AlterFinishAddColumn(pParse, &Y);
1580 }
1581 add_column_fullname ::= fullname(X). {
1582   disableLookaside(pParse);
1583   sqlite3AlterBeginAddColumn(pParse, X);
1584 }
1585 cmd ::= ALTER TABLE fullname(X) RENAME kwcolumn_opt nm(Y) TO nm(Z). {
1586   sqlite3AlterRenameColumn(pParse, X, &Y, &Z);
1587 }
1588 
1589 kwcolumn_opt ::= .
1590 kwcolumn_opt ::= COLUMNKW.
1591 
1592 %endif  SQLITE_OMIT_ALTERTABLE
1593 
1594 //////////////////////// CREATE VIRTUAL TABLE ... /////////////////////////////
1595 %ifndef SQLITE_OMIT_VIRTUALTABLE
1596 cmd ::= create_vtab.                       {sqlite3VtabFinishParse(pParse,0);}
1597 cmd ::= create_vtab LP vtabarglist RP(X).  {sqlite3VtabFinishParse(pParse,&X);}
1598 create_vtab ::= createkw VIRTUAL TABLE ifnotexists(E)
1599                 nm(X) dbnm(Y) USING nm(Z). {
1600     sqlite3VtabBeginParse(pParse, &X, &Y, &Z, E);
1601 }
1602 vtabarglist ::= vtabarg.
1603 vtabarglist ::= vtabarglist COMMA vtabarg.
1604 vtabarg ::= .                       {sqlite3VtabArgInit(pParse);}
1605 vtabarg ::= vtabarg vtabargtoken.
1606 vtabargtoken ::= ANY(X).            {sqlite3VtabArgExtend(pParse,&X);}
1607 vtabargtoken ::= lp anylist RP(X).  {sqlite3VtabArgExtend(pParse,&X);}
1608 lp ::= LP(X).                       {sqlite3VtabArgExtend(pParse,&X);}
1609 anylist ::= .
1610 anylist ::= anylist LP anylist RP.
1611 anylist ::= anylist ANY.
1612 %endif  SQLITE_OMIT_VIRTUALTABLE
1613 
1614 
1615 //////////////////////// COMMON TABLE EXPRESSIONS ////////////////////////////
1616 %type wqlist {With*}
1617 %destructor wqlist {sqlite3WithDelete(pParse->db, $$);}
1618 
1619 with ::= .
1620 %ifndef SQLITE_OMIT_CTE
1621 with ::= WITH wqlist(W).              { sqlite3WithPush(pParse, W, 1); }
1622 with ::= WITH RECURSIVE wqlist(W).    { sqlite3WithPush(pParse, W, 1); }
1623 
1624 wqlist(A) ::= nm(X) eidlist_opt(Y) AS LP select(Z) RP. {
1625   A = sqlite3WithAdd(pParse, 0, &X, Y, Z); /*A-overwrites-X*/
1626 }
1627 wqlist(A) ::= wqlist(A) COMMA nm(X) eidlist_opt(Y) AS LP select(Z) RP. {
1628   A = sqlite3WithAdd(pParse, A, &X, Y, Z);
1629 }
1630 %endif  SQLITE_OMIT_CTE
1631 
1632 //////////////////////// WINDOW FUNCTION EXPRESSIONS /////////////////////////
1633 // These must be at the end of this file. Specifically, the rules that
1634 // introduce tokens WINDOW, OVER and FILTER must appear last. This causes
1635 // the integer values assigned to these tokens to be larger than all other
1636 // tokens that may be output by the tokenizer except TK_SPACE and TK_ILLEGAL.
1637 //
1638 %ifndef SQLITE_OMIT_WINDOWFUNC
1639 %type windowdefn_list {Window*}
1640 %destructor windowdefn_list {sqlite3WindowListDelete(pParse->db, $$);}
1641 windowdefn_list(A) ::= windowdefn(Z). { A = Z; }
1642 windowdefn_list(A) ::= windowdefn_list(Y) COMMA windowdefn(Z). {
1643   assert( Z!=0 );
1644   sqlite3WindowChain(pParse, Z, Y);
1645   Z->pNextWin = Y;
1646   A = Z;
1647 }
1648 
1649 %type windowdefn {Window*}
1650 %destructor windowdefn {sqlite3WindowDelete(pParse->db, $$);}
1651 windowdefn(A) ::= nm(X) AS LP window(Y) RP. {
1652   if( ALWAYS(Y) ){
1653     Y->zName = sqlite3DbStrNDup(pParse->db, X.z, X.n);
1654   }
1655   A = Y;
1656 }
1657 
1658 %type window {Window*}
1659 %destructor window {sqlite3WindowDelete(pParse->db, $$);}
1660 
1661 %type frame_opt {Window*}
1662 %destructor frame_opt {sqlite3WindowDelete(pParse->db, $$);}
1663 
1664 %type part_opt {ExprList*}
1665 %destructor part_opt {sqlite3ExprListDelete(pParse->db, $$);}
1666 
1667 %type filter_clause {Expr*}
1668 %destructor filter_clause {sqlite3ExprDelete(pParse->db, $$);}
1669 
1670 %type over_clause {Window*}
1671 %destructor over_clause {sqlite3WindowDelete(pParse->db, $$);}
1672 
1673 %type filter_over {Window*}
1674 %destructor filter_over {sqlite3WindowDelete(pParse->db, $$);}
1675 
1676 %type range_or_rows {int}
1677 
1678 %type frame_bound {struct FrameBound}
1679 %destructor frame_bound {sqlite3ExprDelete(pParse->db, $$.pExpr);}
1680 %type frame_bound_s {struct FrameBound}
1681 %destructor frame_bound_s {sqlite3ExprDelete(pParse->db, $$.pExpr);}
1682 %type frame_bound_e {struct FrameBound}
1683 %destructor frame_bound_e {sqlite3ExprDelete(pParse->db, $$.pExpr);}
1684 
1685 window(A) ::= PARTITION BY nexprlist(X) orderby_opt(Y) frame_opt(Z). {
1686   A = sqlite3WindowAssemble(pParse, Z, X, Y, 0);
1687 }
1688 window(A) ::= nm(W) PARTITION BY nexprlist(X) orderby_opt(Y) frame_opt(Z). {
1689   A = sqlite3WindowAssemble(pParse, Z, X, Y, &W);
1690 }
1691 window(A) ::= ORDER BY sortlist(Y) frame_opt(Z). {
1692   A = sqlite3WindowAssemble(pParse, Z, 0, Y, 0);
1693 }
1694 window(A) ::= nm(W) ORDER BY sortlist(Y) frame_opt(Z). {
1695   A = sqlite3WindowAssemble(pParse, Z, 0, Y, &W);
1696 }
1697 window(A) ::= frame_opt(Z). {
1698   A = Z;
1699 }
1700 window(A) ::= nm(W) frame_opt(Z). {
1701   A = sqlite3WindowAssemble(pParse, Z, 0, 0, &W);
1702 }
1703 
1704 frame_opt(A) ::= .                             {
1705   A = sqlite3WindowAlloc(pParse, 0, TK_UNBOUNDED, 0, TK_CURRENT, 0, 0);
1706 }
1707 frame_opt(A) ::= range_or_rows(X) frame_bound_s(Y) frame_exclude_opt(Z). {
1708   A = sqlite3WindowAlloc(pParse, X, Y.eType, Y.pExpr, TK_CURRENT, 0, Z);
1709 }
1710 frame_opt(A) ::= range_or_rows(X) BETWEEN frame_bound_s(Y) AND
1711                           frame_bound_e(Z) frame_exclude_opt(W). {
1712   A = sqlite3WindowAlloc(pParse, X, Y.eType, Y.pExpr, Z.eType, Z.pExpr, W);
1713 }
1714 
1715 range_or_rows(A) ::= RANGE|ROWS|GROUPS(X).   {A = @X; /*A-overwrites-X*/}
1716 
1717 frame_bound_s(A) ::= frame_bound(X).         {A = X;}
1718 frame_bound_s(A) ::= UNBOUNDED(X) PRECEDING. {A.eType = @X; A.pExpr = 0;}
1719 frame_bound_e(A) ::= frame_bound(X).         {A = X;}
1720 frame_bound_e(A) ::= UNBOUNDED(X) FOLLOWING. {A.eType = @X; A.pExpr = 0;}
1721 
1722 frame_bound(A) ::= expr(X) PRECEDING|FOLLOWING(Y).
1723                                              {A.eType = @Y; A.pExpr = X;}
1724 frame_bound(A) ::= CURRENT(X) ROW.           {A.eType = @X; A.pExpr = 0;}
1725 
1726 %type frame_exclude_opt {u8}
1727 frame_exclude_opt(A) ::= . {A = 0;}
1728 frame_exclude_opt(A) ::= EXCLUDE frame_exclude(X). {A = X;}
1729 
1730 %type frame_exclude {u8}
1731 frame_exclude(A) ::= NO(X) OTHERS.   {A = @X; /*A-overwrites-X*/}
1732 frame_exclude(A) ::= CURRENT(X) ROW. {A = @X; /*A-overwrites-X*/}
1733 frame_exclude(A) ::= GROUP|TIES(X).  {A = @X; /*A-overwrites-X*/}
1734 
1735 
1736 %type window_clause {Window*}
1737 %destructor window_clause {sqlite3WindowListDelete(pParse->db, $$);}
1738 window_clause(A) ::= WINDOW windowdefn_list(B). { A = B; }
1739 
1740 filter_over(A) ::= filter_clause(F) over_clause(O). {
1741   O->pFilter = F;
1742   A = O;
1743 }
1744 filter_over(A) ::= over_clause(O). {
1745   A = O;
1746 }
1747 filter_over(A) ::= filter_clause(F). {
1748   A = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
1749   if( A ){
1750     A->eFrmType = TK_FILTER;
1751     A->pFilter = F;
1752   }else{
1753     sqlite3ExprDelete(pParse->db, F);
1754   }
1755 }
1756 
1757 over_clause(A) ::= OVER LP window(Z) RP. {
1758   A = Z;
1759   assert( A!=0 );
1760 }
1761 over_clause(A) ::= OVER nm(Z). {
1762   A = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
1763   if( A ){
1764     A->zName = sqlite3DbStrNDup(pParse->db, Z.z, Z.n);
1765   }
1766 }
1767 
1768 filter_clause(A) ::= FILTER LP WHERE expr(X) RP.  { A = X; }
1769 %endif /* SQLITE_OMIT_WINDOWFUNC */
1770 
1771 /*
1772 ** The code generator needs some extra TK_ token values for tokens that
1773 ** are synthesized and do not actually appear in the grammar:
1774 */
1775 %token
1776   TRUEFALSE       /* True or false keyword */
1777   ISNOT           /* Combination of IS and NOT */
1778   FUNCTION        /* A function invocation */
1779   COLUMN          /* Reference to a table column */
1780   AGG_FUNCTION    /* An aggregate function */
1781   AGG_COLUMN      /* An aggregated column */
1782   UMINUS          /* Unary minus */
1783   UPLUS           /* Unary plus */
1784   TRUTH           /* IS TRUE or IS FALSE or IS NOT TRUE or IS NOT FALSE */
1785   REGISTER        /* Reference to a VDBE register */
1786   VECTOR          /* Vector */
1787   SELECT_COLUMN   /* Choose a single column from a multi-column SELECT */
1788   IF_NULL_ROW     /* the if-null-row operator */
1789   ASTERISK        /* The "*" in count(*) and similar */
1790   SPAN            /* The span operator */
1791 .
1792 /* There must be no more than 255 tokens defined above.  If this grammar
1793 ** is extended with new rules and tokens, they must either be so few in
1794 ** number that TK_SPAN is no more than 255, or else the new tokens must
1795 ** appear after this line.
1796 */
1797 %include {
1798 #if TK_SPAN>255
1799 # error too many tokens in the grammar
1800 #endif
1801 }
1802 
1803 /*
1804 ** The TK_SPACE and TK_ILLEGAL tokens must be the last two tokens.  The
1805 ** parser depends on this.  Those tokens are not used in any grammar rule.
1806 ** They are only used by the tokenizer.  Declare them last so that they
1807 ** are guaranteed to be the last two tokens
1808 */
1809 %token SPACE ILLEGAL.
1810