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