Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/sqlite/blob/master/src/window.c # sqlite [Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `master` Branches Tags History `sqlite / src / window.c` 3135 lines ยท 107827 bytes Raw Blame History 1 /* 2 ** 2018 May 08 3 ** 4 ** The author disclaims copyright to this source code. In place of 5 ** a legal notice, here is a blessing: 6 ** 7 ** May you do good and not evil. 8 ** May you find forgiveness for yourself and forgive others. 9 ** May you share freely, never taking more than you give. 10 ** 11 ************************************************************************* 12 */ 13 #include "sqliteInt.h" 14 15 #ifndef SQLITE_OMIT_WINDOWFUNC 16 17 /* 18 ** SELECT REWRITING 19 ** 20 ** Any SELECT statement that contains one or more window functions in 21 ** either the select list or ORDER BY clause (the only two places window 22 ** functions may be used) is transformed by function sqlite3WindowRewrite() 23 ** in order to support window function processing. For example, with the 24 ** schema: 25 ** 26 ** CREATE TABLE t1(a, b, c, d, e, f, g); 27 ** 28 ** the statement: 29 ** 30 ** SELECT a+1, max(b) OVER (PARTITION BY c ORDER BY d) FROM t1 ORDER BY e; 31 ** 32 ** is transformed to: 33 ** 34 ** SELECT a+1, max(b) OVER (PARTITION BY c ORDER BY d) FROM ( 35 ** SELECT a, e, c, d, b FROM t1 ORDER BY c, d 36 ** ) ORDER BY e; 37 ** 38 ** The flattening optimization is disabled when processing this transformed 39 ** SELECT statement. This allows the implementation of the window function 40 ** (in this case max()) to process rows sorted in order of (c, d), which 41 ** makes things easier for obvious reasons. More generally: 42 ** 43 ** * FROM, WHERE, GROUP BY and HAVING clauses are all moved to 44 ** the sub-query. 45 ** 46 ** * ORDER BY, LIMIT and OFFSET remain part of the parent query. 47 ** 48 ** * Terminals from each of the expression trees that make up the 49 ** select-list and ORDER BY expressions in the parent query are 50 ** selected by the sub-query. For the purposes of the transformation, 51 ** terminals are column references and aggregate functions. 52 ** 53 ** If there is more than one window function in the SELECT that uses 54 ** the same window declaration (the OVER bit), then a single scan may 55 ** be used to process more than one window function. For example: 56 ** 57 ** SELECT max(b) OVER (PARTITION BY c ORDER BY d), 58 ** min(e) OVER (PARTITION BY c ORDER BY d) 59 ** FROM t1; 60 ** 61 ** is transformed in the same way as the example above. However: 62 ** 63 ** SELECT max(b) OVER (PARTITION BY c ORDER BY d), 64 ** min(e) OVER (PARTITION BY a ORDER BY b) 65 ** FROM t1; 66 ** 67 ** Must be transformed to: 68 ** 69 ** SELECT max(b) OVER (PARTITION BY c ORDER BY d) FROM ( 70 ** SELECT e, min(e) OVER (PARTITION BY a ORDER BY b), c, d, b FROM 71 ** SELECT a, e, c, d, b FROM t1 ORDER BY a, b 72 ** ) ORDER BY c, d 73 ** ) ORDER BY e; 74 ** 75 ** so that both min() and max() may process rows in the order defined by 76 ** their respective window declarations. 77 ** 78 ** INTERFACE WITH SELECT.C 79 ** 80 ** When processing the rewritten SELECT statement, code in select.c calls 81 ** sqlite3WhereBegin() to begin iterating through the results of the 82 ** sub-query, which is always implemented as a co-routine. It then calls 83 ** sqlite3WindowCodeStep() to process rows and finish the scan by calling 84 ** sqlite3WhereEnd(). 85 ** 86 ** sqlite3WindowCodeStep() generates VM code so that, for each row returned 87 ** by the sub-query a sub-routine (OP_Gosub) coded by select.c is invoked. 88 ** When the sub-routine is invoked: 89 ** 90 ** * The results of all window-functions for the row are stored 91 ** in the associated Window.regResult registers. 92 ** 93 ** * The required terminal values are stored in the current row of 94 ** temp table Window.iEphCsr. 95 ** 96 ** In some cases, depending on the window frame and the specific window 97 ** functions invoked, sqlite3WindowCodeStep() caches each entire partition 98 ** in a temp table before returning any rows. In other cases it does not. 99 ** This detail is encapsulated within this file, the code generated by 100 ** select.c is the same in either case. 101 ** 102 ** BUILT-IN WINDOW FUNCTIONS 103 ** 104 ** This implementation features the following built-in window functions: 105 ** 106 ** row_number() 107 ** rank() 108 ** dense_rank() 109 ** percent_rank() 110 ** cume_dist() 111 ** ntile(N) 112 ** lead(expr [, offset [, default]]) 113 ** lag(expr [, offset [, default]]) 114 ** first_value(expr) 115 ** last_value(expr) 116 ** nth_value(expr, N) 117 ** 118 ** These are the same built-in window functions supported by Postgres. 119 ** Although the behaviour of aggregate window functions (functions that 120 ** can be used as either aggregates or window functions) allows them to 121 ** be implemented using an API, built-in window functions are much more 122 ** esoteric. Additionally, some window functions (e.g. nth_value()) 123 ** may only be implemented by caching the entire partition in memory. 124 ** As such, some built-in window functions use the same API as aggregate 125 ** window functions and some are implemented directly using VDBE 126 ** instructions. Additionally, for those functions that use the API, the 127 ** window frame is sometimes modified before the SELECT statement is 128 ** rewritten. For example, regardless of the specified window frame, the 129 ** row_number() function always uses: 130 ** 131 ** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW 132 ** 133 ** See sqlite3WindowUpdate() for details. 134 ** 135 ** As well as some of the built-in window functions, aggregate window 136 ** functions min() and max() are implemented using VDBE instructions if 137 ** the start of the window frame is declared as anything other than 138 ** UNBOUNDED PRECEDING. 139 */ 140 141 /* 142 ** Implementation of built-in window function row_number(). Assumes that the 143 ** window frame has been coerced to: 144 ** 145 ** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW 146 */ 147 static void row_numberStepFunc( 148 sqlite3_context *pCtx, 149 int nArg, 150 sqlite3_value **apArg 151 ){ 152 i64 *p = (i64*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 153 if( p ) (*p)++; 154 UNUSED_PARAMETER(nArg); 155 UNUSED_PARAMETER(apArg); 156 } 157 static void row_numberValueFunc(sqlite3_context *pCtx){ 158 i64 *p = (i64*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 159 sqlite3_result_int64(pCtx, (p ? *p : 0)); 160 } 161 162 /* 163 ** Context object type used by rank(), dense_rank(), percent_rank() and 164 ** cume_dist(). 165 */ 166 struct CallCount { 167 i64 nValue; 168 i64 nStep; 169 i64 nTotal; 170 }; 171 172 /* 173 ** Implementation of built-in window function dense_rank(). Assumes that 174 ** the window frame has been set to: 175 ** 176 ** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW 177 */ 178 static void dense_rankStepFunc( 179 sqlite3_context *pCtx, 180 int nArg, 181 sqlite3_value **apArg 182 ){ 183 struct CallCount *p; 184 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 185 if( p ) p->nStep = 1; 186 UNUSED_PARAMETER(nArg); 187 UNUSED_PARAMETER(apArg); 188 } 189 static void dense_rankValueFunc(sqlite3_context *pCtx){ 190 struct CallCount *p; 191 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 192 if( p ){ 193 if( p->nStep ){ 194 p->nValue++; 195 p->nStep = 0; 196 } 197 sqlite3_result_int64(pCtx, p->nValue); 198 } 199 } 200 201 /* 202 ** Implementation of built-in window function nth_value(). This 203 ** implementation is used in "slow mode" only - when the EXCLUDE clause 204 ** is not set to the default value "NO OTHERS". 205 */ 206 struct NthValueCtx { 207 i64 nStep; 208 sqlite3_value *pValue; 209 }; 210 static void nth_valueStepFunc( 211 sqlite3_context *pCtx, 212 int nArg, 213 sqlite3_value **apArg 214 ){ 215 struct NthValueCtx *p; 216 p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 217 if( p ){ 218 i64 iVal; 219 switch( sqlite3_value_numeric_type(apArg[1]) ){ 220 case SQLITE_INTEGER: 221 iVal = sqlite3_value_int64(apArg[1]); 222 break; 223 case SQLITE_FLOAT: { 224 double fVal = sqlite3_value_double(apArg[1]); 225 if( sqlite3RealToI64(fVal)!=fVal ) goto error_out; 226 iVal = (i64)fVal; 227 break; 228 } 229 default: 230 goto error_out; 231 } 232 if( iVal<=0 ) goto error_out; 233 234 p->nStep++; 235 if( iVal==p->nStep ){ 236 p->pValue = sqlite3_value_dup(apArg[0]); 237 if( !p->pValue ){ 238 sqlite3_result_error_nomem(pCtx); 239 } 240 } 241 } 242 UNUSED_PARAMETER(nArg); 243 UNUSED_PARAMETER(apArg); 244 return; 245 246 error_out: 247 sqlite3_result_error( 248 pCtx, "second argument to nth_value must be a positive integer", -1 249 ); 250 } 251 static void nth_valueFinalizeFunc(sqlite3_context *pCtx){ 252 struct NthValueCtx *p; 253 p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, 0); 254 if( p && p->pValue ){ 255 sqlite3_result_value(pCtx, p->pValue); 256 sqlite3_value_free(p->pValue); 257 p->pValue = 0; 258 } 259 } 260 #define nth_valueInvFunc noopStepFunc 261 #define nth_valueValueFunc noopValueFunc 262 263 static void first_valueStepFunc( 264 sqlite3_context *pCtx, 265 int nArg, 266 sqlite3_value **apArg 267 ){ 268 struct NthValueCtx *p; 269 p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 270 if( p && p->pValue==0 ){ 271 p->pValue = sqlite3_value_dup(apArg[0]); 272 if( !p->pValue ){ 273 sqlite3_result_error_nomem(pCtx); 274 } 275 } 276 UNUSED_PARAMETER(nArg); 277 UNUSED_PARAMETER(apArg); 278 } 279 static void first_valueFinalizeFunc(sqlite3_context *pCtx){ 280 struct NthValueCtx *p; 281 p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 282 if( p && p->pValue ){ 283 sqlite3_result_value(pCtx, p->pValue); 284 sqlite3_value_free(p->pValue); 285 p->pValue = 0; 286 } 287 } 288 #define first_valueInvFunc noopStepFunc 289 #define first_valueValueFunc noopValueFunc 290 291 /* 292 ** Implementation of built-in window function rank(). Assumes that 293 ** the window frame has been set to: 294 ** 295 ** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW 296 */ 297 static void rankStepFunc( 298 sqlite3_context *pCtx, 299 int nArg, 300 sqlite3_value **apArg 301 ){ 302 struct CallCount *p; 303 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 304 if( p ){ 305 p->nStep++; 306 if( p->nValue==0 ){ 307 p->nValue = p->nStep; 308 } 309 } 310 UNUSED_PARAMETER(nArg); 311 UNUSED_PARAMETER(apArg); 312 } 313 static void rankValueFunc(sqlite3_context *pCtx){ 314 struct CallCount *p; 315 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 316 if( p ){ 317 sqlite3_result_int64(pCtx, p->nValue); 318 p->nValue = 0; 319 } 320 } 321 322 /* 323 ** Implementation of built-in window function percent_rank(). Assumes that 324 ** the window frame has been set to: 325 ** 326 ** GROUPS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING 327 */ 328 static void percent_rankStepFunc( 329 sqlite3_context *pCtx, 330 int nArg, 331 sqlite3_value **apArg 332 ){ 333 struct CallCount *p; 334 UNUSED_PARAMETER(nArg); assert( nArg==0 ); 335 UNUSED_PARAMETER(apArg); 336 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 337 if( p ){ 338 p->nTotal++; 339 } 340 } 341 static void percent_rankInvFunc( 342 sqlite3_context *pCtx, 343 int nArg, 344 sqlite3_value **apArg 345 ){ 346 struct CallCount *p; 347 UNUSED_PARAMETER(nArg); assert( nArg==0 ); 348 UNUSED_PARAMETER(apArg); 349 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 350 assert( p!=0 ); 351 p->nStep++; 352 } 353 static void percent_rankValueFunc(sqlite3_context *pCtx){ 354 struct CallCount *p; 355 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 356 if( p ){ 357 p->nValue = p->nStep; 358 if( p->nTotal>1 ){ 359 double r = (double)p->nValue / (double)(p->nTotal-1); 360 sqlite3_result_double(pCtx, r); 361 }else{ 362 sqlite3_result_double(pCtx, 0.0); 363 } 364 } 365 } 366 #define percent_rankFinalizeFunc percent_rankValueFunc 367 368 /* 369 ** Implementation of built-in window function cume_dist(). Assumes that 370 ** the window frame has been set to: 371 ** 372 ** GROUPS BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING 373 */ 374 static void cume_distStepFunc( 375 sqlite3_context *pCtx, 376 int nArg, 377 sqlite3_value **apArg 378 ){ 379 struct CallCount *p; 380 UNUSED_PARAMETER(nArg); assert( nArg==0 ); 381 UNUSED_PARAMETER(apArg); 382 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 383 if( p ){ 384 p->nTotal++; 385 } 386 } 387 static void cume_distInvFunc( 388 sqlite3_context *pCtx, 389 int nArg, 390 sqlite3_value **apArg 391 ){ 392 struct CallCount *p; 393 UNUSED_PARAMETER(nArg); assert( nArg==0 ); 394 UNUSED_PARAMETER(apArg); 395 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 396 assert( p!=0 ); 397 p->nStep++; 398 } 399 static void cume_distValueFunc(sqlite3_context *pCtx){ 400 struct CallCount *p; 401 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, 0); 402 if( p ){ 403 double r = (double)(p->nStep) / (double)(p->nTotal); 404 sqlite3_result_double(pCtx, r); 405 } 406 } 407 #define cume_distFinalizeFunc cume_distValueFunc 408 409 /* 410 ** Context object for ntile() window function. 411 */ 412 struct NtileCtx { 413 i64 nTotal; /* Total rows in partition */ 414 i64 nParam; /* Parameter passed to ntile(N) */ 415 i64 iRow; /* Current row */ 416 }; 417 418 /* 419 ** Implementation of ntile(). This assumes that the window frame has 420 ** been coerced to: 421 ** 422 ** ROWS CURRENT ROW AND UNBOUNDED FOLLOWING 423 */ 424 static void ntileStepFunc( 425 sqlite3_context *pCtx, 426 int nArg, 427 sqlite3_value **apArg 428 ){ 429 struct NtileCtx *p; 430 assert( nArg==1 ); UNUSED_PARAMETER(nArg); 431 p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 432 if( p ){ 433 if( p->nTotal==0 ){ 434 p->nParam = sqlite3_value_int64(apArg[0]); 435 if( p->nParam<=0 ){ 436 sqlite3_result_error( 437 pCtx, "argument of ntile must be a positive integer", -1 438 ); 439 } 440 } 441 p->nTotal++; 442 } 443 } 444 static void ntileInvFunc( 445 sqlite3_context *pCtx, 446 int nArg, 447 sqlite3_value **apArg 448 ){ 449 struct NtileCtx *p; 450 assert( nArg==1 ); UNUSED_PARAMETER(nArg); 451 UNUSED_PARAMETER(apArg); 452 p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 453 assert( p!=0 ); 454 p->iRow++; 455 } 456 static void ntileValueFunc(sqlite3_context *pCtx){ 457 struct NtileCtx *p; 458 p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 459 if( p && p->nParam>0 ){ 460 int nSize = (p->nTotal / p->nParam); 461 if( nSize==0 ){ 462 sqlite3_result_int64(pCtx, p->iRow+1); 463 }else{ 464 i64 nLarge = p->nTotal - p->nParam*nSize; 465 i64 iSmall = nLarge*(nSize+1); 466 i64 iRow = p->iRow; 467 468 assert( (nLarge*(nSize+1) + (p->nParam-nLarge)*nSize)==p->nTotal ); 469 470 if( iRowpVal); 501 p->pVal = sqlite3_value_dup(apArg[0]); 502 if( p->pVal==0 ){ 503 sqlite3_result_error_nomem(pCtx); 504 }else{ 505 p->nVal++; 506 } 507 } 508 } 509 static void last_valueInvFunc( 510 sqlite3_context *pCtx, 511 int nArg, 512 sqlite3_value **apArg 513 ){ 514 struct LastValueCtx *p; 515 UNUSED_PARAMETER(nArg); 516 UNUSED_PARAMETER(apArg); 517 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 518 if( ALWAYS(p) ){ 519 p->nVal--; 520 if( p->nVal==0 ){ 521 sqlite3_value_free(p->pVal); 522 p->pVal = 0; 523 } 524 } 525 } 526 static void last_valueValueFunc(sqlite3_context *pCtx){ 527 struct LastValueCtx *p; 528 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, 0); 529 if( p && p->pVal ){ 530 sqlite3_result_value(pCtx, p->pVal); 531 } 532 } 533 static void last_valueFinalizeFunc(sqlite3_context *pCtx){ 534 struct LastValueCtx *p; 535 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p)); 536 if( p && p->pVal ){ 537 sqlite3_result_value(pCtx, p->pVal); 538 sqlite3_value_free(p->pVal); 539 p->pVal = 0; 540 } 541 } 542 543 /* 544 ** Static names for the built-in window function names. These static 545 ** names are used, rather than string literals, so that FuncDef objects 546 ** can be associated with a particular window function by direct 547 ** comparison of the zName pointer. Example: 548 ** 549 ** if( pFuncDef->zName==row_valueName ){ ... } 550 */ 551 static const char row_numberName[] = "row_number"; 552 static const char dense_rankName[] = "dense_rank"; 553 static const char rankName[] = "rank"; 554 static const char percent_rankName[] = "percent_rank"; 555 static const char cume_distName[] = "cume_dist"; 556 static const char ntileName[] = "ntile"; 557 static const char last_valueName[] = "last_value"; 558 static const char nth_valueName[] = "nth_value"; 559 static const char first_valueName[] = "first_value"; 560 static const char leadName[] = "lead"; 561 static const char lagName[] = "lag"; 562 563 /* 564 ** No-op implementations of xStep() and xFinalize(). Used as place-holders 565 ** for built-in window functions that never call those interfaces. 566 ** 567 ** The noopValueFunc() is called but is expected to do nothing. The 568 ** noopStepFunc() is never called, and so it is marked with NO_TEST to 569 ** let the test coverage routine know not to expect this function to be 570 ** invoked. 571 */ 572 static void noopStepFunc( /*NO_TEST*/ 573 sqlite3_context *p, /*NO_TEST*/ 574 int n, /*NO_TEST*/ 575 sqlite3_value **a /*NO_TEST*/ 576 ){ /*NO_TEST*/ 577 UNUSED_PARAMETER(p); /*NO_TEST*/ 578 UNUSED_PARAMETER(n); /*NO_TEST*/ 579 UNUSED_PARAMETER(a); /*NO_TEST*/ 580 assert(0); /*NO_TEST*/ 581 } /*NO_TEST*/ 582 static void noopValueFunc(sqlite3_context *p){ UNUSED_PARAMETER(p); /*no-op*/ } 583 584 /* Window functions that use all window interfaces: xStep, xFinal, 585 ** xValue, and xInverse */ 586 #define WINDOWFUNCALL(name,nArg,extra) { \ 587 nArg, (SQLITE_FUNC_BUILTIN|SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \ 588 name ## StepFunc, name ## FinalizeFunc, name ## ValueFunc, \ 589 name ## InvFunc, name ## Name, {0} \ 590 } 591 592 /* Window functions that are implemented using bytecode and thus have 593 ** no-op routines for their methods */ 594 #define WINDOWFUNCNOOP(name,nArg,extra) { \ 595 nArg, (SQLITE_FUNC_BUILTIN|SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \ 596 noopStepFunc, noopValueFunc, noopValueFunc, \ 597 noopStepFunc, name ## Name, {0} \ 598 } 599 600 /* Window functions that use all window interfaces: xStep, the 601 ** same routine for xFinalize and xValue and which never call 602 ** xInverse. */ 603 #define WINDOWFUNCX(name,nArg,extra) { \ 604 nArg, (SQLITE_FUNC_BUILTIN|SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \ 605 name ## StepFunc, name ## ValueFunc, name ## ValueFunc, \ 606 noopStepFunc, name ## Name, {0} \ 607 } 608 609 610 /* 611 ** Register those built-in window functions that are not also aggregates. 612 */ 613 void sqlite3WindowFunctions(void){ 614 static FuncDef aWindowFuncs[] = { 615 WINDOWFUNCX(row_number, 0, 0), 616 WINDOWFUNCX(dense_rank, 0, 0), 617 WINDOWFUNCX(rank, 0, 0), 618 WINDOWFUNCALL(percent_rank, 0, 0), 619 WINDOWFUNCALL(cume_dist, 0, 0), 620 WINDOWFUNCALL(ntile, 1, 0), 621 WINDOWFUNCALL(last_value, 1, 0), 622 WINDOWFUNCALL(nth_value, 2, 0), 623 WINDOWFUNCALL(first_value, 1, 0), 624 WINDOWFUNCNOOP(lead, 1, 0), 625 WINDOWFUNCNOOP(lead, 2, 0), 626 WINDOWFUNCNOOP(lead, 3, 0), 627 WINDOWFUNCNOOP(lag, 1, 0), 628 WINDOWFUNCNOOP(lag, 2, 0), 629 WINDOWFUNCNOOP(lag, 3, 0), 630 }; 631 sqlite3InsertBuiltinFuncs(aWindowFuncs, ArraySize(aWindowFuncs)); 632 } 633 634 static Window *windowFind(Parse *pParse, Window *pList, const char *zName){ 635 Window *p; 636 for(p=pList; p; p=p->pNextWin){ 637 if( sqlite3StrICmp(p->zName, zName)==0 ) break; 638 } 639 if( p==0 ){ 640 sqlite3ErrorMsg(pParse, "no such window: %s", zName); 641 } 642 return p; 643 } 644 645 /* 646 ** This function is called immediately after resolving the function name 647 ** for a window function within a SELECT statement. Argument pList is a 648 ** linked list of WINDOW definitions for the current SELECT statement. 649 ** Argument pFunc is the function definition just resolved and pWin 650 ** is the Window object representing the associated OVER clause. This 651 ** function updates the contents of pWin as follows: 652 ** 653 ** * If the OVER clause referred to a named window (as in "max(x) OVER win"), 654 ** search list pList for a matching WINDOW definition, and update pWin 655 ** accordingly. If no such WINDOW clause can be found, leave an error 656 ** in pParse. 657 ** 658 ** * If the function is a built-in window function that requires the 659 ** window to be coerced (see "BUILT-IN WINDOW FUNCTIONS" at the top 660 ** of this file), pWin is updated here. 661 */ 662 void sqlite3WindowUpdate( 663 Parse *pParse, 664 Window *pList, /* List of named windows for this SELECT */ 665 Window *pWin, /* Window frame to update */ 666 FuncDef *pFunc /* Window function definition */ 667 ){ 668 if( pWin->zName && pWin->eFrmType==0 ){ 669 Window *p = windowFind(pParse, pList, pWin->zName); 670 if( p==0 ) return; 671 pWin->pPartition = sqlite3ExprListDup(pParse->db, p->pPartition, 0); 672 pWin->pOrderBy = sqlite3ExprListDup(pParse->db, p->pOrderBy, 0); 673 pWin->pStart = sqlite3ExprDup(pParse->db, p->pStart, 0); 674 pWin->pEnd = sqlite3ExprDup(pParse->db, p->pEnd, 0); 675 pWin->eStart = p->eStart; 676 pWin->eEnd = p->eEnd; 677 pWin->eFrmType = p->eFrmType; 678 pWin->eExclude = p->eExclude; 679 }else{ 680 sqlite3WindowChain(pParse, pWin, pList); 681 } 682 if( (pWin->eFrmType==TK_RANGE) 683 && (pWin->pStart || pWin->pEnd) 684 && (pWin->pOrderBy==0 || pWin->pOrderBy->nExpr!=1) 685 ){ 686 sqlite3ErrorMsg(pParse, 687 "RANGE with offset PRECEDING/FOLLOWING requires one ORDER BY expression" 688 ); 689 }else 690 if( pFunc->funcFlags & SQLITE_FUNC_WINDOW ){ 691 sqlite3 *db = pParse->db; 692 if( pWin->pFilter ){ 693 sqlite3ErrorMsg(pParse, 694 "FILTER clause may only be used with aggregate window functions" 695 ); 696 }else{ 697 struct WindowUpdate { 698 const char *zFunc; 699 int eFrmType; 700 int eStart; 701 int eEnd; 702 } aUp[] = { 703 { row_numberName, TK_ROWS, TK_UNBOUNDED, TK_CURRENT }, 704 { dense_rankName, TK_RANGE, TK_UNBOUNDED, TK_CURRENT }, 705 { rankName, TK_RANGE, TK_UNBOUNDED, TK_CURRENT }, 706 { percent_rankName, TK_GROUPS, TK_CURRENT, TK_UNBOUNDED }, 707 { cume_distName, TK_GROUPS, TK_FOLLOWING, TK_UNBOUNDED }, 708 { ntileName, TK_ROWS, TK_CURRENT, TK_UNBOUNDED }, 709 { leadName, TK_ROWS, TK_UNBOUNDED, TK_UNBOUNDED }, 710 { lagName, TK_ROWS, TK_UNBOUNDED, TK_CURRENT }, 711 }; 712 int i; 713 for(i=0; izName==aUp[i].zFunc ){ 715 sqlite3ExprDelete(db, pWin->pStart); 716 sqlite3ExprDelete(db, pWin->pEnd); 717 pWin->pEnd = pWin->pStart = 0; 718 pWin->eFrmType = aUp[i].eFrmType; 719 pWin->eStart = aUp[i].eStart; 720 pWin->eEnd = aUp[i].eEnd; 721 pWin->eExclude = 0; 722 if( pWin->eStart==TK_FOLLOWING ){ 723 pWin->pStart = sqlite3ExprInt32(db, 1); 724 } 725 break; 726 } 727 } 728 } 729 } 730 pWin->pWFunc = pFunc; 731 } 732 733 /* 734 ** Context object passed through sqlite3WalkExprList() to 735 ** selectWindowRewriteExprCb() by selectWindowRewriteEList(). 736 */ 737 typedef struct WindowRewrite WindowRewrite; 738 struct WindowRewrite { 739 Window *pWin; 740 SrcList *pSrc; 741 ExprList *pSub; 742 Table *pTab; 743 Select *pSubSelect; /* Current sub-select, if any */ 744 }; 745 746 /* 747 ** Callback function used by selectWindowRewriteEList(). If necessary, 748 ** this function appends to the output expression-list and updates 749 ** expression (*ppExpr) in place. 750 */ 751 static int selectWindowRewriteExprCb(Walker *pWalker, Expr *pExpr){ 752 struct WindowRewrite *p = pWalker->u.pRewrite; 753 Parse *pParse = pWalker->pParse; 754 assert( p!=0 ); 755 assert( p->pWin!=0 ); 756 757 /* If this function is being called from within a scalar sub-select 758 ** that used by the SELECT statement being processed, only process 759 ** TK_COLUMN and TK_AGGREGATE expressions that refer to it (the outer 760 ** SELECT). Do not process window functions at all, as they belong to the 761 ** scalar sub-select. */ 762 if( p->pSubSelect ){ 763 if( pExpr->op==TK_AGG_FUNCTION ){ 764 /* If op2==walkerDepth, then this expression aggregates over the rows 765 ** of the SELECT being processed, even though it is within a scalar 766 ** sub-select. In that case proceed, otherwise skip this node. */ 767 if( pExpr->op2!=pWalker->walkerDepth ) return WRC_Continue; 768 }else if( pExpr->op!=TK_COLUMN ){ 769 return WRC_Continue; 770 }else{ 771 int nSrc = p->pSrc->nSrc; 772 int i; 773 for(i=0; iiTable==p->pSrc->a[i].iCursor ) break; 775 } 776 if( i==nSrc ) return WRC_Continue; 777 } 778 } 779 780 switch( pExpr->op ){ 781 782 case TK_FUNCTION: 783 if( !ExprHasProperty(pExpr, EP_WinFunc) ){ 784 break; 785 }else{ 786 Window *pWin; 787 for(pWin=p->pWin; pWin; pWin=pWin->pNextWin){ 788 if( pExpr->y.pWin==pWin ){ 789 assert( pWin->pOwner==pExpr ); 790 return WRC_Prune; 791 } 792 } 793 } 794 /* no break */ deliberate_fall_through 795 796 case TK_IF_NULL_ROW: 797 case TK_AGG_FUNCTION: 798 case TK_COLUMN: { 799 int iCol = -1; 800 if( pParse->db->mallocFailed ) return WRC_Abort; 801 if( p->pSub ){ 802 int i; 803 for(i=0; ipSub->nExpr; i++){ 804 if( 0==sqlite3ExprCompare(0, p->pSub->a[i].pExpr, pExpr, -1) ){ 805 iCol = i; 806 break; 807 } 808 } 809 } 810 if( iCol<0 ){ 811 Expr *pDup = sqlite3ExprDup(pParse->db, pExpr, 0); 812 if( pDup && pDup->op==TK_AGG_FUNCTION ) pDup->op = TK_FUNCTION; 813 p->pSub = sqlite3ExprListAppend(pParse, p->pSub, pDup); 814 } 815 if( p->pSub ){ 816 int f = pExpr->flags & (EP_Collate|EP_OuterON|EP_InnerON); 817 int iJoin = pExpr->w.iJoin; 818 819 assert( ExprHasProperty(pExpr, EP_Static)==0 ); 820 ExprSetProperty(pExpr, EP_Static); 821 sqlite3ExprDelete(pParse->db, pExpr); 822 ExprClearProperty(pExpr, EP_Static); 823 memset(pExpr, 0, sizeof(Expr)); 824 825 pExpr->op = TK_COLUMN; 826 pExpr->iColumn = (iCol<0 ? p->pSub->nExpr-1: iCol); 827 pExpr->iTable = p->pWin->iEphCsr; 828 pExpr->y.pTab = p->pTab; 829 pExpr->flags = f; 830 if( (f & (EP_OuterON|EP_InnerON)) ) pExpr->w.iJoin = iJoin; 831 } 832 if( pParse->db->mallocFailed ) return WRC_Abort; 833 break; 834 } 835 836 default: /* no-op */ 837 break; 838 } 839 840 return WRC_Continue; 841 } 842 static int selectWindowRewriteSelectCb(Walker *pWalker, Select *pSelect){ 843 struct WindowRewrite *p = pWalker->u.pRewrite; 844 Select *pSave = p->pSubSelect; 845 if( pSave==pSelect ){ 846 return WRC_Continue; 847 }else{ 848 p->pSubSelect = pSelect; 849 pWalker->walkerDepth++; 850 sqlite3WalkSelect(pWalker, pSelect); 851 pWalker->walkerDepth--; 852 p->pSubSelect = pSave; 853 } 854 return WRC_Prune; 855 } 856 857 858 /* 859 ** Iterate through each expression in expression-list pEList. For each: 860 ** 861 ** * TK_COLUMN, 862 ** * aggregate function, or 863 ** * window function with a Window object that is not a member of the 864 ** Window list passed as the second argument (pWin). 865 ** 866 ** Append the node to output expression-list (*ppSub). And replace it 867 ** with a TK_COLUMN that reads the (N-1)th element of table 868 ** pWin->iEphCsr, where N is the number of elements in (*ppSub) after 869 ** appending the new one. 870 */ 871 static void selectWindowRewriteEList( 872 Parse *pParse, 873 Window *pWin, 874 SrcList *pSrc, 875 ExprList *pEList, /* Rewrite expressions in this list */ 876 Table *pTab, 877 ExprList **ppSub /* IN/OUT: Sub-select expression-list */ 878 ){ 879 Walker sWalker; 880 WindowRewrite sRewrite; 881 882 assert( pWin!=0 ); 883 memset(&sWalker, 0, sizeof(Walker)); 884 memset(&sRewrite, 0, sizeof(WindowRewrite)); 885 886 sRewrite.pSub = *ppSub; 887 sRewrite.pWin = pWin; 888 sRewrite.pSrc = pSrc; 889 sRewrite.pTab = pTab; 890 891 sWalker.pParse = pParse; 892 sWalker.xExprCallback = selectWindowRewriteExprCb; 893 sWalker.xSelectCallback = selectWindowRewriteSelectCb; 894 sWalker.u.pRewrite = &sRewrite; 895 896 (void)sqlite3WalkExprList(&sWalker, pEList); 897 898 *ppSub = sRewrite.pSub; 899 } 900 901 /* 902 ** Append a copy of each expression in expression-list pAppend to 903 ** expression list pList. Return a pointer to the result list. 904 */ 905 static ExprList *exprListAppendList( 906 Parse *pParse, /* Parsing context */ 907 ExprList *pList, /* List to which to append. Might be NULL */ 908 ExprList *pAppend, /* List of values to append. Might be NULL */ 909 int bIntToNull 910 ){ 911 if( pAppend ){ 912 int i; 913 int nInit = pList ? pList->nExpr : 0; 914 for(i=0; inExpr; i++){ 915 sqlite3 *db = pParse->db; 916 Expr *pDup = sqlite3ExprDup(db, pAppend->a[i].pExpr, 0); 917 if( db->mallocFailed ){ 918 sqlite3ExprDelete(db, pDup); 919 break; 920 } 921 if( bIntToNull ){ 922 int iDummy; 923 Expr *pSub; 924 pSub = sqlite3ExprSkipCollateAndLikely(pDup); 925 if( sqlite3ExprIsInteger(pSub, &iDummy, 0, 0) ){ 926 pSub->op = TK_NULL; 927 pSub->flags &= ~(EP_IntValue|EP_IsTrue|EP_IsFalse); 928 pSub->u.zToken = 0; 929 } 930 } 931 pList = sqlite3ExprListAppend(pParse, pList, pDup); 932 if( pList ) pList->a[nInit+i].fg.sortFlags = pAppend->a[i].fg.sortFlags; 933 } 934 } 935 return pList; 936 } 937 938 /* 939 ** When rewriting a query, if the new subquery in the FROM clause 940 ** contains TK_AGG_FUNCTION nodes that refer to an outer query, 941 ** then we have to increase the Expr->op2 values of those nodes 942 ** due to the extra subquery layer that was added. 943 ** 944 ** See also the incrAggDepth() routine in resolve.c 945 */ 946 static int sqlite3WindowExtraAggFuncDepth(Walker *pWalker, Expr *pExpr){ 947 if( pExpr->op==TK_AGG_FUNCTION 948 && pExpr->op2>=pWalker->walkerDepth 949 ){ 950 pExpr->op2++; 951 } 952 return WRC_Continue; 953 } 954 955 /* 956 ** Walker callback used to detect aggregate functions in the ORDER BY 957 ** clause of an otherwise non-aggregate SELECT. 958 */ 959 static int disallowAggregatesInOrderByCb(Walker *pWalker, Expr *pExpr){ 960 if( pExpr->op==TK_AGG_FUNCTION 961 && pExpr->pAggInfo==0 962 && pExpr->op2==pWalker->walkerDepth 963 ){ 964 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 965 sqlite3ErrorMsg(pWalker->pParse, 966 "misuse of aggregate: %s()", pExpr->u.zToken); 967 } 968 return WRC_Continue; 969 } 970 971 /* 972 ** If the SELECT statement passed as the second argument does not invoke 973 ** any SQL window functions, this function is a no-op. Otherwise, it 974 ** rewrites the SELECT statement so that window function xStep functions 975 ** are invoked in the correct order as described under "SELECT REWRITING" 976 ** at the top of this file. 977 */ 978 int sqlite3WindowRewrite(Parse *pParse, Select *p){ 979 int rc = SQLITE_OK; 980 if( p->pWin 981 && p->pPrior==0 982 && ALWAYS((p->selFlags & SF_WinRewrite)==0) 983 && ALWAYS(!IN_RENAME_OBJECT) 984 ){ 985 Vdbe *v = sqlite3GetVdbe(pParse); 986 sqlite3 *db = pParse->db; 987 Select *pSub = 0; /* The subquery */ 988 SrcList *pSrc = p->pSrc; 989 Expr *pWhere = p->pWhere; 990 ExprList *pGroupBy = p->pGroupBy; 991 Expr *pHaving = p->pHaving; 992 ExprList *pSort = 0; 993 994 ExprList *pSublist = 0; /* Expression list for sub-query */ 995 Window *pMWin = p->pWin; /* Main window object */ 996 Window *pWin; /* Window object iterator */ 997 Table *pTab; 998 Walker w; 999 1000 u32 selFlags = p->selFlags; 1001 1002 pTab = sqlite3DbMallocZero(db, sizeof(Table)); 1003 if( pTab==0 ){ 1004 return sqlite3ErrorToParser(db, SQLITE_NOMEM); 1005 } 1006 sqlite3AggInfoPersistWalkerInit(&w, pParse); 1007 sqlite3WalkSelect(&w, p); 1008 if( (p->selFlags & SF_Aggregate)==0 ){ 1009 w.xExprCallback = disallowAggregatesInOrderByCb; 1010 w.xSelectCallback = sqlite3WalkerDepthIncrease; 1011 w.xSelectCallback2 = sqlite3WalkerDepthDecrease; 1012 w.walkerDepth = 0; 1013 sqlite3WalkExprList(&w, p->pOrderBy); 1014 } 1015 1016 p->pSrc = 0; 1017 p->pWhere = 0; 1018 p->pGroupBy = 0; 1019 p->pHaving = 0; 1020 p->selFlags &= ~(u32)SF_Aggregate; 1021 p->selFlags |= SF_WinRewrite; 1022 1023 /* Create the ORDER BY clause for the sub-select. This is the concatenation 1024 ** of the window PARTITION and ORDER BY clauses. Then, if this makes it 1025 ** redundant, remove the ORDER BY from the parent SELECT. */ 1026 pSort = exprListAppendList(pParse, 0, pMWin->pPartition, 1); 1027 pSort = exprListAppendList(pParse, pSort, pMWin->pOrderBy, 1); 1028 if( pSort && p->pOrderBy && p->pOrderBy->nExpr<=pSort->nExpr ){ 1029 int nSave = pSort->nExpr; 1030 pSort->nExpr = p->pOrderBy->nExpr; 1031 if( sqlite3ExprListCompare(pSort, p->pOrderBy, -1)==0 ){ 1032 sqlite3ExprListDelete(db, p->pOrderBy); 1033 p->pOrderBy = 0; 1034 } 1035 pSort->nExpr = nSave; 1036 } 1037 1038 /* Assign a cursor number for the ephemeral table used to buffer rows. 1039 ** The OpenEphemeral instruction is coded later, after it is known how 1040 ** many columns the table will have. */ 1041 pMWin->iEphCsr = pParse->nTab++; 1042 pParse->nTab += 3; 1043 1044 selectWindowRewriteEList(pParse, pMWin, pSrc, p->pEList, pTab, &pSublist); 1045 selectWindowRewriteEList(pParse, pMWin, pSrc, p->pOrderBy, pTab, &pSublist); 1046 pMWin->nBufferCol = (pSublist ? pSublist->nExpr : 0); 1047 1048 /* Append the PARTITION BY and ORDER BY expressions to the to the 1049 ** sub-select expression list. They are required to figure out where 1050 ** boundaries for partitions and sets of peer rows lie. */ 1051 pSublist = exprListAppendList(pParse, pSublist, pMWin->pPartition, 0); 1052 pSublist = exprListAppendList(pParse, pSublist, pMWin->pOrderBy, 0); 1053 1054 /* Append the arguments passed to each window function to the 1055 ** sub-select expression list. Also allocate two registers for each 1056 ** window function - one for the accumulator, another for interim 1057 ** results. */ 1058 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){ 1059 ExprList *pArgs; 1060 assert( ExprUseXList(pWin->pOwner) ); 1061 assert( pWin->pWFunc!=0 ); 1062 pArgs = pWin->pOwner->x.pList; 1063 if( pWin->pWFunc->funcFlags & SQLITE_SUBTYPE ){ 1064 selectWindowRewriteEList(pParse, pMWin, pSrc, pArgs, pTab, &pSublist); 1065 pWin->iArgCol = (pSublist ? pSublist->nExpr : 0); 1066 pWin->bExprArgs = 1; 1067 }else{ 1068 pWin->iArgCol = (pSublist ? pSublist->nExpr : 0); 1069 pSublist = exprListAppendList(pParse, pSublist, pArgs, 0); 1070 } 1071 if( pWin->pFilter ){ 1072 Expr *pFilter = sqlite3ExprDup(db, pWin->pFilter, 0); 1073 pSublist = sqlite3ExprListAppend(pParse, pSublist, pFilter); 1074 } 1075 pWin->regAccum = ++pParse->nMem; 1076 pWin->regResult = ++pParse->nMem; 1077 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum); 1078 } 1079 1080 /* If there is no ORDER BY or PARTITION BY clause, and the window 1081 ** function accepts zero arguments, and there are no other columns 1082 ** selected (e.g. "SELECT row_number() OVER () FROM t1"), it is possible 1083 ** that pSublist is still NULL here. Add a constant expression here to 1084 ** keep everything legal in this case. 1085 */ 1086 if( pSublist==0 ){ 1087 pSublist = sqlite3ExprListAppend(pParse, 0, sqlite3ExprInt32(db, 0)); 1088 } 1089 1090 pSub = sqlite3SelectNew( 1091 pParse, pSublist, pSrc, pWhere, pGroupBy, pHaving, pSort, 0, 0 1092 ); 1093 TREETRACE(0x40,pParse,pSub, 1094 ("New window-function subquery in FROM clause of (%u/%p)\n", 1095 p->selId, p)); 1096 p->pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0); 1097 assert( pSub!=0 || p->pSrc==0 ); /* Due to db->mallocFailed test inside 1098 ** of sqlite3DbMallocRawNN() called from 1099 ** sqlite3SrcListAppend() */ 1100 if( p->pSrc==0 ){ 1101 sqlite3SelectDelete(db, pSub); 1102 }else if( sqlite3SrcItemAttachSubquery(pParse, &p->pSrc->a[0], pSub, 0) ){ 1103 Table *pTab2; 1104 p->pSrc->a[0].fg.isCorrelated = 1; 1105 sqlite3SrcListAssignCursors(pParse, p->pSrc); 1106 pSub->selFlags |= SF_Expanded|SF_OrderByReqd; 1107 pTab2 = sqlite3ResultSetOfSelect(pParse, pSub, SQLITE_AFF_NONE); 1108 pSub->selFlags |= (selFlags & SF_Aggregate); 1109 if( pTab2==0 ){ 1110 /* Might actually be some other kind of error, but in that case 1111 ** pParse->nErr will be set, so if SQLITE_NOMEM is set, we will get 1112 ** the correct error message regardless. */ 1113 rc = SQLITE_NOMEM; 1114 }else{ 1115 memcpy(pTab, pTab2, sizeof(Table)); 1116 pTab->tabFlags |= TF_Ephemeral; 1117 p->pSrc->a[0].pSTab = pTab; 1118 pTab = pTab2; 1119 memset(&w, 0, sizeof(w)); 1120 w.xExprCallback = sqlite3WindowExtraAggFuncDepth; 1121 w.xSelectCallback = sqlite3WalkerDepthIncrease; 1122 w.xSelectCallback2 = sqlite3WalkerDepthDecrease; 1123 sqlite3WalkSelect(&w, pSub); 1124 } 1125 } 1126 if( db->mallocFailed ) rc = SQLITE_NOMEM; 1127 1128 /* Defer deleting the temporary table pTab because if an error occurred, 1129 ** there could still be references to that table embedded in the 1130 ** result-set or ORDER BY clause of the SELECT statement p. */ 1131 sqlite3ParserAddCleanup(pParse, sqlite3DbFree, pTab); 1132 } 1133 1134 assert( rc==SQLITE_OK || pParse->nErr!=0 ); 1135 return rc; 1136 } 1137 1138 /* 1139 ** Unlink the Window object from the Select to which it is attached, 1140 ** if it is attached. 1141 */ 1142 void sqlite3WindowUnlinkFromSelect(Window *p){ 1143 if( p->ppThis ){ 1144 *p->ppThis = p->pNextWin; 1145 if( p->pNextWin ) p->pNextWin->ppThis = p->ppThis; 1146 p->ppThis = 0; 1147 } 1148 } 1149 1150 /* 1151 ** Free the Window object passed as the second argument. 1152 */ 1153 void sqlite3WindowDelete(sqlite3 *db, Window *p){ 1154 if( p ){ 1155 sqlite3WindowUnlinkFromSelect(p); 1156 sqlite3ExprDelete(db, p->pFilter); 1157 sqlite3ExprListDelete(db, p->pPartition); 1158 sqlite3ExprListDelete(db, p->pOrderBy); 1159 sqlite3ExprDelete(db, p->pEnd); 1160 sqlite3ExprDelete(db, p->pStart); 1161 sqlite3DbFree(db, p->zName); 1162 sqlite3DbFree(db, p->zBase); 1163 sqlite3DbFree(db, p); 1164 } 1165 } 1166 1167 /* 1168 ** Free the linked list of Window objects starting at the second argument. 1169 */ 1170 void sqlite3WindowListDelete(sqlite3 *db, Window *p){ 1171 while( p ){ 1172 Window *pNext = p->pNextWin; 1173 sqlite3WindowDelete(db, p); 1174 p = pNext; 1175 } 1176 } 1177 1178 /* 1179 ** The argument expression is an PRECEDING or FOLLOWING offset. The 1180 ** value should be a non-negative integer. If the value is not a 1181 ** constant, change it to NULL. The fact that it is then a non-negative 1182 ** integer will be caught later. But it is important not to leave 1183 ** variable values in the expression tree. 1184 */ 1185 static Expr *sqlite3WindowOffsetExpr(Parse *pParse, Expr *pExpr){ 1186 if( 0==sqlite3ExprIsConstant(0,pExpr) ){ 1187 if( IN_RENAME_OBJECT ) sqlite3RenameExprUnmap(pParse, pExpr); 1188 sqlite3ExprDelete(pParse->db, pExpr); 1189 pExpr = sqlite3ExprAlloc(pParse->db, TK_NULL, 0, 0); 1190 } 1191 return pExpr; 1192 } 1193 1194 /* 1195 ** Allocate and return a new Window object describing a Window Definition. 1196 */ 1197 Window *sqlite3WindowAlloc( 1198 Parse *pParse, /* Parsing context */ 1199 int eType, /* Frame type. TK_RANGE, TK_ROWS, TK_GROUPS, or 0 */ 1200 int eStart, /* Start type: CURRENT, PRECEDING, FOLLOWING, UNBOUNDED */ 1201 Expr *pStart, /* Start window size if TK_PRECEDING or FOLLOWING */ 1202 int eEnd, /* End type: CURRENT, FOLLOWING, TK_UNBOUNDED, PRECEDING */ 1203 Expr *pEnd, /* End window size if TK_FOLLOWING or PRECEDING */ 1204 u8 eExclude /* EXCLUDE clause */ 1205 ){ 1206 Window *pWin = 0; 1207 int bImplicitFrame = 0; 1208 1209 /* Parser assures the following: */ 1210 assert( eType==0 || eType==TK_RANGE || eType==TK_ROWS || eType==TK_GROUPS ); 1211 assert( eStart==TK_CURRENT || eStart==TK_PRECEDING 1212 || eStart==TK_UNBOUNDED || eStart==TK_FOLLOWING ); 1213 assert( eEnd==TK_CURRENT || eEnd==TK_FOLLOWING 1214 || eEnd==TK_UNBOUNDED || eEnd==TK_PRECEDING ); 1215 assert( (eStart==TK_PRECEDING || eStart==TK_FOLLOWING)==(pStart!=0) ); 1216 assert( (eEnd==TK_FOLLOWING || eEnd==TK_PRECEDING)==(pEnd!=0) ); 1217 1218 if( eType==0 ){ 1219 bImplicitFrame = 1; 1220 eType = TK_RANGE; 1221 } 1222 1223 /* Additionally, the 1224 ** starting boundary type may not occur earlier in the following list than 1225 ** the ending boundary type: 1226 ** 1227 ** UNBOUNDED PRECEDING 1228 ** PRECEDING 1229 ** CURRENT ROW 1230 ** FOLLOWING 1231 ** UNBOUNDED FOLLOWING 1232 ** 1233 ** The parser ensures that "UNBOUNDED PRECEDING" cannot be used as an ending 1234 ** boundary, and than "UNBOUNDED FOLLOWING" cannot be used as a starting 1235 ** frame boundary. 1236 */ 1237 if( (eStart==TK_CURRENT && eEnd==TK_PRECEDING) 1238 || (eStart==TK_FOLLOWING && (eEnd==TK_PRECEDING || eEnd==TK_CURRENT)) 1239 ){ 1240 sqlite3ErrorMsg(pParse, "unsupported frame specification"); 1241 goto windowAllocErr; 1242 } 1243 1244 pWin = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window)); 1245 if( pWin==0 ) goto windowAllocErr; 1246 pWin->eFrmType = eType; 1247 pWin->eStart = eStart; 1248 pWin->eEnd = eEnd; 1249 if( eExclude==0 && OptimizationDisabled(pParse->db, SQLITE_WindowFunc) ){ 1250 eExclude = TK_NO; 1251 } 1252 pWin->eExclude = eExclude; 1253 pWin->bImplicitFrame = bImplicitFrame; 1254 pWin->pEnd = sqlite3WindowOffsetExpr(pParse, pEnd); 1255 pWin->pStart = sqlite3WindowOffsetExpr(pParse, pStart); 1256 return pWin; 1257 1258 windowAllocErr: 1259 sqlite3ExprDelete(pParse->db, pEnd); 1260 sqlite3ExprDelete(pParse->db, pStart); 1261 return 0; 1262 } 1263 1264 /* 1265 ** Attach PARTITION and ORDER BY clauses pPartition and pOrderBy to window 1266 ** pWin. Also, if parameter pBase is not NULL, set pWin->zBase to the 1267 ** equivalent nul-terminated string. 1268 */ 1269 Window *sqlite3WindowAssemble( 1270 Parse *pParse, 1271 Window *pWin, 1272 ExprList *pPartition, 1273 ExprList *pOrderBy, 1274 Token *pBase 1275 ){ 1276 if( pWin ){ 1277 pWin->pPartition = pPartition; 1278 pWin->pOrderBy = pOrderBy; 1279 if( pBase ){ 1280 pWin->zBase = sqlite3DbStrNDup(pParse->db, pBase->z, pBase->n); 1281 } 1282 }else{ 1283 sqlite3ExprListDelete(pParse->db, pPartition); 1284 sqlite3ExprListDelete(pParse->db, pOrderBy); 1285 } 1286 return pWin; 1287 } 1288 1289 /* 1290 ** Window *pWin has just been created from a WINDOW clause. Token pBase 1291 ** is the base window. Earlier windows from the same WINDOW clause are 1292 ** stored in the linked list starting at pWin->pNextWin. This function 1293 ** either updates *pWin according to the base specification, or else 1294 ** leaves an error in pParse. 1295 */ 1296 void sqlite3WindowChain(Parse *pParse, Window *pWin, Window *pList){ 1297 if( pWin->zBase ){ 1298 sqlite3 *db = pParse->db; 1299 Window *pExist = windowFind(pParse, pList, pWin->zBase); 1300 if( pExist ){ 1301 const char *zErr = 0; 1302 /* Check for errors */ 1303 if( pWin->pPartition ){ 1304 zErr = "PARTITION clause"; 1305 }else if( pExist->pOrderBy && pWin->pOrderBy ){ 1306 zErr = "ORDER BY clause"; 1307 }else if( pExist->bImplicitFrame==0 ){ 1308 zErr = "frame specification"; 1309 } 1310 if( zErr ){ 1311 sqlite3ErrorMsg(pParse, 1312 "cannot override %s of window: %s", zErr, pWin->zBase 1313 ); 1314 }else{ 1315 pWin->pPartition = sqlite3ExprListDup(db, pExist->pPartition, 0); 1316 if( pExist->pOrderBy ){ 1317 assert( pWin->pOrderBy==0 ); 1318 pWin->pOrderBy = sqlite3ExprListDup(db, pExist->pOrderBy, 0); 1319 } 1320 sqlite3DbFree(db, pWin->zBase); 1321 pWin->zBase = 0; 1322 } 1323 } 1324 } 1325 } 1326 1327 /* 1328 ** Attach window object pWin to expression p. 1329 */ 1330 void sqlite3WindowAttach(Parse *pParse, Expr *p, Window *pWin){ 1331 if( p ){ 1332 assert( p->op==TK_FUNCTION ); 1333 assert( pWin ); 1334 assert( ExprIsFullSize(p) ); 1335 p->y.pWin = pWin; 1336 ExprSetProperty(p, EP_WinFunc|EP_FullSize); 1337 pWin->pOwner = p; 1338 if( (p->flags & EP_Distinct) && pWin->eFrmType!=TK_FILTER ){ 1339 sqlite3ErrorMsg(pParse, 1340 "DISTINCT is not supported for window functions" 1341 ); 1342 } 1343 }else{ 1344 sqlite3WindowDelete(pParse->db, pWin); 1345 } 1346 } 1347 1348 /* 1349 ** Possibly link window pWin into the list at pSel->pWin (window functions 1350 ** to be processed as part of SELECT statement pSel). The window is linked 1351 ** in if either (a) there are no other windows already linked to this 1352 ** SELECT, or (b) the windows already linked use a compatible window frame. 1353 */ 1354 void sqlite3WindowLink(Select *pSel, Window *pWin){ 1355 if( pSel ){ 1356 if( 0==pSel->pWin || 0==sqlite3WindowCompare(0, pSel->pWin, pWin, 0) ){ 1357 pWin->pNextWin = pSel->pWin; 1358 if( pSel->pWin ){ 1359 pSel->pWin->ppThis = &pWin->pNextWin; 1360 } 1361 pSel->pWin = pWin; 1362 pWin->ppThis = &pSel->pWin; 1363 }else{ 1364 if( sqlite3ExprListCompare(pWin->pPartition, pSel->pWin->pPartition,-1) ){ 1365 pSel->selFlags |= SF_MultiPart; 1366 } 1367 } 1368 } 1369 } 1370 1371 /* 1372 ** Return 0 if the two window objects are identical, 1 if they are 1373 ** different, or 2 if it cannot be determined if the objects are identical 1374 ** or not. Identical window objects can be processed in a single scan. 1375 */ 1376 int sqlite3WindowCompare( 1377 const Parse *pParse, 1378 const Window *p1, 1379 const Window *p2, 1380 int bFilter 1381 ){ 1382 int res; 1383 if( NEVER(p1==0) || NEVER(p2==0) ) return 1; 1384 if( p1->eFrmType!=p2->eFrmType ) return 1; 1385 if( p1->eStart!=p2->eStart ) return 1; 1386 if( p1->eEnd!=p2->eEnd ) return 1; 1387 if( p1->eExclude!=p2->eExclude ) return 1; 1388 if( sqlite3ExprCompare(pParse, p1->pStart, p2->pStart, -1) ) return 1; 1389 if( sqlite3ExprCompare(pParse, p1->pEnd, p2->pEnd, -1) ) return 1; 1390 if( (res = sqlite3ExprListCompare(p1->pPartition, p2->pPartition, -1)) ){ 1391 return res; 1392 } 1393 if( (res = sqlite3ExprListCompare(p1->pOrderBy, p2->pOrderBy, -1)) ){ 1394 return res; 1395 } 1396 if( bFilter ){ 1397 if( (res = sqlite3ExprCompare(pParse, p1->pFilter, p2->pFilter, -1)) ){ 1398 return res; 1399 } 1400 } 1401 return 0; 1402 } 1403 1404 1405 /* 1406 ** This is called by code in select.c before it calls sqlite3WhereBegin() 1407 ** to begin iterating through the sub-query results. It is used to allocate 1408 ** and initialize registers and cursors used by sqlite3WindowCodeStep(). 1409 */ 1410 void sqlite3WindowCodeInit(Parse *pParse, Select *pSelect){ 1411 Window *pWin; 1412 int nEphExpr; 1413 Window *pMWin; 1414 Vdbe *v; 1415 1416 assert( pSelect->pSrc->a[0].fg.isSubquery ); 1417 nEphExpr = pSelect->pSrc->a[0].u4.pSubq->pSelect->pEList->nExpr; 1418 pMWin = pSelect->pWin; 1419 v = sqlite3GetVdbe(pParse); 1420 1421 sqlite3MayAbort(pParse); 1422 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pMWin->iEphCsr, nEphExpr); 1423 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+1, pMWin->iEphCsr); 1424 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+2, pMWin->iEphCsr); 1425 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+3, pMWin->iEphCsr); 1426 1427 /* Allocate registers to use for PARTITION BY values, if any. Initialize 1428 ** said registers to NULL. */ 1429 if( pMWin->pPartition ){ 1430 int nExpr = pMWin->pPartition->nExpr; 1431 pMWin->regPart = pParse->nMem+1; 1432 pParse->nMem += nExpr; 1433 sqlite3VdbeAddOp3(v, OP_Null, 0, pMWin->regPart, pMWin->regPart+nExpr-1); 1434 } 1435 1436 pMWin->regOne = ++pParse->nMem; 1437 sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regOne); 1438 1439 if( pMWin->eExclude ){ 1440 pMWin->regStartRowid = ++pParse->nMem; 1441 pMWin->regEndRowid = ++pParse->nMem; 1442 pMWin->csrApp = pParse->nTab++; 1443 sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid); 1444 sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid); 1445 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->csrApp, pMWin->iEphCsr); 1446 return; 1447 } 1448 1449 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){ 1450 FuncDef *p = pWin->pWFunc; 1451 if( (p->funcFlags & SQLITE_FUNC_MINMAX) && pWin->eStart!=TK_UNBOUNDED ){ 1452 /* The inline versions of min() and max() require a single ephemeral 1453 ** table and 3 registers. The registers are used as follows: 1454 ** 1455 ** regApp+0: slot to copy min()/max() argument to for MakeRecord 1456 ** regApp+1: integer value used to ensure keys are unique 1457 ** regApp+2: output of MakeRecord 1458 */ 1459 ExprList *pList; 1460 KeyInfo *pKeyInfo; 1461 assert( ExprUseXList(pWin->pOwner) ); 1462 pList = pWin->pOwner->x.pList; 1463 pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pList, 0, 0); 1464 pWin->csrApp = pParse->nTab++; 1465 pWin->regApp = pParse->nMem+1; 1466 pParse->nMem += 3; 1467 if( pKeyInfo && pWin->pWFunc->zName[1]=='i' ){ 1468 assert( pKeyInfo->aSortFlags[0]==0 ); 1469 pKeyInfo->aSortFlags[0] = KEYINFO_ORDER_DESC; 1470 } 1471 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pWin->csrApp, 2); 1472 sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO); 1473 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1); 1474 } 1475 else if( p->zName==nth_valueName || p->zName==first_valueName ){ 1476 /* Allocate two registers at pWin->regApp. These will be used to 1477 ** store the start and end index of the current frame. */ 1478 pWin->regApp = pParse->nMem+1; 1479 pWin->csrApp = pParse->nTab++; 1480 pParse->nMem += 2; 1481 sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr); 1482 } 1483 else if( p->zName==leadName || p->zName==lagName ){ 1484 pWin->csrApp = pParse->nTab++; 1485 sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr); 1486 } 1487 } 1488 } 1489 1490 #define WINDOW_STARTING_INT 0 1491 #define WINDOW_ENDING_INT 1 1492 #define WINDOW_NTH_VALUE_INT 2 1493 #define WINDOW_STARTING_NUM 3 1494 #define WINDOW_ENDING_NUM 4 1495 1496 /* 1497 ** A "PRECEDING " (eCond==0) or "FOLLOWING " (eCond==1) or the 1498 ** value of the second argument to nth_value() (eCond==2) has just been 1499 ** evaluated and the result left in register reg. This function generates VM 1500 ** code to check that the value is a non-negative integer and throws an 1501 ** exception if it is not. 1502 */ 1503 static void windowCheckValue(Parse *pParse, int reg, int eCond){ 1504 static const char *azErr[] = { 1505 "frame starting offset must be a non-negative integer", 1506 "frame ending offset must be a non-negative integer", 1507 "second argument to nth_value must be a positive integer", 1508 "frame starting offset must be a non-negative number", 1509 "frame ending offset must be a non-negative number", 1510 }; 1511 static int aOp[] = { OP_Ge, OP_Ge, OP_Gt, OP_Ge, OP_Ge }; 1512 Vdbe *v = sqlite3GetVdbe(pParse); 1513 int regZero = sqlite3GetTempReg(pParse); 1514 assert( eCond>=0 && eCond=WINDOW_STARTING_NUM ){ 1517 int regString = sqlite3GetTempReg(pParse); 1518 sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC); 1519 sqlite3VdbeAddOp3(v, OP_Ge, regString, sqlite3VdbeCurrentAddr(v)+2, reg); 1520 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC|SQLITE_JUMPIFNULL); 1521 VdbeCoverage(v); 1522 assert( eCond==3 || eCond==4 ); 1523 VdbeCoverageIf(v, eCond==3); 1524 VdbeCoverageIf(v, eCond==4); 1525 }else{ 1526 sqlite3VdbeAddOp2(v, OP_MustBeInt, reg, sqlite3VdbeCurrentAddr(v)+2); 1527 VdbeCoverage(v); 1528 assert( eCond==0 || eCond==1 || eCond==2 ); 1529 VdbeCoverageIf(v, eCond==0); 1530 VdbeCoverageIf(v, eCond==1); 1531 VdbeCoverageIf(v, eCond==2); 1532 } 1533 sqlite3VdbeAddOp3(v, aOp[eCond], regZero, sqlite3VdbeCurrentAddr(v)+2, reg); 1534 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC); 1535 VdbeCoverageNeverNullIf(v, eCond==0); /* NULL case captured by */ 1536 VdbeCoverageNeverNullIf(v, eCond==1); /* the OP_MustBeInt */ 1537 VdbeCoverageNeverNullIf(v, eCond==2); 1538 VdbeCoverageNeverNullIf(v, eCond==3); /* NULL case caught by */ 1539 VdbeCoverageNeverNullIf(v, eCond==4); /* the OP_Ge */ 1540 sqlite3MayAbort(pParse); 1541 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_ERROR, OE_Abort); 1542 sqlite3VdbeAppendP4(v, (void*)azErr[eCond], P4_STATIC); 1543 sqlite3ReleaseTempReg(pParse, regZero); 1544 } 1545 1546 /* 1547 ** Return the number of arguments passed to the window-function associated 1548 ** with the object passed as the only argument to this function. 1549 */ 1550 static int windowArgCount(Window *pWin){ 1551 const ExprList *pList; 1552 assert( ExprUseXList(pWin->pOwner) ); 1553 pList = pWin->pOwner->x.pList; 1554 return (pList ? pList->nExpr : 0); 1555 } 1556 1557 typedef struct WindowCodeArg WindowCodeArg; 1558 typedef struct WindowCsrAndReg WindowCsrAndReg; 1559 1560 /* 1561 ** See comments above struct WindowCodeArg. 1562 */ 1563 struct WindowCsrAndReg { 1564 int csr; /* Cursor number */ 1565 int reg; /* First in array of peer values */ 1566 }; 1567 1568 /* 1569 ** A single instance of this structure is allocated on the stack by 1570 ** sqlite3WindowCodeStep() and a pointer to it passed to the various helper 1571 ** routines. This is to reduce the number of arguments required by each 1572 ** helper function. 1573 ** 1574 ** regArg: 1575 ** Each window function requires an accumulator register (just as an 1576 ** ordinary aggregate function does). This variable is set to the first 1577 ** in an array of accumulator registers - one for each window function 1578 ** in the WindowCodeArg.pMWin list. 1579 ** 1580 ** eDelete: 1581 ** The window functions implementation sometimes caches the input rows 1582 ** that it processes in a temporary table. If it is not zero, this 1583 ** variable indicates when rows may be removed from the temp table (in 1584 ** order to reduce memory requirements - it would always be safe just 1585 ** to leave them there). Possible values for eDelete are: 1586 ** 1587 ** WINDOW_RETURN_ROW: 1588 ** An input row can be discarded after it is returned to the caller. 1589 ** 1590 ** WINDOW_AGGINVERSE: 1591 ** An input row can be discarded after the window functions xInverse() 1592 ** callbacks have been invoked in it. 1593 ** 1594 ** WINDOW_AGGSTEP: 1595 ** An input row can be discarded after the window functions xStep() 1596 ** callbacks have been invoked in it. 1597 ** 1598 ** start,current,end 1599 ** Consider a window-frame similar to the following: 1600 ** 1601 ** (ORDER BY a, b GROUPS BETWEEN 2 PRECEDING AND 2 FOLLOWING) 1602 ** 1603 ** The windows functions implementation caches the input rows in a temp 1604 ** table, sorted by "a, b" (it actually populates the cache lazily, and 1605 ** aggressively removes rows once they are no longer required, but that's 1606 ** a mere detail). It keeps three cursors open on the temp table. One 1607 ** (current) that points to the next row to return to the query engine 1608 ** once its window function values have been calculated. Another (end) 1609 ** points to the next row to call the xStep() method of each window function 1610 ** on (so that it is 2 groups ahead of current). And a third (start) that 1611 ** points to the next row to call the xInverse() method of each window 1612 ** function on. 1613 ** 1614 ** Each cursor (start, current and end) consists of a VDBE cursor 1615 ** (WindowCsrAndReg.csr) and an array of registers (starting at 1616 ** WindowCodeArg.reg) that always contains a copy of the peer values 1617 ** read from the corresponding cursor. 1618 ** 1619 ** Depending on the window-frame in question, all three cursors may not 1620 ** be required. In this case both WindowCodeArg.csr and reg are set to 1621 ** 0. 1622 */ 1623 struct WindowCodeArg { 1624 Parse *pParse; /* Parse context */ 1625 Window *pMWin; /* First in list of functions being processed */ 1626 Vdbe *pVdbe; /* VDBE object */ 1627 int addrGosub; /* OP_Gosub to this address to return one row */ 1628 int regGosub; /* Register used with OP_Gosub(addrGosub) */ 1629 int regArg; /* First in array of accumulator registers */ 1630 int eDelete; /* See above */ 1631 int regRowid; 1632 1633 WindowCsrAndReg start; 1634 WindowCsrAndReg current; 1635 WindowCsrAndReg end; 1636 }; 1637 1638 /* 1639 ** Generate VM code to read the window frames peer values from cursor csr into 1640 ** an array of registers starting at reg. 1641 */ 1642 static void windowReadPeerValues( 1643 WindowCodeArg *p, 1644 int csr, 1645 int reg 1646 ){ 1647 Window *pMWin = p->pMWin; 1648 ExprList *pOrderBy = pMWin->pOrderBy; 1649 if( pOrderBy ){ 1650 Vdbe *v = sqlite3GetVdbe(p->pParse); 1651 ExprList *pPart = pMWin->pPartition; 1652 int iColOff = pMWin->nBufferCol + (pPart ? pPart->nExpr : 0); 1653 int i; 1654 for(i=0; inExpr; i++){ 1655 sqlite3VdbeAddOp3(v, OP_Column, csr, iColOff+i, reg+i); 1656 } 1657 } 1658 } 1659 1660 /* 1661 ** Generate VM code to invoke either xStep() (if bInverse is 0) or 1662 ** xInverse (if bInverse is non-zero) for each window function in the 1663 ** linked list starting at pMWin. Or, for built-in window functions 1664 ** that do not use the standard function API, generate the required 1665 ** inline VM code. 1666 ** 1667 ** If argument csr is greater than or equal to 0, then argument reg is 1668 ** the first register in an array of registers guaranteed to be large 1669 ** enough to hold the array of arguments for each function. In this case 1670 ** the arguments are extracted from the current row of csr into the 1671 ** array of registers before invoking OP_AggStep or OP_AggInverse 1672 ** 1673 ** Or, if csr is less than zero, then the array of registers at reg is 1674 ** already populated with all columns from the current row of the sub-query. 1675 ** 1676 ** If argument regPartSize is non-zero, then it is a register containing the 1677 ** number of rows in the current partition. 1678 */ 1679 static void windowAggStep( 1680 WindowCodeArg *p, 1681 Window *pMWin, /* Linked list of window functions */ 1682 int csr, /* Read arguments from this cursor */ 1683 int bInverse, /* True to invoke xInverse instead of xStep */ 1684 int reg /* Array of registers */ 1685 ){ 1686 Parse *pParse = p->pParse; 1687 Vdbe *v = sqlite3GetVdbe(pParse); 1688 Window *pWin; 1689 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){ 1690 FuncDef *pFunc = pWin->pWFunc; 1691 int regArg; 1692 int nArg = pWin->bExprArgs ? 0 : windowArgCount(pWin); 1693 int i; 1694 int addrIf = 0; 1695 1696 assert( bInverse==0 || pWin->eStart!=TK_UNBOUNDED ); 1697 1698 /* All OVER clauses in the same window function aggregate step must 1699 ** be the same. */ 1700 assert( pWin==pMWin || sqlite3WindowCompare(pParse,pWin,pMWin,0)!=1 ); 1701 1702 for(i=0; izName!=nth_valueName ){ 1704 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+i, reg+i); 1705 }else{ 1706 sqlite3VdbeAddOp3(v, OP_Column, pMWin->iEphCsr, pWin->iArgCol+i, reg+i); 1707 } 1708 } 1709 regArg = reg; 1710 1711 if( pWin->pFilter ){ 1712 int regTmp; 1713 assert( ExprUseXList(pWin->pOwner) ); 1714 assert( pWin->bExprArgs || !nArg ||nArg==pWin->pOwner->x.pList->nExpr ); 1715 assert( pWin->bExprArgs || nArg ||pWin->pOwner->x.pList==0 ); 1716 regTmp = sqlite3GetTempReg(pParse); 1717 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+nArg,regTmp); 1718 addrIf = sqlite3VdbeAddOp3(v, OP_IfNot, regTmp, 0, 1); 1719 VdbeCoverage(v); 1720 sqlite3ReleaseTempReg(pParse, regTmp); 1721 } 1722 1723 if( pMWin->regStartRowid==0 1724 && (pFunc->funcFlags & SQLITE_FUNC_MINMAX) 1725 && (pWin->eStart!=TK_UNBOUNDED) 1726 ){ 1727 int addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regArg); 1728 VdbeCoverage(v); 1729 if( bInverse==0 ){ 1730 sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1, 1); 1731 sqlite3VdbeAddOp2(v, OP_SCopy, regArg, pWin->regApp); 1732 sqlite3VdbeAddOp3(v, OP_MakeRecord, pWin->regApp, 2, pWin->regApp+2); 1733 sqlite3VdbeAddOp2(v, OP_IdxInsert, pWin->csrApp, pWin->regApp+2); 1734 }else{ 1735 sqlite3VdbeAddOp4Int(v, OP_SeekGE, pWin->csrApp, 0, regArg, 1); 1736 VdbeCoverageNeverTaken(v); 1737 sqlite3VdbeAddOp1(v, OP_Delete, pWin->csrApp); 1738 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2); 1739 } 1740 sqlite3VdbeJumpHere(v, addrIsNull); 1741 }else if( pWin->regApp ){ 1742 assert( pWin->pFilter==0 ); 1743 assert( pFunc->zName==nth_valueName 1744 || pFunc->zName==first_valueName 1745 ); 1746 assert( bInverse==0 || bInverse==1 ); 1747 sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1-bInverse, 1); 1748 }else if( pFunc->xSFunc!=noopStepFunc ){ 1749 if( pWin->bExprArgs ){ 1750 int iOp = sqlite3VdbeCurrentAddr(v); 1751 int iEnd; 1752 1753 assert( ExprUseXList(pWin->pOwner) ); 1754 nArg = pWin->pOwner->x.pList->nExpr; 1755 regArg = sqlite3GetTempRange(pParse, nArg); 1756 sqlite3ExprCodeExprList(pParse, pWin->pOwner->x.pList, regArg, 0, 0); 1757 1758 for(iEnd=sqlite3VdbeCurrentAddr(v); iOpopcode==OP_Column && pOp->p1==pMWin->iEphCsr ){ 1761 pOp->p1 = csr; 1762 } 1763 } 1764 } 1765 if( pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){ 1766 CollSeq *pColl; 1767 assert( nArg>0 ); 1768 assert( ExprUseXList(pWin->pOwner) ); 1769 pColl = sqlite3ExprNNCollSeq(pParse, pWin->pOwner->x.pList->a[0].pExpr); 1770 sqlite3VdbeAddOp4(v, OP_CollSeq, 0,0,0, (const char*)pColl, P4_COLLSEQ); 1771 } 1772 sqlite3VdbeAddOp3(v, bInverse? OP_AggInverse : OP_AggStep, 1773 bInverse, regArg, pWin->regAccum); 1774 sqlite3VdbeAppendP4(v, pFunc, P4_FUNCDEF); 1775 sqlite3VdbeChangeP5(v, (u16)nArg); 1776 if( pWin->bExprArgs ){ 1777 sqlite3ReleaseTempRange(pParse, regArg, nArg); 1778 } 1779 } 1780 1781 if( addrIf ) sqlite3VdbeJumpHere(v, addrIf); 1782 } 1783 } 1784 1785 /* 1786 ** Values that may be passed as the second argument to windowCodeOp(). 1787 */ 1788 #define WINDOW_RETURN_ROW 1 1789 #define WINDOW_AGGINVERSE 2 1790 #define WINDOW_AGGSTEP 3 1791 1792 /* 1793 ** Generate VM code to invoke either xValue() (bFin==0) or xFinalize() 1794 ** (bFin==1) for each window function in the linked list starting at 1795 ** pMWin. Or, for built-in window-functions that do not use the standard 1796 ** API, generate the equivalent VM code. 1797 */ 1798 static void windowAggFinal(WindowCodeArg *p, int bFin){ 1799 Parse *pParse = p->pParse; 1800 Window *pMWin = p->pMWin; 1801 Vdbe *v = sqlite3GetVdbe(pParse); 1802 Window *pWin; 1803 1804 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){ 1805 if( pMWin->regStartRowid==0 1806 && (pWin->pWFunc->funcFlags & SQLITE_FUNC_MINMAX) 1807 && (pWin->eStart!=TK_UNBOUNDED) 1808 ){ 1809 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult); 1810 sqlite3VdbeAddOp1(v, OP_Last, pWin->csrApp); 1811 VdbeCoverage(v); 1812 sqlite3VdbeAddOp3(v, OP_Column, pWin->csrApp, 0, pWin->regResult); 1813 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2); 1814 }else if( pWin->regApp ){ 1815 assert( pMWin->regStartRowid==0 ); 1816 }else{ 1817 int nArg = windowArgCount(pWin); 1818 if( bFin ){ 1819 sqlite3VdbeAddOp2(v, OP_AggFinal, pWin->regAccum, nArg); 1820 sqlite3VdbeAppendP4(v, pWin->pWFunc, P4_FUNCDEF); 1821 sqlite3VdbeAddOp2(v, OP_Copy, pWin->regAccum, pWin->regResult); 1822 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum); 1823 }else{ 1824 sqlite3VdbeAddOp3(v, OP_AggValue,pWin->regAccum,nArg,pWin->regResult); 1825 sqlite3VdbeAppendP4(v, pWin->pWFunc, P4_FUNCDEF); 1826 } 1827 } 1828 } 1829 } 1830 1831 /* 1832 ** Generate code to calculate the current values of all window functions in the 1833 ** p->pMWin list by doing a full scan of the current window frame. Store the 1834 ** results in the Window.regResult registers, ready to return the upper 1835 ** layer. 1836 */ 1837 static void windowFullScan(WindowCodeArg *p){ 1838 Window *pWin; 1839 Parse *pParse = p->pParse; 1840 Window *pMWin = p->pMWin; 1841 Vdbe *v = p->pVdbe; 1842 1843 int regCRowid = 0; /* Current rowid value */ 1844 int regCPeer = 0; /* Current peer values */ 1845 int regRowid = 0; /* AggStep rowid value */ 1846 int regPeer = 0; /* AggStep peer values */ 1847 1848 int nPeer; 1849 int lblNext; 1850 int lblBrk; 1851 int addrNext; 1852 int csr; 1853 1854 VdbeModuleComment((v, "windowFullScan begin")); 1855 1856 assert( pMWin!=0 ); 1857 csr = pMWin->csrApp; 1858 nPeer = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0); 1859 1860 lblNext = sqlite3VdbeMakeLabel(pParse); 1861 lblBrk = sqlite3VdbeMakeLabel(pParse); 1862 1863 regCRowid = sqlite3GetTempReg(pParse); 1864 regRowid = sqlite3GetTempReg(pParse); 1865 if( nPeer ){ 1866 regCPeer = sqlite3GetTempRange(pParse, nPeer); 1867 regPeer = sqlite3GetTempRange(pParse, nPeer); 1868 } 1869 1870 sqlite3VdbeAddOp2(v, OP_Rowid, pMWin->iEphCsr, regCRowid); 1871 windowReadPeerValues(p, pMWin->iEphCsr, regCPeer); 1872 1873 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){ 1874 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum); 1875 } 1876 1877 sqlite3VdbeAddOp3(v, OP_SeekGE, csr, lblBrk, pMWin->regStartRowid); 1878 VdbeCoverage(v); 1879 addrNext = sqlite3VdbeCurrentAddr(v); 1880 sqlite3VdbeAddOp2(v, OP_Rowid, csr, regRowid); 1881 sqlite3VdbeAddOp3(v, OP_Gt, pMWin->regEndRowid, lblBrk, regRowid); 1882 VdbeCoverageNeverNull(v); 1883 1884 if( pMWin->eExclude==TK_CURRENT ){ 1885 sqlite3VdbeAddOp3(v, OP_Eq, regCRowid, lblNext, regRowid); 1886 VdbeCoverageNeverNull(v); 1887 }else if( pMWin->eExclude!=TK_NO ){ 1888 int addr; 1889 int addrEq = 0; 1890 KeyInfo *pKeyInfo = 0; 1891 1892 if( pMWin->pOrderBy ){ 1893 pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pMWin->pOrderBy, 0, 0); 1894 } 1895 if( pMWin->eExclude==TK_TIES ){ 1896 addrEq = sqlite3VdbeAddOp3(v, OP_Eq, regCRowid, 0, regRowid); 1897 VdbeCoverageNeverNull(v); 1898 } 1899 if( pKeyInfo ){ 1900 windowReadPeerValues(p, csr, regPeer); 1901 sqlite3VdbeAddOp3(v, OP_Compare, regPeer, regCPeer, nPeer); 1902 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO); 1903 addr = sqlite3VdbeCurrentAddr(v)+1; 1904 sqlite3VdbeAddOp3(v, OP_Jump, addr, lblNext, addr); 1905 VdbeCoverageEqNe(v); 1906 }else{ 1907 sqlite3VdbeAddOp2(v, OP_Goto, 0, lblNext); 1908 } 1909 if( addrEq ) sqlite3VdbeJumpHere(v, addrEq); 1910 } 1911 1912 windowAggStep(p, pMWin, csr, 0, p->regArg); 1913 1914 sqlite3VdbeResolveLabel(v, lblNext); 1915 sqlite3VdbeAddOp2(v, OP_Next, csr, addrNext); 1916 VdbeCoverage(v); 1917 sqlite3VdbeJumpHere(v, addrNext-1); 1918 sqlite3VdbeJumpHere(v, addrNext+1); 1919 sqlite3ReleaseTempReg(pParse, regRowid); 1920 sqlite3ReleaseTempReg(pParse, regCRowid); 1921 if( nPeer ){ 1922 sqlite3ReleaseTempRange(pParse, regPeer, nPeer); 1923 sqlite3ReleaseTempRange(pParse, regCPeer, nPeer); 1924 } 1925 1926 windowAggFinal(p, 1); 1927 VdbeModuleComment((v, "windowFullScan end")); 1928 } 1929 1930 /* 1931 ** Invoke the sub-routine at regGosub (generated by code in select.c) to 1932 ** return the current row of Window.iEphCsr. If all window functions are 1933 ** aggregate window functions that use the standard API, a single 1934 ** OP_Gosub instruction is all that this routine generates. Extra VM code 1935 ** for per-row processing is only generated for the following built-in window 1936 ** functions: 1937 ** 1938 ** nth_value() 1939 ** first_value() 1940 ** lag() 1941 ** lead() 1942 */ 1943 static void windowReturnOneRow(WindowCodeArg *p){ 1944 Window *pMWin = p->pMWin; 1945 Vdbe *v = p->pVdbe; 1946 1947 if( pMWin->regStartRowid ){ 1948 windowFullScan(p); 1949 }else{ 1950 Parse *pParse = p->pParse; 1951 Window *pWin; 1952 1953 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){ 1954 FuncDef *pFunc = pWin->pWFunc; 1955 assert( ExprUseXList(pWin->pOwner) ); 1956 if( pFunc->zName==nth_valueName 1957 || pFunc->zName==first_valueName 1958 ){ 1959 int csr = pWin->csrApp; 1960 int lbl = sqlite3VdbeMakeLabel(pParse); 1961 int tmpReg = sqlite3GetTempReg(pParse); 1962 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult); 1963 1964 if( pFunc->zName==nth_valueName ){ 1965 sqlite3VdbeAddOp3(v, OP_Column,pMWin->iEphCsr,pWin->iArgCol+1,tmpReg); 1966 windowCheckValue(pParse, tmpReg, 2); 1967 }else{ 1968 sqlite3VdbeAddOp2(v, OP_Integer, 1, tmpReg); 1969 } 1970 sqlite3VdbeAddOp3(v, OP_Add, tmpReg, pWin->regApp, tmpReg); 1971 sqlite3VdbeAddOp3(v, OP_Gt, pWin->regApp+1, lbl, tmpReg); 1972 VdbeCoverageNeverNull(v); 1973 sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, 0, tmpReg); 1974 VdbeCoverageNeverTaken(v); 1975 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult); 1976 sqlite3VdbeResolveLabel(v, lbl); 1977 sqlite3ReleaseTempReg(pParse, tmpReg); 1978 } 1979 else if( pFunc->zName==leadName || pFunc->zName==lagName ){ 1980 int nArg = pWin->pOwner->x.pList->nExpr; 1981 int csr = pWin->csrApp; 1982 int lbl = sqlite3VdbeMakeLabel(pParse); 1983 int tmpReg = sqlite3GetTempReg(pParse); 1984 int iEph = pMWin->iEphCsr; 1985 1986 if( nArg<3 ){ 1987 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult); 1988 }else{ 1989 sqlite3VdbeAddOp3(v, OP_Column, iEph,pWin->iArgCol+2,pWin->regResult); 1990 } 1991 sqlite3VdbeAddOp2(v, OP_Rowid, iEph, tmpReg); 1992 if( nArg<2 ){ 1993 int val = (pFunc->zName==leadName ? 1 : -1); 1994 sqlite3VdbeAddOp2(v, OP_AddImm, tmpReg, val); 1995 }else{ 1996 int op = (pFunc->zName==leadName ? OP_Add : OP_Subtract); 1997 int tmpReg2 = sqlite3GetTempReg(pParse); 1998 sqlite3VdbeAddOp3(v, OP_Column, iEph, pWin->iArgCol+1, tmpReg2); 1999 sqlite3VdbeAddOp3(v, op, tmpReg2, tmpReg, tmpReg); 2000 sqlite3ReleaseTempReg(pParse, tmpReg2); 2001 } 2002 2003 sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, lbl, tmpReg); 2004 VdbeCoverage(v); 2005 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult); 2006 sqlite3VdbeResolveLabel(v, lbl); 2007 sqlite3ReleaseTempReg(pParse, tmpReg); 2008 } 2009 } 2010 } 2011 sqlite3VdbeAddOp2(v, OP_Gosub, p->regGosub, p->addrGosub); 2012 } 2013 2014 /* 2015 ** Generate code to set the accumulator register for each window function 2016 ** in the linked list passed as the second argument to NULL. And perform 2017 ** any equivalent initialization required by any built-in window functions 2018 ** in the list. 2019 */ 2020 static int windowInitAccum(Parse *pParse, Window *pMWin){ 2021 Vdbe *v = sqlite3GetVdbe(pParse); 2022 int regArg; 2023 int nArg = 0; 2024 Window *pWin; 2025 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){ 2026 FuncDef *pFunc = pWin->pWFunc; 2027 assert( pWin->regAccum ); 2028 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum); 2029 nArg = MAX(nArg, windowArgCount(pWin)); 2030 if( pMWin->regStartRowid==0 ){ 2031 if( pFunc->zName==nth_valueName || pFunc->zName==first_valueName ){ 2032 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp); 2033 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1); 2034 } 2035 2036 if( (pFunc->funcFlags & SQLITE_FUNC_MINMAX) && pWin->csrApp ){ 2037 assert( pWin->eStart!=TK_UNBOUNDED ); 2038 sqlite3VdbeAddOp1(v, OP_ResetSorter, pWin->csrApp); 2039 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1); 2040 } 2041 } 2042 } 2043 regArg = pParse->nMem+1; 2044 pParse->nMem += nArg; 2045 return regArg; 2046 } 2047 2048 /* 2049 ** Return true if the current frame should be cached in the ephemeral table, 2050 ** even if there are no xInverse() calls required. 2051 */ 2052 static int windowCacheFrame(Window *pMWin){ 2053 Window *pWin; 2054 if( pMWin->regStartRowid ) return 1; 2055 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){ 2056 FuncDef *pFunc = pWin->pWFunc; 2057 if( (pFunc->zName==nth_valueName) 2058 || (pFunc->zName==first_valueName) 2059 || (pFunc->zName==leadName) 2060 || (pFunc->zName==lagName) 2061 ){ 2062 return 1; 2063 } 2064 } 2065 return 0; 2066 } 2067 2068 /* 2069 ** regOld and regNew are each the first register in an array of size 2070 ** pOrderBy->nExpr. This function generates code to compare the two 2071 ** arrays of registers using the collation sequences and other comparison 2072 ** parameters specified by pOrderBy. 2073 ** 2074 ** If the two arrays are not equal, the contents of regNew is copied to 2075 ** regOld and control falls through. Otherwise, if the contents of the arrays 2076 ** are equal, an OP_Goto is executed. The address of the OP_Goto is returned. 2077 */ 2078 static void windowIfNewPeer( 2079 Parse *pParse, 2080 ExprList *pOrderBy, 2081 int regNew, /* First in array of new values */ 2082 int regOld, /* First in array of old values */ 2083 int addr /* Jump here */ 2084 ){ 2085 Vdbe *v = sqlite3GetVdbe(pParse); 2086 if( pOrderBy ){ 2087 int nVal = pOrderBy->nExpr; 2088 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pOrderBy, 0, 0); 2089 sqlite3VdbeAddOp3(v, OP_Compare, regOld, regNew, nVal); 2090 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO); 2091 sqlite3VdbeAddOp3(v, OP_Jump, 2092 sqlite3VdbeCurrentAddr(v)+1, addr, sqlite3VdbeCurrentAddr(v)+1 2093 ); 2094 VdbeCoverageEqNe(v); 2095 sqlite3VdbeAddOp3(v, OP_Copy, regNew, regOld, nVal-1); 2096 }else{ 2097 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr); 2098 } 2099 } 2100 2101 /* 2102 ** This function is called as part of generating VM programs for RANGE 2103 ** offset PRECEDING/FOLLOWING frame boundaries. Assuming "ASC" order for 2104 ** the ORDER BY term in the window, and that argument op is OP_Ge, it generates 2105 ** code equivalent to: 2106 ** 2107 ** if( csr1.peerVal + regVal >= csr2.peerVal ) goto lbl; 2108 ** 2109 ** The value of parameter op may also be OP_Gt or OP_Le. In these cases the 2110 ** operator in the above pseudo-code is replaced with ">" or "<=", respectively. 2111 ** 2112 ** If the sort-order for the ORDER BY term in the window is DESC, then the 2113 ** comparison is reversed. Instead of adding regVal to csr1.peerVal, it is 2114 ** subtracted. And the comparison operator is inverted to - ">=" becomes "<=", 2115 ** ">" becomes "<", and so on. So, with DESC sort order, if the argument op 2116 ** is OP_Ge, the generated code is equivalent to: 2117 ** 2118 ** if( csr1.peerVal - regVal <= csr2.peerVal ) goto lbl; 2119 ** 2120 ** A special type of arithmetic is used such that if csr1.peerVal is not 2121 ** a numeric type (real or integer), then the result of the addition 2122 ** or subtraction is a a copy of csr1.peerVal. 2123 */ 2124 static void windowCodeRangeTest( 2125 WindowCodeArg *p, 2126 int op, /* OP_Ge, OP_Gt, or OP_Le */ 2127 int csr1, /* Cursor number for cursor 1 */ 2128 int regVal, /* Register containing non-negative number */ 2129 int csr2, /* Cursor number for cursor 2 */ 2130 int lbl /* Jump destination if condition is true */ 2131 ){ 2132 Parse *pParse = p->pParse; 2133 Vdbe *v = sqlite3GetVdbe(pParse); 2134 ExprList *pOrderBy = p->pMWin->pOrderBy; /* ORDER BY clause for window */ 2135 int reg1 = sqlite3GetTempReg(pParse); /* Reg. for csr1.peerVal+regVal */ 2136 int reg2 = sqlite3GetTempReg(pParse); /* Reg. for csr2.peerVal */ 2137 int regString = ++pParse->nMem; /* Reg. for constant value '' */ 2138 int arith = OP_Add; /* OP_Add or OP_Subtract */ 2139 int addrGe; /* Jump destination */ 2140 int addrDone = sqlite3VdbeMakeLabel(pParse); /* Address past OP_Ge */ 2141 CollSeq *pColl; 2142 2143 /* Read the peer-value from each cursor into a register */ 2144 windowReadPeerValues(p, csr1, reg1); 2145 windowReadPeerValues(p, csr2, reg2); 2146 2147 assert( op==OP_Ge || op==OP_Gt || op==OP_Le ); 2148 assert( pOrderBy && pOrderBy->nExpr==1 ); 2149 if( pOrderBy->a[0].fg.sortFlags & KEYINFO_ORDER_DESC ){ 2150 switch( op ){ 2151 case OP_Ge: op = OP_Le; break; 2152 case OP_Gt: op = OP_Lt; break; 2153 default: assert( op==OP_Le ); op = OP_Ge; break; 2154 } 2155 arith = OP_Subtract; 2156 } 2157 2158 VdbeModuleComment((v, "CodeRangeTest: if( R%d %s R%d %s R%d ) goto lbl", 2159 reg1, (arith==OP_Add ? "+" : "-"), regVal, 2160 ((op==OP_Ge) ? ">=" : (op==OP_Le) ? "<=" : (op==OP_Gt) ? ">" : "<"), reg2 2161 )); 2162 2163 /* If the BIGNULL flag is set for the ORDER BY, then it is required to 2164 ** consider NULL values to be larger than all other values, instead of 2165 ** the usual smaller. The VDBE opcodes OP_Ge and so on do not handle this 2166 ** (and adding that capability causes a performance regression), so 2167 ** instead if the BIGNULL flag is set then cases where either reg1 or 2168 ** reg2 are NULL are handled separately in the following block. The code 2169 ** generated is equivalent to: 2170 ** 2171 ** if( reg1 IS NULL ){ 2172 ** if( op==OP_Ge ) goto lbl; 2173 ** if( op==OP_Gt && reg2 IS NOT NULL ) goto lbl; 2174 ** if( op==OP_Le && reg2 IS NULL ) goto lbl; 2175 ** }else if( reg2 IS NULL ){ 2176 ** if( op==OP_Le ) goto lbl; 2177 ** } 2178 ** 2179 ** Additionally, if either reg1 or reg2 are NULL but the jump to lbl is 2180 ** not taken, control jumps over the comparison operator coded below this 2181 ** block. */ 2182 if( pOrderBy->a[0].fg.sortFlags & KEYINFO_ORDER_BIGNULL ){ 2183 /* This block runs if reg1 contains a NULL. */ 2184 int addr = sqlite3VdbeAddOp1(v, OP_NotNull, reg1); VdbeCoverage(v); 2185 switch( op ){ 2186 case OP_Ge: 2187 sqlite3VdbeAddOp2(v, OP_Goto, 0, lbl); 2188 break; 2189 case OP_Gt: 2190 sqlite3VdbeAddOp2(v, OP_NotNull, reg2, lbl); 2191 VdbeCoverage(v); 2192 break; 2193 case OP_Le: 2194 sqlite3VdbeAddOp2(v, OP_IsNull, reg2, lbl); 2195 VdbeCoverage(v); 2196 break; 2197 default: assert( op==OP_Lt ); /* no-op */ break; 2198 } 2199 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrDone); 2200 2201 /* This block runs if reg1 is not NULL, but reg2 is. */ 2202 sqlite3VdbeJumpHere(v, addr); 2203 sqlite3VdbeAddOp2(v, OP_IsNull, reg2, 2204 (op==OP_Gt || op==OP_Ge) ? addrDone : lbl); 2205 VdbeCoverage(v); 2206 } 2207 2208 /* Register reg1 currently contains csr1.peerVal (the peer-value from csr1). 2209 ** This block adds (or subtracts for DESC) the numeric value in regVal 2210 ** from it. Or, if reg1 is not numeric (it is a NULL, a text value or a blob), 2211 ** then leave reg1 as it is. In pseudo-code, this is implemented as: 2212 ** 2213 ** if( reg1>='' ) goto addrGe; 2214 ** reg1 = reg1 +/- regVal 2215 ** addrGe: 2216 ** 2217 ** Since all strings and blobs are greater-than-or-equal-to an empty string, 2218 ** the add/subtract is skipped for these, as required. If reg1 is a NULL, 2219 ** then the arithmetic is performed, but since adding or subtracting from 2220 ** NULL is always NULL anyway, this case is handled as required too. */ 2221 sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC); 2222 addrGe = sqlite3VdbeAddOp3(v, OP_Ge, regString, 0, reg1); 2223 VdbeCoverage(v); 2224 if( (op==OP_Ge && arith==OP_Add) || (op==OP_Le && arith==OP_Subtract) ){ 2225 sqlite3VdbeAddOp3(v, op, reg2, lbl, reg1); VdbeCoverage(v); 2226 } 2227 sqlite3VdbeAddOp3(v, arith, regVal, reg1, reg1); 2228 sqlite3VdbeJumpHere(v, addrGe); 2229 2230 /* Compare registers reg2 and reg1, taking the jump if required. Note that 2231 ** control skips over this test if the BIGNULL flag is set and either 2232 ** reg1 or reg2 contain a NULL value. */ 2233 sqlite3VdbeAddOp3(v, op, reg2, lbl, reg1); VdbeCoverage(v); 2234 pColl = sqlite3ExprNNCollSeq(pParse, pOrderBy->a[0].pExpr); 2235 sqlite3VdbeAppendP4(v, (void*)pColl, P4_COLLSEQ); 2236 sqlite3VdbeChangeP5(v, SQLITE_NULLEQ); 2237 sqlite3VdbeResolveLabel(v, addrDone); 2238 2239 assert( op==OP_Ge || op==OP_Gt || op==OP_Lt || op==OP_Le ); 2240 testcase(op==OP_Ge); VdbeCoverageIf(v, op==OP_Ge); 2241 testcase(op==OP_Lt); VdbeCoverageIf(v, op==OP_Lt); 2242 testcase(op==OP_Le); VdbeCoverageIf(v, op==OP_Le); 2243 testcase(op==OP_Gt); VdbeCoverageIf(v, op==OP_Gt); 2244 sqlite3ReleaseTempReg(pParse, reg1); 2245 sqlite3ReleaseTempReg(pParse, reg2); 2246 2247 VdbeModuleComment((v, "CodeRangeTest: end")); 2248 } 2249 2250 /* 2251 ** Helper function for sqlite3WindowCodeStep(). Each call to this function 2252 ** generates VM code for a single RETURN_ROW, AGGSTEP or AGGINVERSE 2253 ** operation. Refer to the header comment for sqlite3WindowCodeStep() for 2254 ** details. 2255 */ 2256 static int windowCodeOp( 2257 WindowCodeArg *p, /* Context object */ 2258 int op, /* WINDOW_RETURN_ROW, AGGSTEP or AGGINVERSE */ 2259 int regCountdown, /* Register for OP_IfPos countdown */ 2260 int jumpOnEof /* Jump here if stepped cursor reaches EOF */ 2261 ){ 2262 int csr, reg; 2263 Parse *pParse = p->pParse; 2264 Window *pMWin = p->pMWin; 2265 int ret = 0; 2266 Vdbe *v = p->pVdbe; 2267 int addrContinue = 0; 2268 int bPeer = (pMWin->eFrmType!=TK_ROWS); 2269 2270 int lblDone = sqlite3VdbeMakeLabel(pParse); 2271 int addrNextRange = 0; 2272 2273 /* Special case - WINDOW_AGGINVERSE is always a no-op if the frame 2274 ** starts with UNBOUNDED PRECEDING. */ 2275 if( op==WINDOW_AGGINVERSE && pMWin->eStart==TK_UNBOUNDED ){ 2276 assert( regCountdown==0 && jumpOnEof==0 ); 2277 return 0; 2278 } 2279 2280 if( regCountdown>0 ){ 2281 if( pMWin->eFrmType==TK_RANGE ){ 2282 addrNextRange = sqlite3VdbeCurrentAddr(v); 2283 assert( op==WINDOW_AGGINVERSE || op==WINDOW_AGGSTEP ); 2284 if( op==WINDOW_AGGINVERSE ){ 2285 if( pMWin->eStart==TK_FOLLOWING ){ 2286 windowCodeRangeTest( 2287 p, OP_Le, p->current.csr, regCountdown, p->start.csr, lblDone 2288 ); 2289 }else{ 2290 windowCodeRangeTest( 2291 p, OP_Ge, p->start.csr, regCountdown, p->current.csr, lblDone 2292 ); 2293 } 2294 }else{ 2295 windowCodeRangeTest( 2296 p, OP_Gt, p->end.csr, regCountdown, p->current.csr, lblDone 2297 ); 2298 } 2299 }else{ 2300 sqlite3VdbeAddOp3(v, OP_IfPos, regCountdown, lblDone, 1); 2301 VdbeCoverage(v); 2302 } 2303 } 2304 2305 if( op==WINDOW_RETURN_ROW && pMWin->regStartRowid==0 ){ 2306 windowAggFinal(p, 0); 2307 } 2308 addrContinue = sqlite3VdbeCurrentAddr(v); 2309 2310 /* If this is a (RANGE BETWEEN a FOLLOWING AND b FOLLOWING) or 2311 ** (RANGE BETWEEN b PRECEDING AND a PRECEDING) frame, ensure the 2312 ** start cursor does not advance past the end cursor within the 2313 ** temporary table. It otherwise might, if (a>b). Also ensure that, 2314 ** if the input cursor is still finding new rows, that the end 2315 ** cursor does not go past it to EOF. */ 2316 if( pMWin->eStart==pMWin->eEnd && regCountdown 2317 && pMWin->eFrmType==TK_RANGE 2318 ){ 2319 int regRowid1 = sqlite3GetTempReg(pParse); 2320 int regRowid2 = sqlite3GetTempReg(pParse); 2321 if( op==WINDOW_AGGINVERSE ){ 2322 sqlite3VdbeAddOp2(v, OP_Rowid, p->start.csr, regRowid1); 2323 sqlite3VdbeAddOp2(v, OP_Rowid, p->end.csr, regRowid2); 2324 sqlite3VdbeAddOp3(v, OP_Ge, regRowid2, lblDone, regRowid1); 2325 VdbeCoverage(v); 2326 }else if( p->regRowid ){ 2327 sqlite3VdbeAddOp2(v, OP_Rowid, p->end.csr, regRowid1); 2328 sqlite3VdbeAddOp3(v, OP_Ge, p->regRowid, lblDone, regRowid1); 2329 VdbeCoverageNeverNull(v); 2330 } 2331 sqlite3ReleaseTempReg(pParse, regRowid1); 2332 sqlite3ReleaseTempReg(pParse, regRowid2); 2333 assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_FOLLOWING ); 2334 } 2335 2336 switch( op ){ 2337 case WINDOW_RETURN_ROW: 2338 csr = p->current.csr; 2339 reg = p->current.reg; 2340 windowReturnOneRow(p); 2341 break; 2342 2343 case WINDOW_AGGINVERSE: 2344 csr = p->start.csr; 2345 reg = p->start.reg; 2346 if( pMWin->regStartRowid ){ 2347 assert( pMWin->regEndRowid ); 2348 sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regStartRowid, 1); 2349 }else{ 2350 windowAggStep(p, pMWin, csr, 1, p->regArg); 2351 } 2352 break; 2353 2354 default: 2355 assert( op==WINDOW_AGGSTEP ); 2356 csr = p->end.csr; 2357 reg = p->end.reg; 2358 if( pMWin->regStartRowid ){ 2359 assert( pMWin->regEndRowid ); 2360 sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regEndRowid, 1); 2361 }else{ 2362 windowAggStep(p, pMWin, csr, 0, p->regArg); 2363 } 2364 break; 2365 } 2366 2367 if( op==p->eDelete ){ 2368 sqlite3VdbeAddOp1(v, OP_Delete, csr); 2369 sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION); 2370 } 2371 2372 if( jumpOnEof ){ 2373 sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+2); 2374 VdbeCoverage(v); 2375 ret = sqlite3VdbeAddOp0(v, OP_Goto); 2376 }else{ 2377 sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+1+bPeer); 2378 VdbeCoverage(v); 2379 if( bPeer ){ 2380 sqlite3VdbeAddOp2(v, OP_Goto, 0, lblDone); 2381 } 2382 } 2383 2384 if( bPeer ){ 2385 int nReg = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0); 2386 int regTmp = (nReg ? sqlite3GetTempRange(pParse, nReg) : 0); 2387 windowReadPeerValues(p, csr, regTmp); 2388 windowIfNewPeer(pParse, pMWin->pOrderBy, regTmp, reg, addrContinue); 2389 sqlite3ReleaseTempRange(pParse, regTmp, nReg); 2390 } 2391 2392 if( addrNextRange ){ 2393 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNextRange); 2394 } 2395 sqlite3VdbeResolveLabel(v, lblDone); 2396 return ret; 2397 } 2398 2399 2400 /* 2401 ** Allocate and return a duplicate of the Window object indicated by the 2402 ** third argument. Set the Window.pOwner field of the new object to 2403 ** pOwner. 2404 */ 2405 Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p){ 2406 Window *pNew = 0; 2407 if( ALWAYS(p) ){ 2408 pNew = sqlite3DbMallocZero(db, sizeof(Window)); 2409 if( pNew ){ 2410 pNew->zName = sqlite3DbStrDup(db, p->zName); 2411 pNew->zBase = sqlite3DbStrDup(db, p->zBase); 2412 pNew->pFilter = sqlite3ExprDup(db, p->pFilter, 0); 2413 pNew->pWFunc = p->pWFunc; 2414 pNew->pPartition = sqlite3ExprListDup(db, p->pPartition, 0); 2415 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, 0); 2416 pNew->eFrmType = p->eFrmType; 2417 pNew->eEnd = p->eEnd; 2418 pNew->eStart = p->eStart; 2419 pNew->eExclude = p->eExclude; 2420 pNew->regResult = p->regResult; 2421 pNew->regAccum = p->regAccum; 2422 pNew->iArgCol = p->iArgCol; 2423 pNew->iEphCsr = p->iEphCsr; 2424 pNew->bExprArgs = p->bExprArgs; 2425 pNew->pStart = sqlite3ExprDup(db, p->pStart, 0); 2426 pNew->pEnd = sqlite3ExprDup(db, p->pEnd, 0); 2427 pNew->pOwner = pOwner; 2428 pNew->bImplicitFrame = p->bImplicitFrame; 2429 } 2430 } 2431 return pNew; 2432 } 2433 2434 /* 2435 ** Return a copy of the linked list of Window objects passed as the 2436 ** second argument. 2437 */ 2438 Window *sqlite3WindowListDup(sqlite3 *db, Window *p){ 2439 Window *pWin; 2440 Window *pRet = 0; 2441 Window **pp = &pRet; 2442 2443 for(pWin=p; pWin; pWin=pWin->pNextWin){ 2444 *pp = sqlite3WindowDup(db, 0, pWin); 2445 if( *pp==0 ) break; 2446 pp = &((*pp)->pNextWin); 2447 } 2448 2449 return pRet; 2450 } 2451 2452 /* 2453 ** Return true if it can be determined at compile time that expression 2454 ** pExpr evaluates to a value that, when cast to an integer, is greater 2455 ** than zero. False otherwise. 2456 ** 2457 ** If an OOM error occurs, this function sets the Parse.db.mallocFailed 2458 ** flag and returns zero. 2459 */ 2460 static int windowExprGtZero(Parse *pParse, Expr *pExpr){ 2461 int ret = 0; 2462 sqlite3 *db = pParse->db; 2463 sqlite3_value *pVal = 0; 2464 sqlite3ValueFromExpr(db, pExpr, db->enc, SQLITE_AFF_NUMERIC, &pVal); 2465 if( pVal && sqlite3_value_int(pVal)>0 ){ 2466 ret = 1; 2467 } 2468 sqlite3ValueFree(pVal); 2469 return ret; 2470 } 2471 2472 /* 2473 ** sqlite3WhereBegin() has already been called for the SELECT statement 2474 ** passed as the second argument when this function is invoked. It generates 2475 ** code to populate the Window.regResult register for each window function 2476 ** and invoke the sub-routine at instruction addrGosub once for each row. 2477 ** sqlite3WhereEnd() is always called before returning. 2478 ** 2479 ** This function handles several different types of window frames, which 2480 ** require slightly different processing. The following pseudo code is 2481 ** used to implement window frames of the form: 2482 ** 2483 ** ROWS BETWEEN PRECEDING AND FOLLOWING 2484 ** 2485 ** Other window frame types use variants of the following: 2486 ** 2487 ** ... loop started by sqlite3WhereBegin() ... 2488 ** if( new partition ){ 2489 ** Gosub flush 2490 ** } 2491 ** Insert new row into eph table. 2492 ** 2493 ** if( first row of partition ){ 2494 ** // Rewind three cursors, all open on the eph table. 2495 ** Rewind(csrEnd); 2496 ** Rewind(csrStart); 2497 ** Rewind(csrCurrent); 2498 ** 2499 ** regEnd = // FOLLOWING expression 2500 ** regStart = // PRECEDING expression 2501 ** }else{ 2502 ** // First time this branch is taken, the eph table contains two 2503 ** // rows. The first row in the partition, which all three cursors 2504 ** // currently point to, and the following row. 2505 ** AGGSTEP 2506 ** if( (regEnd--)<=0 ){ 2507 ** RETURN_ROW 2508 ** if( (regStart--)<=0 ){ 2509 ** AGGINVERSE 2510 ** } 2511 ** } 2512 ** } 2513 ** } 2514 ** flush: 2515 ** AGGSTEP 2516 ** while( 1 ){ 2517 ** RETURN ROW 2518 ** if( csrCurrent is EOF ) break; 2519 ** if( (regStart--)<=0 ){ 2520 ** AggInverse(csrStart) 2521 ** Next(csrStart) 2522 ** } 2523 ** } 2524 ** 2525 ** The pseudo-code above uses the following shorthand: 2526 ** 2527 ** AGGSTEP: invoke the aggregate xStep() function for each window function 2528 ** with arguments read from the current row of cursor csrEnd, then 2529 ** step cursor csrEnd forward one row (i.e. sqlite3BtreeNext()). 2530 ** 2531 ** RETURN_ROW: return a row to the caller based on the contents of the 2532 ** current row of csrCurrent and the current state of all 2533 ** aggregates. Then step cursor csrCurrent forward one row. 2534 ** 2535 ** AGGINVERSE: invoke the aggregate xInverse() function for each window 2536 ** functions with arguments read from the current row of cursor 2537 ** csrStart. Then step csrStart forward one row. 2538 ** 2539 ** There are two other ROWS window frames that are handled significantly 2540 ** differently from the above - "BETWEEN PRECEDING AND PRECEDING" 2541 ** and "BETWEEN FOLLOWING AND FOLLOWING". These are special 2542 ** cases because they change the order in which the three cursors (csrStart, 2543 ** csrCurrent and csrEnd) iterate through the ephemeral table. Cases that 2544 ** use UNBOUNDED or CURRENT ROW are much simpler variations on one of these 2545 ** three. 2546 ** 2547 ** ROWS BETWEEN PRECEDING AND PRECEDING 2548 ** 2549 ** ... loop started by sqlite3WhereBegin() ... 2550 ** if( new partition ){ 2551 ** Gosub flush 2552 ** } 2553 ** Insert new row into eph table. 2554 ** if( first row of partition ){ 2555 ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent) 2556 ** regEnd = 2557 ** regStart = 2558 ** }else{ 2559 ** if( (regEnd--)<=0 ){ 2560 ** AGGSTEP 2561 ** } 2562 ** RETURN_ROW 2563 ** if( (regStart--)<=0 ){ 2564 ** AGGINVERSE 2565 ** } 2566 ** } 2567 ** } 2568 ** flush: 2569 ** if( (regEnd--)<=0 ){ 2570 ** AGGSTEP 2571 ** } 2572 ** RETURN_ROW 2573 ** 2574 ** 2575 ** ROWS BETWEEN FOLLOWING AND FOLLOWING 2576 ** 2577 ** ... loop started by sqlite3WhereBegin() ... 2578 ** if( new partition ){ 2579 ** Gosub flush 2580 ** } 2581 ** Insert new row into eph table. 2582 ** if( first row of partition ){ 2583 ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent) 2584 ** regEnd = 2585 ** regStart = regEnd - 2586 ** }else{ 2587 ** AGGSTEP 2588 ** if( (regEnd--)<=0 ){ 2589 ** RETURN_ROW 2590 ** } 2591 ** if( (regStart--)<=0 ){ 2592 ** AGGINVERSE 2593 ** } 2594 ** } 2595 ** } 2596 ** flush: 2597 ** AGGSTEP 2598 ** while( 1 ){ 2599 ** if( (regEnd--)<=0 ){ 2600 ** RETURN_ROW 2601 ** if( eof ) break; 2602 ** } 2603 ** if( (regStart--)<=0 ){ 2604 ** AGGINVERSE 2605 ** if( eof ) break 2606 ** } 2607 ** } 2608 ** while( !eof csrCurrent ){ 2609 ** RETURN_ROW 2610 ** } 2611 ** 2612 ** For the most part, the patterns above are adapted to support UNBOUNDED by 2613 ** assuming that it is equivalent to "infinity PRECEDING/FOLLOWING" and 2614 ** CURRENT ROW by assuming that it is equivalent to "0 PRECEDING/FOLLOWING". 2615 ** This is optimized of course - branches that will never be taken and 2616 ** conditions that are always true are omitted from the VM code. The only 2617 ** exceptional case is: 2618 ** 2619 ** ROWS BETWEEN FOLLOWING AND UNBOUNDED FOLLOWING 2620 ** 2621 ** ... loop started by sqlite3WhereBegin() ... 2622 ** if( new partition ){ 2623 ** Gosub flush 2624 ** } 2625 ** Insert new row into eph table. 2626 ** if( first row of partition ){ 2627 ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent) 2628 ** regStart = 2629 ** }else{ 2630 ** AGGSTEP 2631 ** } 2632 ** } 2633 ** flush: 2634 ** AGGSTEP 2635 ** while( 1 ){ 2636 ** if( (regStart--)<=0 ){ 2637 ** AGGINVERSE 2638 ** if( eof ) break 2639 ** } 2640 ** RETURN_ROW 2641 ** } 2642 ** while( !eof csrCurrent ){ 2643 ** RETURN_ROW 2644 ** } 2645 ** 2646 ** Also requiring special handling are the cases: 2647 ** 2648 ** ROWS BETWEEN PRECEDING AND PRECEDING 2649 ** ROWS BETWEEN FOLLOWING AND FOLLOWING 2650 ** 2651 ** when (expr1 < expr2). This is detected at runtime, not by this function. 2652 ** To handle this case, the pseudo-code programs depicted above are modified 2653 ** slightly to be: 2654 ** 2655 ** ... loop started by sqlite3WhereBegin() ... 2656 ** if( new partition ){ 2657 ** Gosub flush 2658 ** } 2659 ** Insert new row into eph table. 2660 ** if( first row of partition ){ 2661 ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent) 2662 ** regEnd = 2663 ** regStart = 2664 ** if( regEnd < regStart ){ 2665 ** RETURN_ROW 2666 ** delete eph table contents 2667 ** continue 2668 ** } 2669 ** ... 2670 ** 2671 ** The new "continue" statement in the above jumps to the next iteration 2672 ** of the outer loop - the one started by sqlite3WhereBegin(). 2673 ** 2674 ** The various GROUPS cases are implemented using the same patterns as 2675 ** ROWS. The VM code is modified slightly so that: 2676 ** 2677 ** 1. The else branch in the main loop is only taken if the row just 2678 ** added to the ephemeral table is the start of a new group. In 2679 ** other words, it becomes: 2680 ** 2681 ** ... loop started by sqlite3WhereBegin() ... 2682 ** if( new partition ){ 2683 ** Gosub flush 2684 ** } 2685 ** Insert new row into eph table. 2686 ** if( first row of partition ){ 2687 ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent) 2688 ** regEnd = 2689 ** regStart = 2690 ** }else if( new group ){ 2691 ** ... 2692 ** } 2693 ** } 2694 ** 2695 ** 2. Instead of processing a single row, each RETURN_ROW, AGGSTEP or 2696 ** AGGINVERSE step processes the current row of the relevant cursor and 2697 ** all subsequent rows belonging to the same group. 2698 ** 2699 ** RANGE window frames are a little different again. As for GROUPS, the 2700 ** main loop runs once per group only. And RETURN_ROW, AGGSTEP and AGGINVERSE 2701 ** deal in groups instead of rows. As for ROWS and GROUPS, there are three 2702 ** basic cases: 2703 ** 2704 ** RANGE BETWEEN PRECEDING AND FOLLOWING 2705 ** 2706 ** ... loop started by sqlite3WhereBegin() ... 2707 ** if( new partition ){ 2708 ** Gosub flush 2709 ** } 2710 ** Insert new row into eph table. 2711 ** if( first row of partition ){ 2712 ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent) 2713 ** regEnd = 2714 ** regStart = 2715 ** }else{ 2716 ** AGGSTEP 2717 ** while( (csrCurrent.key + regEnd) < csrEnd.key ){ 2718 ** RETURN_ROW 2719 ** while( csrStart.key + regStart) < csrCurrent.key ){ 2720 ** AGGINVERSE 2721 ** } 2722 ** } 2723 ** } 2724 ** } 2725 ** flush: 2726 ** AGGSTEP 2727 ** while( 1 ){ 2728 ** RETURN ROW 2729 ** if( csrCurrent is EOF ) break; 2730 ** while( csrStart.key + regStart) < csrCurrent.key ){ 2731 ** AGGINVERSE 2732 ** } 2733 ** } 2734 ** } 2735 ** 2736 ** In the above notation, "csr.key" means the current value of the ORDER BY 2737 ** expression (there is only ever 1 for a RANGE that uses an FOLLOWING 2738 ** or PRECEDING AND PRECEDING 2741 ** 2742 ** ... loop started by sqlite3WhereBegin() ... 2743 ** if( new partition ){ 2744 ** Gosub flush 2745 ** } 2746 ** Insert new row into eph table. 2747 ** if( first row of partition ){ 2748 ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent) 2749 ** regEnd = 2750 ** regStart = 2751 ** }else{ 2752 ** while( (csrEnd.key + regEnd) <= csrCurrent.key ){ 2753 ** AGGSTEP 2754 ** } 2755 ** while( (csrStart.key + regStart) < csrCurrent.key ){ 2756 ** AGGINVERSE 2757 ** } 2758 ** RETURN_ROW 2759 ** } 2760 ** } 2761 ** flush: 2762 ** while( (csrEnd.key + regEnd) <= csrCurrent.key ){ 2763 ** AGGSTEP 2764 ** } 2765 ** while( (csrStart.key + regStart) < csrCurrent.key ){ 2766 ** AGGINVERSE 2767 ** } 2768 ** RETURN_ROW 2769 ** 2770 ** RANGE BETWEEN FOLLOWING AND FOLLOWING 2771 ** 2772 ** ... loop started by sqlite3WhereBegin() ... 2773 ** if( new partition ){ 2774 ** Gosub flush 2775 ** } 2776 ** Insert new row into eph table. 2777 ** if( first row of partition ){ 2778 ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent) 2779 ** regEnd = 2780 ** regStart = 2781 ** }else{ 2782 ** AGGSTEP 2783 ** while( (csrCurrent.key + regEnd) < csrEnd.key ){ 2784 ** while( (csrCurrent.key + regStart) > csrStart.key ){ 2785 ** AGGINVERSE 2786 ** } 2787 ** RETURN_ROW 2788 ** } 2789 ** } 2790 ** } 2791 ** flush: 2792 ** AGGSTEP 2793 ** while( 1 ){ 2794 ** while( (csrCurrent.key + regStart) > csrStart.key ){ 2795 ** AGGINVERSE 2796 ** if( eof ) break "while( 1 )" loop. 2797 ** } 2798 ** RETURN_ROW 2799 ** } 2800 ** while( !eof csrCurrent ){ 2801 ** RETURN_ROW 2802 ** } 2803 ** 2804 ** The text above leaves out many details. Refer to the code and comments 2805 ** below for a more complete picture. 2806 */ 2807 void sqlite3WindowCodeStep( 2808 Parse *pParse, /* Parse context */ 2809 Select *p, /* Rewritten SELECT statement */ 2810 WhereInfo *pWInfo, /* Context returned by sqlite3WhereBegin() */ 2811 int regGosub, /* Register for OP_Gosub */ 2812 int addrGosub /* OP_Gosub here to return each row */ 2813 ){ 2814 Window *pMWin = p->pWin; 2815 ExprList *pOrderBy = pMWin->pOrderBy; 2816 Vdbe *v = sqlite3GetVdbe(pParse); 2817 int csrWrite; /* Cursor used to write to eph. table */ 2818 int csrInput = p->pSrc->a[0].iCursor; /* Cursor of sub-select */ 2819 int nInput = p->pSrc->a[0].pSTab->nCol; /* Number of cols returned by sub */ 2820 int iInput; /* To iterate through sub cols */ 2821 int addrNe; /* Address of OP_Ne */ 2822 int addrGosubFlush = 0; /* Address of OP_Gosub to flush: */ 2823 int addrInteger = 0; /* Address of OP_Integer */ 2824 int addrEmpty; /* Address of OP_Rewind in flush: */ 2825 int regNew; /* Array of registers holding new input row */ 2826 int regRecord; /* regNew array in record form */ 2827 int regNewPeer = 0; /* Peer values for new row (part of regNew) */ 2828 int regPeer = 0; /* Peer values for current row */ 2829 int regFlushPart = 0; /* Register for "Gosub flush_partition" */ 2830 WindowCodeArg s; /* Context object for sub-routines */ 2831 int lblWhereEnd; /* Label just before sqlite3WhereEnd() code */ 2832 int regStart = 0; /* Value of PRECEDING */ 2833 int regEnd = 0; /* Value of FOLLOWING */ 2834 2835 assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_CURRENT 2836 || pMWin->eStart==TK_FOLLOWING || pMWin->eStart==TK_UNBOUNDED 2837 ); 2838 assert( pMWin->eEnd==TK_FOLLOWING || pMWin->eEnd==TK_CURRENT 2839 || pMWin->eEnd==TK_UNBOUNDED || pMWin->eEnd==TK_PRECEDING 2840 ); 2841 assert( pMWin->eExclude==0 || pMWin->eExclude==TK_CURRENT 2842 || pMWin->eExclude==TK_GROUP || pMWin->eExclude==TK_TIES 2843 || pMWin->eExclude==TK_NO 2844 ); 2845 2846 lblWhereEnd = sqlite3VdbeMakeLabel(pParse); 2847 2848 /* Fill in the context object */ 2849 memset(&s, 0, sizeof(WindowCodeArg)); 2850 s.pParse = pParse; 2851 s.pMWin = pMWin; 2852 s.pVdbe = v; 2853 s.regGosub = regGosub; 2854 s.addrGosub = addrGosub; 2855 s.current.csr = pMWin->iEphCsr; 2856 csrWrite = s.current.csr+1; 2857 s.start.csr = s.current.csr+2; 2858 s.end.csr = s.current.csr+3; 2859 2860 /* Figure out when rows may be deleted from the ephemeral table. There 2861 ** are four options - they may never be deleted (eDelete==0), they may 2862 ** be deleted as soon as they are no longer part of the window frame 2863 ** (eDelete==WINDOW_AGGINVERSE), they may be deleted as after the row 2864 ** has been returned to the caller (WINDOW_RETURN_ROW), or they may 2865 ** be deleted after they enter the frame (WINDOW_AGGSTEP). */ 2866 switch( pMWin->eStart ){ 2867 case TK_FOLLOWING: 2868 if( pMWin->eFrmType!=TK_RANGE 2869 && windowExprGtZero(pParse, pMWin->pStart) 2870 ){ 2871 s.eDelete = WINDOW_RETURN_ROW; 2872 } 2873 break; 2874 case TK_UNBOUNDED: 2875 if( windowCacheFrame(pMWin)==0 ){ 2876 if( pMWin->eEnd==TK_PRECEDING ){ 2877 if( pMWin->eFrmType!=TK_RANGE 2878 && windowExprGtZero(pParse, pMWin->pEnd) 2879 ){ 2880 s.eDelete = WINDOW_AGGSTEP; 2881 } 2882 }else{ 2883 s.eDelete = WINDOW_RETURN_ROW; 2884 } 2885 } 2886 break; 2887 default: 2888 s.eDelete = WINDOW_AGGINVERSE; 2889 break; 2890 } 2891 2892 /* Allocate registers for the array of values from the sub-query, the 2893 ** same values in record form, and the rowid used to insert said record 2894 ** into the ephemeral table. */ 2895 regNew = pParse->nMem+1; 2896 pParse->nMem += nInput; 2897 regRecord = ++pParse->nMem; 2898 s.regRowid = ++pParse->nMem; 2899 2900 /* If the window frame contains an " PRECEDING" or " FOLLOWING" 2901 ** clause, allocate registers to store the results of evaluating each 2902 ** . */ 2903 if( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_FOLLOWING ){ 2904 regStart = ++pParse->nMem; 2905 } 2906 if( pMWin->eEnd==TK_PRECEDING || pMWin->eEnd==TK_FOLLOWING ){ 2907 regEnd = ++pParse->nMem; 2908 } 2909 2910 /* If this is not a "ROWS BETWEEN ..." frame, then allocate arrays of 2911 ** registers to store copies of the ORDER BY expressions (peer values) 2912 ** for the main loop, and for each cursor (start, current and end). */ 2913 if( pMWin->eFrmType!=TK_ROWS ){ 2914 int nPeer = (pOrderBy ? pOrderBy->nExpr : 0); 2915 regNewPeer = regNew + pMWin->nBufferCol; 2916 if( pMWin->pPartition ) regNewPeer += pMWin->pPartition->nExpr; 2917 regPeer = pParse->nMem+1; pParse->nMem += nPeer; 2918 s.start.reg = pParse->nMem+1; pParse->nMem += nPeer; 2919 s.current.reg = pParse->nMem+1; pParse->nMem += nPeer; 2920 s.end.reg = pParse->nMem+1; pParse->nMem += nPeer; 2921 } 2922 2923 /* Load the column values for the row returned by the sub-select 2924 ** into an array of registers starting at regNew. Assemble them into 2925 ** a record in register regRecord. */ 2926 for(iInput=0; iInputpPartition ){ 2937 int addr; 2938 ExprList *pPart = pMWin->pPartition; 2939 int nPart = pPart->nExpr; 2940 int regNewPart = regNew + pMWin->nBufferCol; 2941 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pPart, 0, 0); 2942 2943 regFlushPart = ++pParse->nMem; 2944 addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPart, pMWin->regPart, nPart); 2945 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO); 2946 sqlite3VdbeAddOp3(v, OP_Jump, addr+2, addr+4, addr+2); 2947 VdbeCoverageEqNe(v); 2948 addrGosubFlush = sqlite3VdbeAddOp1(v, OP_Gosub, regFlushPart); 2949 VdbeComment((v, "call flush_partition")); 2950 sqlite3VdbeAddOp3(v, OP_Copy, regNewPart, pMWin->regPart, nPart-1); 2951 } 2952 2953 /* Insert the new row into the ephemeral table */ 2954 sqlite3VdbeAddOp2(v, OP_NewRowid, csrWrite, s.regRowid); 2955 sqlite3VdbeAddOp3(v, OP_Insert, csrWrite, regRecord, s.regRowid); 2956 addrNe = sqlite3VdbeAddOp3(v, OP_Ne, pMWin->regOne, 0, s.regRowid); 2957 VdbeCoverageNeverNull(v); 2958 2959 /* This block is run for the first row of each partition */ 2960 s.regArg = windowInitAccum(pParse, pMWin); 2961 2962 if( regStart ){ 2963 sqlite3ExprCode(pParse, pMWin->pStart, regStart); 2964 windowCheckValue(pParse, regStart, 0 + (pMWin->eFrmType==TK_RANGE?3:0)); 2965 } 2966 if( regEnd ){ 2967 sqlite3ExprCode(pParse, pMWin->pEnd, regEnd); 2968 windowCheckValue(pParse, regEnd, 1 + (pMWin->eFrmType==TK_RANGE?3:0)); 2969 } 2970 2971 if( pMWin->eFrmType!=TK_RANGE && pMWin->eStart==pMWin->eEnd && regStart ){ 2972 int op = ((pMWin->eStart==TK_FOLLOWING) ? OP_Ge : OP_Le); 2973 int addrGe = sqlite3VdbeAddOp3(v, op, regStart, 0, regEnd); 2974 VdbeCoverageNeverNullIf(v, op==OP_Ge); /* NeverNull because bound */ 2975 VdbeCoverageNeverNullIf(v, op==OP_Le); /* values previously checked */ 2976 windowAggFinal(&s, 0); 2977 sqlite3VdbeAddOp1(v, OP_Rewind, s.current.csr); 2978 windowReturnOneRow(&s); 2979 sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr); 2980 sqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd); 2981 sqlite3VdbeJumpHere(v, addrGe); 2982 } 2983 if( pMWin->eStart==TK_FOLLOWING && pMWin->eFrmType!=TK_RANGE && regEnd ){ 2984 assert( pMWin->eEnd==TK_FOLLOWING ); 2985 sqlite3VdbeAddOp3(v, OP_Subtract, regStart, regEnd, regStart); 2986 } 2987 2988 if( pMWin->eStart!=TK_UNBOUNDED ){ 2989 sqlite3VdbeAddOp1(v, OP_Rewind, s.start.csr); 2990 } 2991 sqlite3VdbeAddOp1(v, OP_Rewind, s.current.csr); 2992 sqlite3VdbeAddOp1(v, OP_Rewind, s.end.csr); 2993 if( regPeer && pOrderBy ){ 2994 sqlite3VdbeAddOp3(v, OP_Copy, regNewPeer, regPeer, pOrderBy->nExpr-1); 2995 sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.start.reg, pOrderBy->nExpr-1); 2996 sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.current.reg, pOrderBy->nExpr-1); 2997 sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.end.reg, pOrderBy->nExpr-1); 2998 } 2999 3000 sqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd); 3001 3002 sqlite3VdbeJumpHere(v, addrNe); 3003 3004 /* Beginning of the block executed for the second and subsequent rows. */ 3005 if( regPeer ){ 3006 windowIfNewPeer(pParse, pOrderBy, regNewPeer, regPeer, lblWhereEnd); 3007 } 3008 if( pMWin->eStart==TK_FOLLOWING ){ 3009 windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0); 3010 if( pMWin->eEnd!=TK_UNBOUNDED ){ 3011 if( pMWin->eFrmType==TK_RANGE ){ 3012 int lbl = sqlite3VdbeMakeLabel(pParse); 3013 int addrNext = sqlite3VdbeCurrentAddr(v); 3014 windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl); 3015 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0); 3016 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0); 3017 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNext); 3018 sqlite3VdbeResolveLabel(v, lbl); 3019 }else{ 3020 windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 0); 3021 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0); 3022 } 3023 } 3024 }else 3025 if( pMWin->eEnd==TK_PRECEDING ){ 3026 int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE); 3027 windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0); 3028 if( bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0); 3029 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0); 3030 if( !bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0); 3031 }else{ 3032 int addr = 0; 3033 windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0); 3034 if( pMWin->eEnd!=TK_UNBOUNDED ){ 3035 if( pMWin->eFrmType==TK_RANGE ){ 3036 int lbl = 0; 3037 addr = sqlite3VdbeCurrentAddr(v); 3038 if( regEnd ){ 3039 lbl = sqlite3VdbeMakeLabel(pParse); 3040 windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl); 3041 } 3042 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0); 3043 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0); 3044 if( regEnd ){ 3045 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr); 3046 sqlite3VdbeResolveLabel(v, lbl); 3047 } 3048 }else{ 3049 if( regEnd ){ 3050 addr = sqlite3VdbeAddOp3(v, OP_IfPos, regEnd, 0, 1); 3051 VdbeCoverage(v); 3052 } 3053 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0); 3054 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0); 3055 if( regEnd ) sqlite3VdbeJumpHere(v, addr); 3056 } 3057 } 3058 } 3059 3060 /* End of the main input loop */ 3061 sqlite3VdbeResolveLabel(v, lblWhereEnd); 3062 sqlite3WhereEnd(pWInfo); 3063 3064 /* Fall through */ 3065 if( pMWin->pPartition ){ 3066 addrInteger = sqlite3VdbeAddOp2(v, OP_Integer, 0, regFlushPart); 3067 sqlite3VdbeJumpHere(v, addrGosubFlush); 3068 } 3069 3070 s.regRowid = 0; 3071 addrEmpty = sqlite3VdbeAddOp1(v, OP_Rewind, csrWrite); 3072 VdbeCoverage(v); 3073 if( pMWin->eEnd==TK_PRECEDING ){ 3074 int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE); 3075 windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0); 3076 if( bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0); 3077 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0); 3078 }else if( pMWin->eStart==TK_FOLLOWING ){ 3079 int addrStart; 3080 int addrBreak1; 3081 int addrBreak2; 3082 int addrBreak3; 3083 windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0); 3084 if( pMWin->eFrmType==TK_RANGE ){ 3085 addrStart = sqlite3VdbeCurrentAddr(v); 3086 addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1); 3087 addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1); 3088 }else 3089 if( pMWin->eEnd==TK_UNBOUNDED ){ 3090 addrStart = sqlite3VdbeCurrentAddr(v); 3091 addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regStart, 1); 3092 addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, 0, 1); 3093 }else{ 3094 assert( pMWin->eEnd==TK_FOLLOWING ); 3095 /* assert( regStart>=0 ); 3096 ** regEnd = regEnd - regStart; 3097 ** regStart = 0; */ 3098 sqlite3VdbeAddOp3(v, OP_Subtract, regStart, regEnd, regEnd); 3099 sqlite3VdbeAddOp2(v, OP_Integer, 0, regStart); 3100 3101 addrStart = sqlite3VdbeCurrentAddr(v); 3102 addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 1); 3103 addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1); 3104 } 3105 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart); 3106 sqlite3VdbeJumpHere(v, addrBreak2); 3107 addrStart = sqlite3VdbeCurrentAddr(v); 3108 addrBreak3 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1); 3109 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart); 3110 sqlite3VdbeJumpHere(v, addrBreak1); 3111 sqlite3VdbeJumpHere(v, addrBreak3); 3112 }else{ 3113 int addrBreak; 3114 int addrStart; 3115 windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0); 3116 addrStart = sqlite3VdbeCurrentAddr(v); 3117 addrBreak = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1); 3118 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0); 3119 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart); 3120 sqlite3VdbeJumpHere(v, addrBreak); 3121 } 3122 sqlite3VdbeJumpHere(v, addrEmpty); 3123 3124 sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr); 3125 if( pMWin->pPartition ){ 3126 if( pMWin->regStartRowid ){ 3127 sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid); 3128 sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid); 3129 } 3130 sqlite3VdbeChangeP1(v, addrInteger, sqlite3VdbeCurrentAddr(v)); 3131 sqlite3VdbeAddOp1(v, OP_Return, regFlushPart); 3132 } 3133 } 3134 3135 #endif /* SQLITE_OMIT_WINDOWFUNC */