xref: /sqlite-3.40.0/src/parse.y (revision 1e25d20c)
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   /* Attach a With object describing the WITH clause to a Select
515   ** object describing the query for which the WITH clause is a prefix.
516   */
517   static Select *attachWithToSelect(Parse *pParse, Select *pSelect, With *pWith){
518     if( pSelect ){
519       pSelect->pWith = pWith;
520       parserDoubleLinkSelect(pParse, pSelect);
521     }else{
522       sqlite3WithDelete(pParse->db, pWith);
523     }
524     return pSelect;
525   }
526 }
527 
528 %ifndef SQLITE_OMIT_CTE
529 select(A) ::= WITH wqlist(W) selectnowith(X). {A = attachWithToSelect(pParse,X,W);}
530 select(A) ::= WITH RECURSIVE wqlist(W) selectnowith(X).
531                                               {A = attachWithToSelect(pParse,X,W);}
532 %endif /* SQLITE_OMIT_CTE */
533 select(A) ::= selectnowith(X). {
534   Select *p = X;
535   if( p ){
536     parserDoubleLinkSelect(pParse, p);
537   }
538   A = p; /*A-overwrites-X*/
539 }
540 
541 selectnowith(A) ::= oneselect(A).
542 %ifndef SQLITE_OMIT_COMPOUND_SELECT
543 selectnowith(A) ::= selectnowith(A) multiselect_op(Y) oneselect(Z).  {
544   Select *pRhs = Z;
545   Select *pLhs = A;
546   if( pRhs && pRhs->pPrior ){
547     SrcList *pFrom;
548     Token x;
549     x.n = 0;
550     parserDoubleLinkSelect(pParse, pRhs);
551     pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
552     pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0);
553   }
554   if( pRhs ){
555     pRhs->op = (u8)Y;
556     pRhs->pPrior = pLhs;
557     if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue;
558     pRhs->selFlags &= ~SF_MultiValue;
559     if( Y!=TK_ALL ) pParse->hasCompound = 1;
560   }else{
561     sqlite3SelectDelete(pParse->db, pLhs);
562   }
563   A = pRhs;
564 }
565 %type multiselect_op {int}
566 multiselect_op(A) ::= UNION(OP).             {A = @OP; /*A-overwrites-OP*/}
567 multiselect_op(A) ::= UNION ALL.             {A = TK_ALL;}
568 multiselect_op(A) ::= EXCEPT|INTERSECT(OP).  {A = @OP; /*A-overwrites-OP*/}
569 %endif SQLITE_OMIT_COMPOUND_SELECT
570 
571 oneselect(A) ::= SELECT distinct(D) selcollist(W) from(X) where_opt(Y)
572                  groupby_opt(P) having_opt(Q)
573                  orderby_opt(Z) limit_opt(L). {
574   A = sqlite3SelectNew(pParse,W,X,Y,P,Q,Z,D,L);
575 }
576 %ifndef SQLITE_OMIT_WINDOWFUNC
577 oneselect(A) ::= SELECT distinct(D) selcollist(W) from(X) where_opt(Y)
578                  groupby_opt(P) having_opt(Q) window_clause(R)
579                  orderby_opt(Z) limit_opt(L). {
580   A = sqlite3SelectNew(pParse,W,X,Y,P,Q,Z,D,L);
581   if( A ){
582     A->pWinDefn = R;
583   }else{
584     sqlite3WindowListDelete(pParse->db, R);
585   }
586 }
587 %endif
588 
589 
590 oneselect(A) ::= values(A).
591 
592 %type values {Select*}
593 %destructor values {sqlite3SelectDelete(pParse->db, $$);}
594 values(A) ::= VALUES LP nexprlist(X) RP. {
595   A = sqlite3SelectNew(pParse,X,0,0,0,0,0,SF_Values,0);
596 }
597 values(A) ::= values(A) COMMA LP nexprlist(Y) RP. {
598   Select *pRight, *pLeft = A;
599   pRight = sqlite3SelectNew(pParse,Y,0,0,0,0,0,SF_Values|SF_MultiValue,0);
600   if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue;
601   if( pRight ){
602     pRight->op = TK_ALL;
603     pRight->pPrior = pLeft;
604     A = pRight;
605   }else{
606     A = pLeft;
607   }
608 }
609 
610 // The "distinct" nonterminal is true (1) if the DISTINCT keyword is
611 // present and false (0) if it is not.
612 //
613 %type distinct {int}
614 distinct(A) ::= DISTINCT.   {A = SF_Distinct;}
615 distinct(A) ::= ALL.        {A = SF_All;}
616 distinct(A) ::= .           {A = 0;}
617 
618 // selcollist is a list of expressions that are to become the return
619 // values of the SELECT statement.  The "*" in statements like
620 // "SELECT * FROM ..." is encoded as a special expression with an
621 // opcode of TK_ASTERISK.
622 //
623 %type selcollist {ExprList*}
624 %destructor selcollist {sqlite3ExprListDelete(pParse->db, $$);}
625 %type sclp {ExprList*}
626 %destructor sclp {sqlite3ExprListDelete(pParse->db, $$);}
627 sclp(A) ::= selcollist(A) COMMA.
628 sclp(A) ::= .                                {A = 0;}
629 selcollist(A) ::= sclp(A) scanpt(B) expr(X) scanpt(Z) as(Y).     {
630    A = sqlite3ExprListAppend(pParse, A, X);
631    if( Y.n>0 ) sqlite3ExprListSetName(pParse, A, &Y, 1);
632    sqlite3ExprListSetSpan(pParse,A,B,Z);
633 }
634 selcollist(A) ::= sclp(A) scanpt STAR. {
635   Expr *p = sqlite3Expr(pParse->db, TK_ASTERISK, 0);
636   A = sqlite3ExprListAppend(pParse, A, p);
637 }
638 selcollist(A) ::= sclp(A) scanpt nm(X) DOT STAR. {
639   Expr *pRight = sqlite3PExpr(pParse, TK_ASTERISK, 0, 0);
640   Expr *pLeft = sqlite3ExprAlloc(pParse->db, TK_ID, &X, 1);
641   Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
642   A = sqlite3ExprListAppend(pParse,A, pDot);
643 }
644 
645 // An option "AS <id>" phrase that can follow one of the expressions that
646 // define the result set, or one of the tables in the FROM clause.
647 //
648 %type as {Token}
649 as(X) ::= AS nm(Y).    {X = Y;}
650 as(X) ::= ids(X).
651 as(X) ::= .            {X.n = 0; X.z = 0;}
652 
653 
654 %type seltablist {SrcList*}
655 %destructor seltablist {sqlite3SrcListDelete(pParse->db, $$);}
656 %type stl_prefix {SrcList*}
657 %destructor stl_prefix {sqlite3SrcListDelete(pParse->db, $$);}
658 %type from {SrcList*}
659 %destructor from {sqlite3SrcListDelete(pParse->db, $$);}
660 
661 // A complete FROM clause.
662 //
663 from(A) ::= .                {A = 0;}
664 from(A) ::= FROM seltablist(X). {
665   A = X;
666   sqlite3SrcListShiftJoinType(A);
667 }
668 
669 // "seltablist" is a "Select Table List" - the content of the FROM clause
670 // in a SELECT statement.  "stl_prefix" is a prefix of this list.
671 //
672 stl_prefix(A) ::= seltablist(A) joinop(Y).    {
673    if( ALWAYS(A && A->nSrc>0) ) A->a[A->nSrc-1].fg.jointype = (u8)Y;
674 }
675 stl_prefix(A) ::= .                           {A = 0;}
676 seltablist(A) ::= stl_prefix(A) nm(Y) dbnm(D) as(Z) indexed_opt(I)
677                   on_opt(N) using_opt(U). {
678   A = sqlite3SrcListAppendFromTerm(pParse,A,&Y,&D,&Z,0,N,U);
679   sqlite3SrcListIndexedBy(pParse, A, &I);
680 }
681 seltablist(A) ::= stl_prefix(A) nm(Y) dbnm(D) LP exprlist(E) RP as(Z)
682                   on_opt(N) using_opt(U). {
683   A = sqlite3SrcListAppendFromTerm(pParse,A,&Y,&D,&Z,0,N,U);
684   sqlite3SrcListFuncArgs(pParse, A, E);
685 }
686 %ifndef SQLITE_OMIT_SUBQUERY
687   seltablist(A) ::= stl_prefix(A) LP select(S) RP
688                     as(Z) on_opt(N) using_opt(U). {
689     A = sqlite3SrcListAppendFromTerm(pParse,A,0,0,&Z,S,N,U);
690   }
691   seltablist(A) ::= stl_prefix(A) LP seltablist(F) RP
692                     as(Z) on_opt(N) using_opt(U). {
693     if( A==0 && Z.n==0 && N==0 && U==0 ){
694       A = F;
695     }else if( F->nSrc==1 ){
696       A = sqlite3SrcListAppendFromTerm(pParse,A,0,0,&Z,0,N,U);
697       if( A ){
698         struct SrcList_item *pNew = &A->a[A->nSrc-1];
699         struct SrcList_item *pOld = F->a;
700         pNew->zName = pOld->zName;
701         pNew->zDatabase = pOld->zDatabase;
702         pNew->pSelect = pOld->pSelect;
703         if( pOld->fg.isTabFunc ){
704           pNew->u1.pFuncArg = pOld->u1.pFuncArg;
705           pOld->u1.pFuncArg = 0;
706           pOld->fg.isTabFunc = 0;
707           pNew->fg.isTabFunc = 1;
708         }
709         pOld->zName = pOld->zDatabase = 0;
710         pOld->pSelect = 0;
711       }
712       sqlite3SrcListDelete(pParse->db, F);
713     }else{
714       Select *pSubquery;
715       sqlite3SrcListShiftJoinType(F);
716       pSubquery = sqlite3SelectNew(pParse,0,F,0,0,0,0,SF_NestedFrom,0);
717       A = sqlite3SrcListAppendFromTerm(pParse,A,0,0,&Z,pSubquery,N,U);
718     }
719   }
720 %endif  SQLITE_OMIT_SUBQUERY
721 
722 %type dbnm {Token}
723 dbnm(A) ::= .          {A.z=0; A.n=0;}
724 dbnm(A) ::= DOT nm(X). {A = X;}
725 
726 %type fullname {SrcList*}
727 %destructor fullname {sqlite3SrcListDelete(pParse->db, $$);}
728 fullname(A) ::= nm(X).  {
729   A = sqlite3SrcListAppend(pParse,0,&X,0);
730   if( IN_RENAME_OBJECT && A ) sqlite3RenameTokenMap(pParse, A->a[0].zName, &X);
731 }
732 fullname(A) ::= nm(X) DOT nm(Y). {
733   A = sqlite3SrcListAppend(pParse,0,&X,&Y);
734   if( IN_RENAME_OBJECT && A ) sqlite3RenameTokenMap(pParse, A->a[0].zName, &Y);
735 }
736 
737 %type xfullname {SrcList*}
738 %destructor xfullname {sqlite3SrcListDelete(pParse->db, $$);}
739 xfullname(A) ::= nm(X).
740    {A = sqlite3SrcListAppend(pParse,0,&X,0); /*A-overwrites-X*/}
741 xfullname(A) ::= nm(X) DOT nm(Y).
742    {A = sqlite3SrcListAppend(pParse,0,&X,&Y); /*A-overwrites-X*/}
743 xfullname(A) ::= nm(X) DOT nm(Y) AS nm(Z).  {
744    A = sqlite3SrcListAppend(pParse,0,&X,&Y); /*A-overwrites-X*/
745    if( A ) A->a[0].zAlias = sqlite3NameFromToken(pParse->db, &Z);
746 }
747 xfullname(A) ::= nm(X) AS nm(Z). {
748    A = sqlite3SrcListAppend(pParse,0,&X,0); /*A-overwrites-X*/
749    if( A ) A->a[0].zAlias = sqlite3NameFromToken(pParse->db, &Z);
750 }
751 
752 %type joinop {int}
753 joinop(X) ::= COMMA|JOIN.              { X = JT_INNER; }
754 joinop(X) ::= JOIN_KW(A) JOIN.
755                   {X = sqlite3JoinType(pParse,&A,0,0);  /*X-overwrites-A*/}
756 joinop(X) ::= JOIN_KW(A) nm(B) JOIN.
757                   {X = sqlite3JoinType(pParse,&A,&B,0); /*X-overwrites-A*/}
758 joinop(X) ::= JOIN_KW(A) nm(B) nm(C) JOIN.
759                   {X = sqlite3JoinType(pParse,&A,&B,&C);/*X-overwrites-A*/}
760 
761 // There is a parsing abiguity in an upsert statement that uses a
762 // SELECT on the RHS of a the INSERT:
763 //
764 //      INSERT INTO tab SELECT * FROM aaa JOIN bbb ON CONFLICT ...
765 //                                        here ----^^
766 //
767 // When the ON token is encountered, the parser does not know if it is
768 // the beginning of an ON CONFLICT clause, or the beginning of an ON
769 // clause associated with the JOIN.  The conflict is resolved in favor
770 // of the JOIN.  If an ON CONFLICT clause is intended, insert a dummy
771 // WHERE clause in between, like this:
772 //
773 //      INSERT INTO tab SELECT * FROM aaa JOIN bbb WHERE true ON CONFLICT ...
774 //
775 // The [AND] and [OR] precedence marks in the rules for on_opt cause the
776 // ON in this context to always be interpreted as belonging to the JOIN.
777 //
778 %type on_opt {Expr*}
779 %destructor on_opt {sqlite3ExprDelete(pParse->db, $$);}
780 on_opt(N) ::= ON expr(E).  {N = E;}
781 on_opt(N) ::= .     [OR]   {N = 0;}
782 
783 // Note that this block abuses the Token type just a little. If there is
784 // no "INDEXED BY" clause, the returned token is empty (z==0 && n==0). If
785 // there is an INDEXED BY clause, then the token is populated as per normal,
786 // with z pointing to the token data and n containing the number of bytes
787 // in the token.
788 //
789 // If there is a "NOT INDEXED" clause, then (z==0 && n==1), which is
790 // normally illegal. The sqlite3SrcListIndexedBy() function
791 // recognizes and interprets this as a special case.
792 //
793 %type indexed_opt {Token}
794 indexed_opt(A) ::= .                 {A.z=0; A.n=0;}
795 indexed_opt(A) ::= INDEXED BY nm(X). {A = X;}
796 indexed_opt(A) ::= NOT INDEXED.      {A.z=0; A.n=1;}
797 
798 %type using_opt {IdList*}
799 %destructor using_opt {sqlite3IdListDelete(pParse->db, $$);}
800 using_opt(U) ::= USING LP idlist(L) RP.  {U = L;}
801 using_opt(U) ::= .                        {U = 0;}
802 
803 
804 %type orderby_opt {ExprList*}
805 %destructor orderby_opt {sqlite3ExprListDelete(pParse->db, $$);}
806 
807 // the sortlist non-terminal stores a list of expression where each
808 // expression is optionally followed by ASC or DESC to indicate the
809 // sort order.
810 //
811 %type sortlist {ExprList*}
812 %destructor sortlist {sqlite3ExprListDelete(pParse->db, $$);}
813 
814 orderby_opt(A) ::= .                          {A = 0;}
815 orderby_opt(A) ::= ORDER BY sortlist(X).      {A = X;}
816 sortlist(A) ::= sortlist(A) COMMA expr(Y) sortorder(Z) nulls(X). {
817   A = sqlite3ExprListAppend(pParse,A,Y);
818   sqlite3ExprListSetSortOrder(A,Z,X);
819 }
820 sortlist(A) ::= expr(Y) sortorder(Z) nulls(X). {
821   A = sqlite3ExprListAppend(pParse,0,Y); /*A-overwrites-Y*/
822   sqlite3ExprListSetSortOrder(A,Z,X);
823 }
824 
825 %type sortorder {int}
826 
827 sortorder(A) ::= ASC.           {A = SQLITE_SO_ASC;}
828 sortorder(A) ::= DESC.          {A = SQLITE_SO_DESC;}
829 sortorder(A) ::= .              {A = SQLITE_SO_UNDEFINED;}
830 
831 %type nulls {int}
832 nulls(A) ::= NULLS FIRST.       {A = SQLITE_SO_ASC;}
833 nulls(A) ::= NULLS LAST.        {A = SQLITE_SO_DESC;}
834 nulls(A) ::= .                  {A = SQLITE_SO_UNDEFINED;}
835 
836 %type groupby_opt {ExprList*}
837 %destructor groupby_opt {sqlite3ExprListDelete(pParse->db, $$);}
838 groupby_opt(A) ::= .                      {A = 0;}
839 groupby_opt(A) ::= GROUP BY nexprlist(X). {A = X;}
840 
841 %type having_opt {Expr*}
842 %destructor having_opt {sqlite3ExprDelete(pParse->db, $$);}
843 having_opt(A) ::= .                {A = 0;}
844 having_opt(A) ::= HAVING expr(X).  {A = X;}
845 
846 %type limit_opt {Expr*}
847 
848 // The destructor for limit_opt will never fire in the current grammar.
849 // The limit_opt non-terminal only occurs at the end of a single production
850 // rule for SELECT statements.  As soon as the rule that create the
851 // limit_opt non-terminal reduces, the SELECT statement rule will also
852 // reduce.  So there is never a limit_opt non-terminal on the stack
853 // except as a transient.  So there is never anything to destroy.
854 //
855 //%destructor limit_opt {sqlite3ExprDelete(pParse->db, $$);}
856 limit_opt(A) ::= .       {A = 0;}
857 limit_opt(A) ::= LIMIT expr(X).
858                          {A = sqlite3PExpr(pParse,TK_LIMIT,X,0);}
859 limit_opt(A) ::= LIMIT expr(X) OFFSET expr(Y).
860                          {A = sqlite3PExpr(pParse,TK_LIMIT,X,Y);}
861 limit_opt(A) ::= LIMIT expr(X) COMMA expr(Y).
862                          {A = sqlite3PExpr(pParse,TK_LIMIT,Y,X);}
863 
864 /////////////////////////// The DELETE statement /////////////////////////////
865 //
866 %if SQLITE_ENABLE_UPDATE_DELETE_LIMIT || SQLITE_UDL_CAPABLE_PARSER
867 cmd ::= with DELETE FROM xfullname(X) indexed_opt(I) where_opt_ret(W)
868         orderby_opt(O) limit_opt(L). {
869   sqlite3SrcListIndexedBy(pParse, X, &I);
870 #ifndef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
871   if( O || L ){
872     updateDeleteLimitError(pParse,O,L);
873     O = 0;
874     L = 0;
875   }
876 #endif
877   sqlite3DeleteFrom(pParse,X,W,O,L);
878 }
879 %else
880 cmd ::= with DELETE FROM xfullname(X) indexed_opt(I) where_opt_ret(W). {
881   sqlite3SrcListIndexedBy(pParse, X, &I);
882   sqlite3DeleteFrom(pParse,X,W,0,0);
883 }
884 %endif
885 
886 %type where_opt {Expr*}
887 %destructor where_opt {sqlite3ExprDelete(pParse->db, $$);}
888 %type where_opt_ret {Expr*}
889 %destructor where_opt_ret {sqlite3ExprDelete(pParse->db, $$);}
890 
891 where_opt(A) ::= .                    {A = 0;}
892 where_opt(A) ::= WHERE expr(X).       {A = X;}
893 where_opt_ret(A) ::= .                                      {A = 0;}
894 where_opt_ret(A) ::= WHERE expr(X).                         {A = X;}
895 where_opt_ret(A) ::= RETURNING selcollist(X).
896        {sqlite3AddReturning(pParse,X); A = 0;}
897 where_opt_ret(A) ::= WHERE expr(X) RETURNING selcollist(Y).
898        {sqlite3AddReturning(pParse,Y); A = X;}
899 
900 ////////////////////////// The UPDATE command ////////////////////////////////
901 //
902 %if SQLITE_ENABLE_UPDATE_DELETE_LIMIT || SQLITE_UDL_CAPABLE_PARSER
903 cmd ::= with UPDATE orconf(R) xfullname(X) indexed_opt(I) SET setlist(Y) from(F)
904         where_opt_ret(W) orderby_opt(O) limit_opt(L).  {
905   sqlite3SrcListIndexedBy(pParse, X, &I);
906   X = sqlite3SrcListAppendList(pParse, X, F);
907   sqlite3ExprListCheckLength(pParse,Y,"set list");
908 #ifndef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
909   if( O || L ){
910     updateDeleteLimitError(pParse,O,L);
911     O = 0;
912     L = 0;
913   }
914 #endif
915   sqlite3Update(pParse,X,Y,W,R,O,L,0);
916 }
917 %else
918 cmd ::= with UPDATE orconf(R) xfullname(X) indexed_opt(I) SET setlist(Y) from(F)
919         where_opt_ret(W). {
920   sqlite3SrcListIndexedBy(pParse, X, &I);
921   sqlite3ExprListCheckLength(pParse,Y,"set list");
922   X = sqlite3SrcListAppendList(pParse, X, F);
923   sqlite3Update(pParse,X,Y,W,R,0,0,0);
924 }
925 %endif
926 
927 
928 
929 %type setlist {ExprList*}
930 %destructor setlist {sqlite3ExprListDelete(pParse->db, $$);}
931 
932 setlist(A) ::= setlist(A) COMMA nm(X) EQ expr(Y). {
933   A = sqlite3ExprListAppend(pParse, A, Y);
934   sqlite3ExprListSetName(pParse, A, &X, 1);
935 }
936 setlist(A) ::= setlist(A) COMMA LP idlist(X) RP EQ expr(Y). {
937   A = sqlite3ExprListAppendVector(pParse, A, X, Y);
938 }
939 setlist(A) ::= nm(X) EQ expr(Y). {
940   A = sqlite3ExprListAppend(pParse, 0, Y);
941   sqlite3ExprListSetName(pParse, A, &X, 1);
942 }
943 setlist(A) ::= LP idlist(X) RP EQ expr(Y). {
944   A = sqlite3ExprListAppendVector(pParse, 0, X, Y);
945 }
946 
947 ////////////////////////// The INSERT command /////////////////////////////////
948 //
949 cmd ::= with insert_cmd(R) INTO xfullname(X) idlist_opt(F) select(S)
950         upsert(U). {
951   sqlite3Insert(pParse, X, S, F, R, U);
952 }
953 cmd ::= with insert_cmd(R) INTO xfullname(X) idlist_opt(F) DEFAULT VALUES returning.
954 {
955   sqlite3Insert(pParse, X, 0, F, R, 0);
956 }
957 
958 %type upsert {Upsert*}
959 
960 // Because upsert only occurs at the tip end of the INSERT rule for cmd,
961 // there is never a case where the value of the upsert pointer will not
962 // be destroyed by the cmd action.  So comment-out the destructor to
963 // avoid unreachable code.
964 //%destructor upsert {sqlite3UpsertDelete(pParse->db,$$);}
965 upsert(A) ::= . { A = 0; }
966 upsert(A) ::= RETURNING selcollist(X).  { A = 0; sqlite3AddReturning(pParse,X); }
967 upsert(A) ::= ON CONFLICT LP sortlist(T) RP where_opt(TW)
968               DO UPDATE SET setlist(Z) where_opt(W) upsert(N).
969               { A = sqlite3UpsertNew(pParse->db,T,TW,Z,W,N);}
970 upsert(A) ::= ON CONFLICT LP sortlist(T) RP where_opt(TW) DO NOTHING upsert(N).
971               { A = sqlite3UpsertNew(pParse->db,T,TW,0,0,N); }
972 upsert(A) ::= ON CONFLICT DO NOTHING returning.
973               { A = sqlite3UpsertNew(pParse->db,0,0,0,0,0); }
974 upsert(A) ::= ON CONFLICT DO UPDATE SET setlist(Z) where_opt(W) returning.
975               { A = sqlite3UpsertNew(pParse->db,0,0,Z,W,0);}
976 
977 returning ::= RETURNING selcollist(X).  {sqlite3AddReturning(pParse,X);}
978 returning ::= .
979 
980 %type insert_cmd {int}
981 insert_cmd(A) ::= INSERT orconf(R).   {A = R;}
982 insert_cmd(A) ::= REPLACE.            {A = OE_Replace;}
983 
984 %type idlist_opt {IdList*}
985 %destructor idlist_opt {sqlite3IdListDelete(pParse->db, $$);}
986 %type idlist {IdList*}
987 %destructor idlist {sqlite3IdListDelete(pParse->db, $$);}
988 
989 idlist_opt(A) ::= .                       {A = 0;}
990 idlist_opt(A) ::= LP idlist(X) RP.    {A = X;}
991 idlist(A) ::= idlist(A) COMMA nm(Y).
992     {A = sqlite3IdListAppend(pParse,A,&Y);}
993 idlist(A) ::= nm(Y).
994     {A = sqlite3IdListAppend(pParse,0,&Y); /*A-overwrites-Y*/}
995 
996 /////////////////////////// Expression Processing /////////////////////////////
997 //
998 
999 %type expr {Expr*}
1000 %destructor expr {sqlite3ExprDelete(pParse->db, $$);}
1001 %type term {Expr*}
1002 %destructor term {sqlite3ExprDelete(pParse->db, $$);}
1003 
1004 %include {
1005 
1006   /* Construct a new Expr object from a single identifier.  Use the
1007   ** new Expr to populate pOut.  Set the span of pOut to be the identifier
1008   ** that created the expression.
1009   */
1010   static Expr *tokenExpr(Parse *pParse, int op, Token t){
1011     Expr *p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr)+t.n+1);
1012     if( p ){
1013       /* memset(p, 0, sizeof(Expr)); */
1014       p->op = (u8)op;
1015       p->affExpr = 0;
1016       p->flags = EP_Leaf;
1017       ExprClearVVAProperties(p);
1018       p->iAgg = -1;
1019       p->pLeft = p->pRight = 0;
1020       p->x.pList = 0;
1021       p->pAggInfo = 0;
1022       p->y.pTab = 0;
1023       p->op2 = 0;
1024       p->iTable = 0;
1025       p->iColumn = 0;
1026       p->u.zToken = (char*)&p[1];
1027       memcpy(p->u.zToken, t.z, t.n);
1028       p->u.zToken[t.n] = 0;
1029       if( sqlite3Isquote(p->u.zToken[0]) ){
1030         sqlite3DequoteExpr(p);
1031       }
1032 #if SQLITE_MAX_EXPR_DEPTH>0
1033       p->nHeight = 1;
1034 #endif
1035       if( IN_RENAME_OBJECT ){
1036         return (Expr*)sqlite3RenameTokenMap(pParse, (void*)p, &t);
1037       }
1038     }
1039     return p;
1040   }
1041 
1042 }
1043 
1044 expr(A) ::= term(A).
1045 expr(A) ::= LP expr(X) RP. {A = X;}
1046 expr(A) ::= id(X).          {A=tokenExpr(pParse,TK_ID,X); /*A-overwrites-X*/}
1047 expr(A) ::= JOIN_KW(X).     {A=tokenExpr(pParse,TK_ID,X); /*A-overwrites-X*/}
1048 expr(A) ::= nm(X) DOT nm(Y). {
1049   Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &X, 1);
1050   Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &Y, 1);
1051   if( IN_RENAME_OBJECT ){
1052     sqlite3RenameTokenMap(pParse, (void*)temp2, &Y);
1053     sqlite3RenameTokenMap(pParse, (void*)temp1, &X);
1054   }
1055   A = sqlite3PExpr(pParse, TK_DOT, temp1, temp2);
1056 }
1057 expr(A) ::= nm(X) DOT nm(Y) DOT nm(Z). {
1058   Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &X, 1);
1059   Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &Y, 1);
1060   Expr *temp3 = sqlite3ExprAlloc(pParse->db, TK_ID, &Z, 1);
1061   Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3);
1062   if( IN_RENAME_OBJECT ){
1063     sqlite3RenameTokenMap(pParse, (void*)temp3, &Z);
1064     sqlite3RenameTokenMap(pParse, (void*)temp2, &Y);
1065   }
1066   A = sqlite3PExpr(pParse, TK_DOT, temp1, temp4);
1067 }
1068 term(A) ::= NULL|FLOAT|BLOB(X). {A=tokenExpr(pParse,@X,X); /*A-overwrites-X*/}
1069 term(A) ::= STRING(X).          {A=tokenExpr(pParse,@X,X); /*A-overwrites-X*/}
1070 term(A) ::= INTEGER(X). {
1071   A = sqlite3ExprAlloc(pParse->db, TK_INTEGER, &X, 1);
1072 }
1073 expr(A) ::= VARIABLE(X).     {
1074   if( !(X.z[0]=='#' && sqlite3Isdigit(X.z[1])) ){
1075     u32 n = X.n;
1076     A = tokenExpr(pParse, TK_VARIABLE, X);
1077     sqlite3ExprAssignVarNumber(pParse, A, n);
1078   }else{
1079     /* When doing a nested parse, one can include terms in an expression
1080     ** that look like this:   #1 #2 ...  These terms refer to registers
1081     ** in the virtual machine.  #N is the N-th register. */
1082     Token t = X; /*A-overwrites-X*/
1083     assert( t.n>=2 );
1084     if( pParse->nested==0 ){
1085       sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &t);
1086       A = 0;
1087     }else{
1088       A = sqlite3PExpr(pParse, TK_REGISTER, 0, 0);
1089       if( A ) sqlite3GetInt32(&t.z[1], &A->iTable);
1090     }
1091   }
1092 }
1093 expr(A) ::= expr(A) COLLATE ids(C). {
1094   A = sqlite3ExprAddCollateToken(pParse, A, &C, 1);
1095 }
1096 %ifndef SQLITE_OMIT_CAST
1097 expr(A) ::= CAST LP expr(E) AS typetoken(T) RP. {
1098   A = sqlite3ExprAlloc(pParse->db, TK_CAST, &T, 1);
1099   sqlite3ExprAttachSubtrees(pParse->db, A, E, 0);
1100 }
1101 %endif  SQLITE_OMIT_CAST
1102 
1103 
1104 expr(A) ::= id(X) LP distinct(D) exprlist(Y) RP. {
1105   A = sqlite3ExprFunction(pParse, Y, &X, D);
1106 }
1107 expr(A) ::= id(X) LP STAR RP. {
1108   A = sqlite3ExprFunction(pParse, 0, &X, 0);
1109 }
1110 
1111 %ifndef SQLITE_OMIT_WINDOWFUNC
1112 expr(A) ::= id(X) LP distinct(D) exprlist(Y) RP filter_over(Z). {
1113   A = sqlite3ExprFunction(pParse, Y, &X, D);
1114   sqlite3WindowAttach(pParse, A, Z);
1115 }
1116 expr(A) ::= id(X) LP STAR RP filter_over(Z). {
1117   A = sqlite3ExprFunction(pParse, 0, &X, 0);
1118   sqlite3WindowAttach(pParse, A, Z);
1119 }
1120 %endif
1121 
1122 term(A) ::= CTIME_KW(OP). {
1123   A = sqlite3ExprFunction(pParse, 0, &OP, 0);
1124 }
1125 
1126 expr(A) ::= LP nexprlist(X) COMMA expr(Y) RP. {
1127   ExprList *pList = sqlite3ExprListAppend(pParse, X, Y);
1128   A = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
1129   if( A ){
1130     A->x.pList = pList;
1131     if( ALWAYS(pList->nExpr) ){
1132       A->flags |= pList->a[0].pExpr->flags & EP_Propagate;
1133     }
1134   }else{
1135     sqlite3ExprListDelete(pParse->db, pList);
1136   }
1137 }
1138 
1139 expr(A) ::= expr(A) AND expr(Y).        {A=sqlite3ExprAnd(pParse,A,Y);}
1140 expr(A) ::= expr(A) OR(OP) expr(Y).     {A=sqlite3PExpr(pParse,@OP,A,Y);}
1141 expr(A) ::= expr(A) LT|GT|GE|LE(OP) expr(Y).
1142                                         {A=sqlite3PExpr(pParse,@OP,A,Y);}
1143 expr(A) ::= expr(A) EQ|NE(OP) expr(Y).  {A=sqlite3PExpr(pParse,@OP,A,Y);}
1144 expr(A) ::= expr(A) BITAND|BITOR|LSHIFT|RSHIFT(OP) expr(Y).
1145                                         {A=sqlite3PExpr(pParse,@OP,A,Y);}
1146 expr(A) ::= expr(A) PLUS|MINUS(OP) expr(Y).
1147                                         {A=sqlite3PExpr(pParse,@OP,A,Y);}
1148 expr(A) ::= expr(A) STAR|SLASH|REM(OP) expr(Y).
1149                                         {A=sqlite3PExpr(pParse,@OP,A,Y);}
1150 expr(A) ::= expr(A) CONCAT(OP) expr(Y). {A=sqlite3PExpr(pParse,@OP,A,Y);}
1151 %type likeop {Token}
1152 likeop(A) ::= LIKE_KW|MATCH(A).
1153 likeop(A) ::= NOT LIKE_KW|MATCH(X). {A=X; A.n|=0x80000000; /*A-overwrite-X*/}
1154 expr(A) ::= expr(A) likeop(OP) expr(Y).  [LIKE_KW]  {
1155   ExprList *pList;
1156   int bNot = OP.n & 0x80000000;
1157   OP.n &= 0x7fffffff;
1158   pList = sqlite3ExprListAppend(pParse,0, Y);
1159   pList = sqlite3ExprListAppend(pParse,pList, A);
1160   A = sqlite3ExprFunction(pParse, pList, &OP, 0);
1161   if( bNot ) A = sqlite3PExpr(pParse, TK_NOT, A, 0);
1162   if( A ) A->flags |= EP_InfixFunc;
1163 }
1164 expr(A) ::= expr(A) likeop(OP) expr(Y) ESCAPE expr(E).  [LIKE_KW]  {
1165   ExprList *pList;
1166   int bNot = OP.n & 0x80000000;
1167   OP.n &= 0x7fffffff;
1168   pList = sqlite3ExprListAppend(pParse,0, Y);
1169   pList = sqlite3ExprListAppend(pParse,pList, A);
1170   pList = sqlite3ExprListAppend(pParse,pList, E);
1171   A = sqlite3ExprFunction(pParse, pList, &OP, 0);
1172   if( bNot ) A = sqlite3PExpr(pParse, TK_NOT, A, 0);
1173   if( A ) A->flags |= EP_InfixFunc;
1174 }
1175 
1176 expr(A) ::= expr(A) ISNULL|NOTNULL(E).   {A = sqlite3PExpr(pParse,@E,A,0);}
1177 expr(A) ::= expr(A) NOT NULL.    {A = sqlite3PExpr(pParse,TK_NOTNULL,A,0);}
1178 
1179 %include {
1180   /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
1181   ** unary TK_ISNULL or TK_NOTNULL expression. */
1182   static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
1183     sqlite3 *db = pParse->db;
1184     if( pA && pY && pY->op==TK_NULL && !IN_RENAME_OBJECT ){
1185       pA->op = (u8)op;
1186       sqlite3ExprDelete(db, pA->pRight);
1187       pA->pRight = 0;
1188     }
1189   }
1190 }
1191 
1192 //    expr1 IS expr2
1193 //    expr1 IS NOT expr2
1194 //
1195 // If expr2 is NULL then code as TK_ISNULL or TK_NOTNULL.  If expr2
1196 // is any other expression, code as TK_IS or TK_ISNOT.
1197 //
1198 expr(A) ::= expr(A) IS expr(Y).     {
1199   A = sqlite3PExpr(pParse,TK_IS,A,Y);
1200   binaryToUnaryIfNull(pParse, Y, A, TK_ISNULL);
1201 }
1202 expr(A) ::= expr(A) IS NOT expr(Y). {
1203   A = sqlite3PExpr(pParse,TK_ISNOT,A,Y);
1204   binaryToUnaryIfNull(pParse, Y, A, TK_NOTNULL);
1205 }
1206 
1207 expr(A) ::= NOT(B) expr(X).
1208               {A = sqlite3PExpr(pParse, @B, X, 0);/*A-overwrites-B*/}
1209 expr(A) ::= BITNOT(B) expr(X).
1210               {A = sqlite3PExpr(pParse, @B, X, 0);/*A-overwrites-B*/}
1211 expr(A) ::= PLUS|MINUS(B) expr(X). [BITNOT] {
1212   A = sqlite3PExpr(pParse, @B==TK_PLUS ? TK_UPLUS : TK_UMINUS, X, 0);
1213   /*A-overwrites-B*/
1214 }
1215 
1216 %type between_op {int}
1217 between_op(A) ::= BETWEEN.     {A = 0;}
1218 between_op(A) ::= NOT BETWEEN. {A = 1;}
1219 expr(A) ::= expr(A) between_op(N) expr(X) AND expr(Y). [BETWEEN] {
1220   ExprList *pList = sqlite3ExprListAppend(pParse,0, X);
1221   pList = sqlite3ExprListAppend(pParse,pList, Y);
1222   A = sqlite3PExpr(pParse, TK_BETWEEN, A, 0);
1223   if( A ){
1224     A->x.pList = pList;
1225   }else{
1226     sqlite3ExprListDelete(pParse->db, pList);
1227   }
1228   if( N ) A = sqlite3PExpr(pParse, TK_NOT, A, 0);
1229 }
1230 %ifndef SQLITE_OMIT_SUBQUERY
1231   %type in_op {int}
1232   in_op(A) ::= IN.      {A = 0;}
1233   in_op(A) ::= NOT IN.  {A = 1;}
1234   expr(A) ::= expr(A) in_op(N) LP exprlist(Y) RP. [IN] {
1235     if( Y==0 ){
1236       /* Expressions of the form
1237       **
1238       **      expr1 IN ()
1239       **      expr1 NOT IN ()
1240       **
1241       ** simplify to constants 0 (false) and 1 (true), respectively,
1242       ** regardless of the value of expr1.
1243       */
1244       sqlite3ExprUnmapAndDelete(pParse, A);
1245       A = sqlite3Expr(pParse->db, TK_INTEGER, N ? "1" : "0");
1246     }else if( Y->nExpr==1 && sqlite3ExprIsConstant(Y->a[0].pExpr) ){
1247       Expr *pRHS = Y->a[0].pExpr;
1248       Y->a[0].pExpr = 0;
1249       sqlite3ExprListDelete(pParse->db, Y);
1250       pRHS = sqlite3PExpr(pParse, TK_UPLUS, pRHS, 0);
1251       A = sqlite3PExpr(pParse, TK_EQ, A, pRHS);
1252       if( N ) A = sqlite3PExpr(pParse, TK_NOT, A, 0);
1253     }else{
1254       A = sqlite3PExpr(pParse, TK_IN, A, 0);
1255       if( A ){
1256         A->x.pList = Y;
1257         sqlite3ExprSetHeightAndFlags(pParse, A);
1258       }else{
1259         sqlite3ExprListDelete(pParse->db, Y);
1260       }
1261       if( N ) A = sqlite3PExpr(pParse, TK_NOT, A, 0);
1262     }
1263   }
1264   expr(A) ::= LP select(X) RP. {
1265     A = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
1266     sqlite3PExprAddSelect(pParse, A, X);
1267   }
1268   expr(A) ::= expr(A) in_op(N) LP select(Y) RP.  [IN] {
1269     A = sqlite3PExpr(pParse, TK_IN, A, 0);
1270     sqlite3PExprAddSelect(pParse, A, Y);
1271     if( N ) A = sqlite3PExpr(pParse, TK_NOT, A, 0);
1272   }
1273   expr(A) ::= expr(A) in_op(N) nm(Y) dbnm(Z) paren_exprlist(E). [IN] {
1274     SrcList *pSrc = sqlite3SrcListAppend(pParse, 0,&Y,&Z);
1275     Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0);
1276     if( E )  sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, E);
1277     A = sqlite3PExpr(pParse, TK_IN, A, 0);
1278     sqlite3PExprAddSelect(pParse, A, pSelect);
1279     if( N ) A = sqlite3PExpr(pParse, TK_NOT, A, 0);
1280   }
1281   expr(A) ::= EXISTS LP select(Y) RP. {
1282     Expr *p;
1283     p = A = sqlite3PExpr(pParse, TK_EXISTS, 0, 0);
1284     sqlite3PExprAddSelect(pParse, p, Y);
1285   }
1286 %endif SQLITE_OMIT_SUBQUERY
1287 
1288 /* CASE expressions */
1289 expr(A) ::= CASE case_operand(X) case_exprlist(Y) case_else(Z) END. {
1290   A = sqlite3PExpr(pParse, TK_CASE, X, 0);
1291   if( A ){
1292     A->x.pList = Z ? sqlite3ExprListAppend(pParse,Y,Z) : Y;
1293     sqlite3ExprSetHeightAndFlags(pParse, A);
1294   }else{
1295     sqlite3ExprListDelete(pParse->db, Y);
1296     sqlite3ExprDelete(pParse->db, Z);
1297   }
1298 }
1299 %type case_exprlist {ExprList*}
1300 %destructor case_exprlist {sqlite3ExprListDelete(pParse->db, $$);}
1301 case_exprlist(A) ::= case_exprlist(A) WHEN expr(Y) THEN expr(Z). {
1302   A = sqlite3ExprListAppend(pParse,A, Y);
1303   A = sqlite3ExprListAppend(pParse,A, Z);
1304 }
1305 case_exprlist(A) ::= WHEN expr(Y) THEN expr(Z). {
1306   A = sqlite3ExprListAppend(pParse,0, Y);
1307   A = sqlite3ExprListAppend(pParse,A, Z);
1308 }
1309 %type case_else {Expr*}
1310 %destructor case_else {sqlite3ExprDelete(pParse->db, $$);}
1311 case_else(A) ::=  ELSE expr(X).         {A = X;}
1312 case_else(A) ::=  .                     {A = 0;}
1313 %type case_operand {Expr*}
1314 %destructor case_operand {sqlite3ExprDelete(pParse->db, $$);}
1315 case_operand(A) ::= expr(X).            {A = X; /*A-overwrites-X*/}
1316 case_operand(A) ::= .                   {A = 0;}
1317 
1318 %type exprlist {ExprList*}
1319 %destructor exprlist {sqlite3ExprListDelete(pParse->db, $$);}
1320 %type nexprlist {ExprList*}
1321 %destructor nexprlist {sqlite3ExprListDelete(pParse->db, $$);}
1322 
1323 exprlist(A) ::= nexprlist(A).
1324 exprlist(A) ::= .                            {A = 0;}
1325 nexprlist(A) ::= nexprlist(A) COMMA expr(Y).
1326     {A = sqlite3ExprListAppend(pParse,A,Y);}
1327 nexprlist(A) ::= expr(Y).
1328     {A = sqlite3ExprListAppend(pParse,0,Y); /*A-overwrites-Y*/}
1329 
1330 %ifndef SQLITE_OMIT_SUBQUERY
1331 /* A paren_exprlist is an optional expression list contained inside
1332 ** of parenthesis */
1333 %type paren_exprlist {ExprList*}
1334 %destructor paren_exprlist {sqlite3ExprListDelete(pParse->db, $$);}
1335 paren_exprlist(A) ::= .   {A = 0;}
1336 paren_exprlist(A) ::= LP exprlist(X) RP.  {A = X;}
1337 %endif SQLITE_OMIT_SUBQUERY
1338 
1339 
1340 ///////////////////////////// The CREATE INDEX command ///////////////////////
1341 //
1342 cmd ::= createkw(S) uniqueflag(U) INDEX ifnotexists(NE) nm(X) dbnm(D)
1343         ON nm(Y) LP sortlist(Z) RP where_opt(W). {
1344   sqlite3CreateIndex(pParse, &X, &D,
1345                      sqlite3SrcListAppend(pParse,0,&Y,0), Z, U,
1346                       &S, W, SQLITE_SO_ASC, NE, SQLITE_IDXTYPE_APPDEF);
1347   if( IN_RENAME_OBJECT && pParse->pNewIndex ){
1348     sqlite3RenameTokenMap(pParse, pParse->pNewIndex->zName, &Y);
1349   }
1350 }
1351 
1352 %type uniqueflag {int}
1353 uniqueflag(A) ::= UNIQUE.  {A = OE_Abort;}
1354 uniqueflag(A) ::= .        {A = OE_None;}
1355 
1356 
1357 // The eidlist non-terminal (Expression Id List) generates an ExprList
1358 // from a list of identifiers.  The identifier names are in ExprList.a[].zName.
1359 // This list is stored in an ExprList rather than an IdList so that it
1360 // can be easily sent to sqlite3ColumnsExprList().
1361 //
1362 // eidlist is grouped with CREATE INDEX because it used to be the non-terminal
1363 // used for the arguments to an index.  That is just an historical accident.
1364 //
1365 // IMPORTANT COMPATIBILITY NOTE:  Some prior versions of SQLite accepted
1366 // COLLATE clauses and ASC or DESC keywords on ID lists in inappropriate
1367 // places - places that might have been stored in the sqlite_schema table.
1368 // Those extra features were ignored.  But because they might be in some
1369 // (busted) old databases, we need to continue parsing them when loading
1370 // historical schemas.
1371 //
1372 %type eidlist {ExprList*}
1373 %destructor eidlist {sqlite3ExprListDelete(pParse->db, $$);}
1374 %type eidlist_opt {ExprList*}
1375 %destructor eidlist_opt {sqlite3ExprListDelete(pParse->db, $$);}
1376 
1377 %include {
1378   /* Add a single new term to an ExprList that is used to store a
1379   ** list of identifiers.  Report an error if the ID list contains
1380   ** a COLLATE clause or an ASC or DESC keyword, except ignore the
1381   ** error while parsing a legacy schema.
1382   */
1383   static ExprList *parserAddExprIdListTerm(
1384     Parse *pParse,
1385     ExprList *pPrior,
1386     Token *pIdToken,
1387     int hasCollate,
1388     int sortOrder
1389   ){
1390     ExprList *p = sqlite3ExprListAppend(pParse, pPrior, 0);
1391     if( (hasCollate || sortOrder!=SQLITE_SO_UNDEFINED)
1392         && pParse->db->init.busy==0
1393     ){
1394       sqlite3ErrorMsg(pParse, "syntax error after column name \"%.*s\"",
1395                          pIdToken->n, pIdToken->z);
1396     }
1397     sqlite3ExprListSetName(pParse, p, pIdToken, 1);
1398     return p;
1399   }
1400 } // end %include
1401 
1402 eidlist_opt(A) ::= .                         {A = 0;}
1403 eidlist_opt(A) ::= LP eidlist(X) RP.         {A = X;}
1404 eidlist(A) ::= eidlist(A) COMMA nm(Y) collate(C) sortorder(Z).  {
1405   A = parserAddExprIdListTerm(pParse, A, &Y, C, Z);
1406 }
1407 eidlist(A) ::= nm(Y) collate(C) sortorder(Z). {
1408   A = parserAddExprIdListTerm(pParse, 0, &Y, C, Z); /*A-overwrites-Y*/
1409 }
1410 
1411 %type collate {int}
1412 collate(C) ::= .              {C = 0;}
1413 collate(C) ::= COLLATE ids.   {C = 1;}
1414 
1415 
1416 ///////////////////////////// The DROP INDEX command /////////////////////////
1417 //
1418 cmd ::= DROP INDEX ifexists(E) fullname(X).   {sqlite3DropIndex(pParse, X, E);}
1419 
1420 ///////////////////////////// The VACUUM command /////////////////////////////
1421 //
1422 %if !SQLITE_OMIT_VACUUM && !SQLITE_OMIT_ATTACH
1423 %type vinto {Expr*}
1424 %destructor vinto {sqlite3ExprDelete(pParse->db, $$);}
1425 cmd ::= VACUUM vinto(Y).                {sqlite3Vacuum(pParse,0,Y);}
1426 cmd ::= VACUUM nm(X) vinto(Y).          {sqlite3Vacuum(pParse,&X,Y);}
1427 vinto(A) ::= INTO expr(X).              {A = X;}
1428 vinto(A) ::= .                          {A = 0;}
1429 %endif
1430 
1431 ///////////////////////////// The PRAGMA command /////////////////////////////
1432 //
1433 %ifndef SQLITE_OMIT_PRAGMA
1434 cmd ::= PRAGMA nm(X) dbnm(Z).                {sqlite3Pragma(pParse,&X,&Z,0,0);}
1435 cmd ::= PRAGMA nm(X) dbnm(Z) EQ nmnum(Y).    {sqlite3Pragma(pParse,&X,&Z,&Y,0);}
1436 cmd ::= PRAGMA nm(X) dbnm(Z) LP nmnum(Y) RP. {sqlite3Pragma(pParse,&X,&Z,&Y,0);}
1437 cmd ::= PRAGMA nm(X) dbnm(Z) EQ minus_num(Y).
1438                                              {sqlite3Pragma(pParse,&X,&Z,&Y,1);}
1439 cmd ::= PRAGMA nm(X) dbnm(Z) LP minus_num(Y) RP.
1440                                              {sqlite3Pragma(pParse,&X,&Z,&Y,1);}
1441 
1442 nmnum(A) ::= plus_num(A).
1443 nmnum(A) ::= nm(A).
1444 nmnum(A) ::= ON(A).
1445 nmnum(A) ::= DELETE(A).
1446 nmnum(A) ::= DEFAULT(A).
1447 %endif SQLITE_OMIT_PRAGMA
1448 %token_class number INTEGER|FLOAT.
1449 plus_num(A) ::= PLUS number(X).       {A = X;}
1450 plus_num(A) ::= number(A).
1451 minus_num(A) ::= MINUS number(X).     {A = X;}
1452 //////////////////////////// The CREATE TRIGGER command /////////////////////
1453 
1454 %ifndef SQLITE_OMIT_TRIGGER
1455 
1456 cmd ::= createkw trigger_decl(A) BEGIN trigger_cmd_list(S) END(Z). {
1457   Token all;
1458   all.z = A.z;
1459   all.n = (int)(Z.z - A.z) + Z.n;
1460   sqlite3FinishTrigger(pParse, S, &all);
1461 }
1462 
1463 trigger_decl(A) ::= temp(T) TRIGGER ifnotexists(NOERR) nm(B) dbnm(Z)
1464                     trigger_time(C) trigger_event(D)
1465                     ON fullname(E) foreach_clause when_clause(G). {
1466   sqlite3BeginTrigger(pParse, &B, &Z, C, D.a, D.b, E, G, T, NOERR);
1467   A = (Z.n==0?B:Z); /*A-overwrites-T*/
1468 }
1469 
1470 %type trigger_time {int}
1471 trigger_time(A) ::= BEFORE|AFTER(X).  { A = @X; /*A-overwrites-X*/ }
1472 trigger_time(A) ::= INSTEAD OF.  { A = TK_INSTEAD;}
1473 trigger_time(A) ::= .            { A = TK_BEFORE; }
1474 
1475 %type trigger_event {struct TrigEvent}
1476 %destructor trigger_event {sqlite3IdListDelete(pParse->db, $$.b);}
1477 trigger_event(A) ::= DELETE|INSERT(X).   {A.a = @X; /*A-overwrites-X*/ A.b = 0;}
1478 trigger_event(A) ::= UPDATE(X).          {A.a = @X; /*A-overwrites-X*/ A.b = 0;}
1479 trigger_event(A) ::= UPDATE OF idlist(X).{A.a = TK_UPDATE; A.b = X;}
1480 
1481 foreach_clause ::= .
1482 foreach_clause ::= FOR EACH ROW.
1483 
1484 %type when_clause {Expr*}
1485 %destructor when_clause {sqlite3ExprDelete(pParse->db, $$);}
1486 when_clause(A) ::= .             { A = 0; }
1487 when_clause(A) ::= WHEN expr(X). { A = X; }
1488 
1489 %type trigger_cmd_list {TriggerStep*}
1490 %destructor trigger_cmd_list {sqlite3DeleteTriggerStep(pParse->db, $$);}
1491 trigger_cmd_list(A) ::= trigger_cmd_list(A) trigger_cmd(X) SEMI. {
1492   assert( A!=0 );
1493   A->pLast->pNext = X;
1494   A->pLast = X;
1495 }
1496 trigger_cmd_list(A) ::= trigger_cmd(A) SEMI. {
1497   assert( A!=0 );
1498   A->pLast = A;
1499 }
1500 
1501 // Disallow qualified table names on INSERT, UPDATE, and DELETE statements
1502 // within a trigger.  The table to INSERT, UPDATE, or DELETE is always in
1503 // the same database as the table that the trigger fires on.
1504 //
1505 %type trnm {Token}
1506 trnm(A) ::= nm(A).
1507 trnm(A) ::= nm DOT nm(X). {
1508   A = X;
1509   sqlite3ErrorMsg(pParse,
1510         "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
1511         "statements within triggers");
1512 }
1513 
1514 // Disallow the INDEX BY and NOT INDEXED clauses on UPDATE and DELETE
1515 // statements within triggers.  We make a specific error message for this
1516 // since it is an exception to the default grammar rules.
1517 //
1518 tridxby ::= .
1519 tridxby ::= INDEXED BY nm. {
1520   sqlite3ErrorMsg(pParse,
1521         "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
1522         "within triggers");
1523 }
1524 tridxby ::= NOT INDEXED. {
1525   sqlite3ErrorMsg(pParse,
1526         "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
1527         "within triggers");
1528 }
1529 
1530 
1531 
1532 %type trigger_cmd {TriggerStep*}
1533 %destructor trigger_cmd {sqlite3DeleteTriggerStep(pParse->db, $$);}
1534 // UPDATE
1535 trigger_cmd(A) ::=
1536    UPDATE(B) orconf(R) trnm(X) tridxby SET setlist(Y) from(F) where_opt(Z) scanpt(E).
1537    {A = sqlite3TriggerUpdateStep(pParse, &X, F, Y, Z, R, B.z, E);}
1538 
1539 // INSERT
1540 trigger_cmd(A) ::= scanpt(B) insert_cmd(R) INTO
1541                       trnm(X) idlist_opt(F) select(S) upsert(U) scanpt(Z). {
1542    A = sqlite3TriggerInsertStep(pParse,&X,F,S,R,U,B,Z);/*A-overwrites-R*/
1543 }
1544 // DELETE
1545 trigger_cmd(A) ::= DELETE(B) FROM trnm(X) tridxby where_opt(Y) scanpt(E).
1546    {A = sqlite3TriggerDeleteStep(pParse, &X, Y, B.z, E);}
1547 
1548 // SELECT
1549 trigger_cmd(A) ::= scanpt(B) select(X) scanpt(E).
1550    {A = sqlite3TriggerSelectStep(pParse->db, X, B, E); /*A-overwrites-X*/}
1551 
1552 // The special RAISE expression that may occur in trigger programs
1553 expr(A) ::= RAISE LP IGNORE RP.  {
1554   A = sqlite3PExpr(pParse, TK_RAISE, 0, 0);
1555   if( A ){
1556     A->affExpr = OE_Ignore;
1557   }
1558 }
1559 expr(A) ::= RAISE LP raisetype(T) COMMA nm(Z) RP.  {
1560   A = sqlite3ExprAlloc(pParse->db, TK_RAISE, &Z, 1);
1561   if( A ) {
1562     A->affExpr = (char)T;
1563   }
1564 }
1565 %endif  !SQLITE_OMIT_TRIGGER
1566 
1567 %type raisetype {int}
1568 raisetype(A) ::= ROLLBACK.  {A = OE_Rollback;}
1569 raisetype(A) ::= ABORT.     {A = OE_Abort;}
1570 raisetype(A) ::= FAIL.      {A = OE_Fail;}
1571 
1572 
1573 ////////////////////////  DROP TRIGGER statement //////////////////////////////
1574 %ifndef SQLITE_OMIT_TRIGGER
1575 cmd ::= DROP TRIGGER ifexists(NOERR) fullname(X). {
1576   sqlite3DropTrigger(pParse,X,NOERR);
1577 }
1578 %endif  !SQLITE_OMIT_TRIGGER
1579 
1580 //////////////////////// ATTACH DATABASE file AS name /////////////////////////
1581 %ifndef SQLITE_OMIT_ATTACH
1582 cmd ::= ATTACH database_kw_opt expr(F) AS expr(D) key_opt(K). {
1583   sqlite3Attach(pParse, F, D, K);
1584 }
1585 cmd ::= DETACH database_kw_opt expr(D). {
1586   sqlite3Detach(pParse, D);
1587 }
1588 
1589 %type key_opt {Expr*}
1590 %destructor key_opt {sqlite3ExprDelete(pParse->db, $$);}
1591 key_opt(A) ::= .                     { A = 0; }
1592 key_opt(A) ::= KEY expr(X).          { A = X; }
1593 
1594 database_kw_opt ::= DATABASE.
1595 database_kw_opt ::= .
1596 %endif SQLITE_OMIT_ATTACH
1597 
1598 ////////////////////////// REINDEX collation //////////////////////////////////
1599 %ifndef SQLITE_OMIT_REINDEX
1600 cmd ::= REINDEX.                {sqlite3Reindex(pParse, 0, 0);}
1601 cmd ::= REINDEX nm(X) dbnm(Y).  {sqlite3Reindex(pParse, &X, &Y);}
1602 %endif  SQLITE_OMIT_REINDEX
1603 
1604 /////////////////////////////////// ANALYZE ///////////////////////////////////
1605 %ifndef SQLITE_OMIT_ANALYZE
1606 cmd ::= ANALYZE.                {sqlite3Analyze(pParse, 0, 0);}
1607 cmd ::= ANALYZE nm(X) dbnm(Y).  {sqlite3Analyze(pParse, &X, &Y);}
1608 %endif
1609 
1610 //////////////////////// ALTER TABLE table ... ////////////////////////////////
1611 %ifndef SQLITE_OMIT_ALTERTABLE
1612 cmd ::= ALTER TABLE fullname(X) RENAME TO nm(Z). {
1613   sqlite3AlterRenameTable(pParse,X,&Z);
1614 }
1615 cmd ::= ALTER TABLE add_column_fullname
1616         ADD kwcolumn_opt columnname(Y) carglist. {
1617   Y.n = (int)(pParse->sLastToken.z-Y.z) + pParse->sLastToken.n;
1618   sqlite3AlterFinishAddColumn(pParse, &Y);
1619 }
1620 cmd ::= ALTER TABLE fullname(X) DROP kwcolumn_opt nm(Y). {
1621   sqlite3AlterDropColumn(pParse, X, &Y);
1622 }
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 %type wqitem {Cte*}
1662 // %destructor wqitem {sqlite3CteDelete(pParse->db, $$);} // not reachable
1663 
1664 with ::= .
1665 %ifndef SQLITE_OMIT_CTE
1666 with ::= WITH wqlist(W).              { sqlite3WithPush(pParse, W, 1); }
1667 with ::= WITH RECURSIVE wqlist(W).    { sqlite3WithPush(pParse, W, 1); }
1668 
1669 wqitem(A) ::= nm(X) eidlist_opt(Y) AS LP select(Z) RP. {
1670   A = sqlite3CteNew(pParse, &X, Y, Z); /*A-overwrites-X*/
1671 }
1672 wqlist(A) ::= wqitem(X). {
1673   A = sqlite3WithAdd(pParse, 0, X); /*A-overwrites-X*/
1674 }
1675 wqlist(A) ::= wqlist(A) COMMA wqitem(X). {
1676   A = sqlite3WithAdd(pParse, A, X);
1677 }
1678 %endif  SQLITE_OMIT_CTE
1679 
1680 //////////////////////// WINDOW FUNCTION EXPRESSIONS /////////////////////////
1681 // These must be at the end of this file. Specifically, the rules that
1682 // introduce tokens WINDOW, OVER and FILTER must appear last. This causes
1683 // the integer values assigned to these tokens to be larger than all other
1684 // tokens that may be output by the tokenizer except TK_SPACE and TK_ILLEGAL.
1685 //
1686 %ifndef SQLITE_OMIT_WINDOWFUNC
1687 %type windowdefn_list {Window*}
1688 %destructor windowdefn_list {sqlite3WindowListDelete(pParse->db, $$);}
1689 windowdefn_list(A) ::= windowdefn(Z). { A = Z; }
1690 windowdefn_list(A) ::= windowdefn_list(Y) COMMA windowdefn(Z). {
1691   assert( Z!=0 );
1692   sqlite3WindowChain(pParse, Z, Y);
1693   Z->pNextWin = Y;
1694   A = Z;
1695 }
1696 
1697 %type windowdefn {Window*}
1698 %destructor windowdefn {sqlite3WindowDelete(pParse->db, $$);}
1699 windowdefn(A) ::= nm(X) AS LP window(Y) RP. {
1700   if( ALWAYS(Y) ){
1701     Y->zName = sqlite3DbStrNDup(pParse->db, X.z, X.n);
1702   }
1703   A = Y;
1704 }
1705 
1706 %type window {Window*}
1707 %destructor window {sqlite3WindowDelete(pParse->db, $$);}
1708 
1709 %type frame_opt {Window*}
1710 %destructor frame_opt {sqlite3WindowDelete(pParse->db, $$);}
1711 
1712 %type part_opt {ExprList*}
1713 %destructor part_opt {sqlite3ExprListDelete(pParse->db, $$);}
1714 
1715 %type filter_clause {Expr*}
1716 %destructor filter_clause {sqlite3ExprDelete(pParse->db, $$);}
1717 
1718 %type over_clause {Window*}
1719 %destructor over_clause {sqlite3WindowDelete(pParse->db, $$);}
1720 
1721 %type filter_over {Window*}
1722 %destructor filter_over {sqlite3WindowDelete(pParse->db, $$);}
1723 
1724 %type range_or_rows {int}
1725 
1726 %type frame_bound {struct FrameBound}
1727 %destructor frame_bound {sqlite3ExprDelete(pParse->db, $$.pExpr);}
1728 %type frame_bound_s {struct FrameBound}
1729 %destructor frame_bound_s {sqlite3ExprDelete(pParse->db, $$.pExpr);}
1730 %type frame_bound_e {struct FrameBound}
1731 %destructor frame_bound_e {sqlite3ExprDelete(pParse->db, $$.pExpr);}
1732 
1733 window(A) ::= PARTITION BY nexprlist(X) orderby_opt(Y) frame_opt(Z). {
1734   A = sqlite3WindowAssemble(pParse, Z, X, Y, 0);
1735 }
1736 window(A) ::= nm(W) PARTITION BY nexprlist(X) orderby_opt(Y) frame_opt(Z). {
1737   A = sqlite3WindowAssemble(pParse, Z, X, Y, &W);
1738 }
1739 window(A) ::= ORDER BY sortlist(Y) frame_opt(Z). {
1740   A = sqlite3WindowAssemble(pParse, Z, 0, Y, 0);
1741 }
1742 window(A) ::= nm(W) ORDER BY sortlist(Y) frame_opt(Z). {
1743   A = sqlite3WindowAssemble(pParse, Z, 0, Y, &W);
1744 }
1745 window(A) ::= frame_opt(Z). {
1746   A = Z;
1747 }
1748 window(A) ::= nm(W) frame_opt(Z). {
1749   A = sqlite3WindowAssemble(pParse, Z, 0, 0, &W);
1750 }
1751 
1752 frame_opt(A) ::= .                             {
1753   A = sqlite3WindowAlloc(pParse, 0, TK_UNBOUNDED, 0, TK_CURRENT, 0, 0);
1754 }
1755 frame_opt(A) ::= range_or_rows(X) frame_bound_s(Y) frame_exclude_opt(Z). {
1756   A = sqlite3WindowAlloc(pParse, X, Y.eType, Y.pExpr, TK_CURRENT, 0, Z);
1757 }
1758 frame_opt(A) ::= range_or_rows(X) BETWEEN frame_bound_s(Y) AND
1759                           frame_bound_e(Z) frame_exclude_opt(W). {
1760   A = sqlite3WindowAlloc(pParse, X, Y.eType, Y.pExpr, Z.eType, Z.pExpr, W);
1761 }
1762 
1763 range_or_rows(A) ::= RANGE|ROWS|GROUPS(X).   {A = @X; /*A-overwrites-X*/}
1764 
1765 frame_bound_s(A) ::= frame_bound(X).         {A = X;}
1766 frame_bound_s(A) ::= UNBOUNDED(X) PRECEDING. {A.eType = @X; A.pExpr = 0;}
1767 frame_bound_e(A) ::= frame_bound(X).         {A = X;}
1768 frame_bound_e(A) ::= UNBOUNDED(X) FOLLOWING. {A.eType = @X; A.pExpr = 0;}
1769 
1770 frame_bound(A) ::= expr(X) PRECEDING|FOLLOWING(Y).
1771                                              {A.eType = @Y; A.pExpr = X;}
1772 frame_bound(A) ::= CURRENT(X) ROW.           {A.eType = @X; A.pExpr = 0;}
1773 
1774 %type frame_exclude_opt {u8}
1775 frame_exclude_opt(A) ::= . {A = 0;}
1776 frame_exclude_opt(A) ::= EXCLUDE frame_exclude(X). {A = X;}
1777 
1778 %type frame_exclude {u8}
1779 frame_exclude(A) ::= NO(X) OTHERS.   {A = @X; /*A-overwrites-X*/}
1780 frame_exclude(A) ::= CURRENT(X) ROW. {A = @X; /*A-overwrites-X*/}
1781 frame_exclude(A) ::= GROUP|TIES(X).  {A = @X; /*A-overwrites-X*/}
1782 
1783 
1784 %type window_clause {Window*}
1785 %destructor window_clause {sqlite3WindowListDelete(pParse->db, $$);}
1786 window_clause(A) ::= WINDOW windowdefn_list(B). { A = B; }
1787 
1788 filter_over(A) ::= filter_clause(F) over_clause(O). {
1789   O->pFilter = F;
1790   A = O;
1791 }
1792 filter_over(A) ::= over_clause(O). {
1793   A = O;
1794 }
1795 filter_over(A) ::= filter_clause(F). {
1796   A = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
1797   if( A ){
1798     A->eFrmType = TK_FILTER;
1799     A->pFilter = F;
1800   }else{
1801     sqlite3ExprDelete(pParse->db, F);
1802   }
1803 }
1804 
1805 over_clause(A) ::= OVER LP window(Z) RP. {
1806   A = Z;
1807   assert( A!=0 );
1808 }
1809 over_clause(A) ::= OVER nm(Z). {
1810   A = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
1811   if( A ){
1812     A->zName = sqlite3DbStrNDup(pParse->db, Z.z, Z.n);
1813   }
1814 }
1815 
1816 filter_clause(A) ::= FILTER LP WHERE expr(X) RP.  { A = X; }
1817 %endif /* SQLITE_OMIT_WINDOWFUNC */
1818 
1819 /*
1820 ** The code generator needs some extra TK_ token values for tokens that
1821 ** are synthesized and do not actually appear in the grammar:
1822 */
1823 %token
1824   COLUMN          /* Reference to a table column */
1825   AGG_FUNCTION    /* An aggregate function */
1826   AGG_COLUMN      /* An aggregated column */
1827   TRUEFALSE       /* True or false keyword */
1828   ISNOT           /* Combination of IS and NOT */
1829   FUNCTION        /* A function invocation */
1830   UMINUS          /* Unary minus */
1831   UPLUS           /* Unary plus */
1832   TRUTH           /* IS TRUE or IS FALSE or IS NOT TRUE or IS NOT FALSE */
1833   REGISTER        /* Reference to a VDBE register */
1834   VECTOR          /* Vector */
1835   SELECT_COLUMN   /* Choose a single column from a multi-column SELECT */
1836   IF_NULL_ROW     /* the if-null-row operator */
1837   ASTERISK        /* The "*" in count(*) and similar */
1838   SPAN            /* The span operator */
1839 .
1840 /* There must be no more than 255 tokens defined above.  If this grammar
1841 ** is extended with new rules and tokens, they must either be so few in
1842 ** number that TK_SPAN is no more than 255, or else the new tokens must
1843 ** appear after this line.
1844 */
1845 %include {
1846 #if TK_SPAN>255
1847 # error too many tokens in the grammar
1848 #endif
1849 }
1850 
1851 /*
1852 ** The TK_SPACE and TK_ILLEGAL tokens must be the last two tokens.  The
1853 ** parser depends on this.  Those tokens are not used in any grammar rule.
1854 ** They are only used by the tokenizer.  Declare them last so that they
1855 ** are guaranteed to be the last two tokens
1856 */
1857 %token SPACE ILLEGAL.
1858