blob: b1ae0b6bcc2ae77db5e6329689e0e4f62a2ddace [file] [log] [blame]
dan86fb6e12018-05-16 20:58:07 +00001/*
dan26522d12018-06-11 18:16:51 +00002** 2018 May 08
dan86fb6e12018-05-16 20:58:07 +00003**
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
dan67a9b8e2018-06-22 20:51:35 +000015#ifndef SQLITE_OMIT_WINDOWFUNC
16
dandfa552f2018-06-02 21:04:28 +000017/*
dan73925692018-06-12 18:40:17 +000018** 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 funtions) 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.
danc0bb4452018-06-12 20:53:38 +0000134**
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.
dan73925692018-06-12 18:40:17 +0000139*/
140
141/*
dandfa552f2018-06-02 21:04:28 +0000142** 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*/
147static 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}
dan2a11bb22018-06-11 20:50:25 +0000155static void row_numberInvFunc(
dandfa552f2018-06-02 21:04:28 +0000156 sqlite3_context *pCtx,
157 int nArg,
158 sqlite3_value **apArg
159){
160}
161static void row_numberValueFunc(sqlite3_context *pCtx){
162 i64 *p = (i64*)sqlite3_aggregate_context(pCtx, sizeof(*p));
163 sqlite3_result_int64(pCtx, (p ? *p : 0));
164}
165
166/*
dan2a11bb22018-06-11 20:50:25 +0000167** Context object type used by rank(), dense_rank(), percent_rank() and
168** cume_dist().
dandfa552f2018-06-02 21:04:28 +0000169*/
170struct CallCount {
171 i64 nValue;
172 i64 nStep;
173 i64 nTotal;
174};
175
176/*
dan9c277582018-06-20 09:23:49 +0000177** Implementation of built-in window function dense_rank(). Assumes that
178** the window frame has been set to:
179**
180** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
dandfa552f2018-06-02 21:04:28 +0000181*/
182static void dense_rankStepFunc(
183 sqlite3_context *pCtx,
184 int nArg,
185 sqlite3_value **apArg
186){
187 struct CallCount *p;
188 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
189 if( p ) p->nStep = 1;
190}
dan2a11bb22018-06-11 20:50:25 +0000191static void dense_rankInvFunc(
dandfa552f2018-06-02 21:04:28 +0000192 sqlite3_context *pCtx,
193 int nArg,
194 sqlite3_value **apArg
195){
196}
197static void dense_rankValueFunc(sqlite3_context *pCtx){
198 struct CallCount *p;
199 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
200 if( p ){
201 if( p->nStep ){
202 p->nValue++;
203 p->nStep = 0;
204 }
205 sqlite3_result_int64(pCtx, p->nValue);
206 }
207}
208
209/*
dan9c277582018-06-20 09:23:49 +0000210** Implementation of built-in window function rank(). Assumes that
211** the window frame has been set to:
212**
213** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
dandfa552f2018-06-02 21:04:28 +0000214*/
215static void rankStepFunc(
216 sqlite3_context *pCtx,
217 int nArg,
218 sqlite3_value **apArg
219){
220 struct CallCount *p;
221 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
222 if( p ){
223 p->nStep++;
224 if( p->nValue==0 ){
225 p->nValue = p->nStep;
226 }
227 }
228}
dan2a11bb22018-06-11 20:50:25 +0000229static void rankInvFunc(
dandfa552f2018-06-02 21:04:28 +0000230 sqlite3_context *pCtx,
231 int nArg,
232 sqlite3_value **apArg
233){
234}
235static void rankValueFunc(sqlite3_context *pCtx){
236 struct CallCount *p;
237 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
238 if( p ){
239 sqlite3_result_int64(pCtx, p->nValue);
240 p->nValue = 0;
241 }
242}
243
244/*
dan9c277582018-06-20 09:23:49 +0000245** Implementation of built-in window function percent_rank(). Assumes that
246** the window frame has been set to:
247**
248** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
dandfa552f2018-06-02 21:04:28 +0000249*/
250static void percent_rankStepFunc(
251 sqlite3_context *pCtx,
252 int nArg,
253 sqlite3_value **apArg
254){
255 struct CallCount *p;
256 assert( nArg==1 );
257
258 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
dancf0343b2018-07-06 13:25:02 +0000259 if( p ){
dandfa552f2018-06-02 21:04:28 +0000260 if( p->nTotal==0 ){
261 p->nTotal = sqlite3_value_int64(apArg[0]);
262 }
263 p->nStep++;
264 if( p->nValue==0 ){
265 p->nValue = p->nStep;
266 }
267 }
268}
dan2a11bb22018-06-11 20:50:25 +0000269static void percent_rankInvFunc(
dandfa552f2018-06-02 21:04:28 +0000270 sqlite3_context *pCtx,
271 int nArg,
272 sqlite3_value **apArg
273){
274}
275static void percent_rankValueFunc(sqlite3_context *pCtx){
276 struct CallCount *p;
277 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
278 if( p ){
279 if( p->nTotal>1 ){
280 double r = (double)(p->nValue-1) / (double)(p->nTotal-1);
281 sqlite3_result_double(pCtx, r);
282 }else{
danb7306f62018-06-21 19:20:39 +0000283 sqlite3_result_double(pCtx, 0.0);
dandfa552f2018-06-02 21:04:28 +0000284 }
285 p->nValue = 0;
286 }
287}
288
dan9c277582018-06-20 09:23:49 +0000289/*
290** Implementation of built-in window function cume_dist(). Assumes that
291** the window frame has been set to:
292**
293** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
294*/
danf1abe362018-06-04 08:22:09 +0000295static void cume_distStepFunc(
296 sqlite3_context *pCtx,
297 int nArg,
298 sqlite3_value **apArg
299){
300 struct CallCount *p;
301 assert( nArg==1 );
302
303 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
dancf0343b2018-07-06 13:25:02 +0000304 if( p ){
danf1abe362018-06-04 08:22:09 +0000305 if( p->nTotal==0 ){
306 p->nTotal = sqlite3_value_int64(apArg[0]);
307 }
308 p->nStep++;
309 }
310}
dan2a11bb22018-06-11 20:50:25 +0000311static void cume_distInvFunc(
danf1abe362018-06-04 08:22:09 +0000312 sqlite3_context *pCtx,
313 int nArg,
314 sqlite3_value **apArg
315){
316}
317static void cume_distValueFunc(sqlite3_context *pCtx){
318 struct CallCount *p;
319 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
dan660af932018-06-18 16:55:22 +0000320 if( p && p->nTotal ){
danf1abe362018-06-04 08:22:09 +0000321 double r = (double)(p->nStep) / (double)(p->nTotal);
322 sqlite3_result_double(pCtx, r);
323 }
324}
325
dan2a11bb22018-06-11 20:50:25 +0000326/*
327** Context object for ntile() window function.
328*/
dan6bc5c9e2018-06-04 18:55:11 +0000329struct NtileCtx {
330 i64 nTotal; /* Total rows in partition */
331 i64 nParam; /* Parameter passed to ntile(N) */
332 i64 iRow; /* Current row */
333};
334
335/*
336** Implementation of ntile(). This assumes that the window frame has
337** been coerced to:
338**
339** ROWS UNBOUNDED PRECEDING AND CURRENT ROW
dan6bc5c9e2018-06-04 18:55:11 +0000340*/
341static void ntileStepFunc(
342 sqlite3_context *pCtx,
343 int nArg,
344 sqlite3_value **apArg
345){
346 struct NtileCtx *p;
347 assert( nArg==2 );
348 p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
dan17074e32018-06-22 17:57:10 +0000349 if( p ){
dan6bc5c9e2018-06-04 18:55:11 +0000350 if( p->nTotal==0 ){
351 p->nParam = sqlite3_value_int64(apArg[0]);
352 p->nTotal = sqlite3_value_int64(apArg[1]);
353 if( p->nParam<=0 ){
354 sqlite3_result_error(
355 pCtx, "argument of ntile must be a positive integer", -1
356 );
357 }
358 }
359 p->iRow++;
360 }
361}
dan2a11bb22018-06-11 20:50:25 +0000362static void ntileInvFunc(
dan6bc5c9e2018-06-04 18:55:11 +0000363 sqlite3_context *pCtx,
364 int nArg,
365 sqlite3_value **apArg
366){
367}
368static void ntileValueFunc(sqlite3_context *pCtx){
369 struct NtileCtx *p;
370 p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
371 if( p && p->nParam>0 ){
372 int nSize = (p->nTotal / p->nParam);
373 if( nSize==0 ){
374 sqlite3_result_int64(pCtx, p->iRow);
375 }else{
376 i64 nLarge = p->nTotal - p->nParam*nSize;
377 i64 iSmall = nLarge*(nSize+1);
378 i64 iRow = p->iRow-1;
379
380 assert( (nLarge*(nSize+1) + (p->nParam-nLarge)*nSize)==p->nTotal );
381
382 if( iRow<iSmall ){
383 sqlite3_result_int64(pCtx, 1 + iRow/(nSize+1));
384 }else{
385 sqlite3_result_int64(pCtx, 1 + nLarge + (iRow-iSmall)/nSize);
386 }
387 }
388 }
389}
390
dan2a11bb22018-06-11 20:50:25 +0000391/*
392** Context object for last_value() window function.
393*/
dan1c5ed622018-06-05 16:16:17 +0000394struct LastValueCtx {
395 sqlite3_value *pVal;
396 int nVal;
397};
398
399/*
400** Implementation of last_value().
401*/
402static void last_valueStepFunc(
403 sqlite3_context *pCtx,
404 int nArg,
405 sqlite3_value **apArg
406){
407 struct LastValueCtx *p;
dan9c277582018-06-20 09:23:49 +0000408 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
dan1c5ed622018-06-05 16:16:17 +0000409 if( p ){
410 sqlite3_value_free(p->pVal);
411 p->pVal = sqlite3_value_dup(apArg[0]);
dan6fde1792018-06-15 19:01:35 +0000412 if( p->pVal==0 ){
413 sqlite3_result_error_nomem(pCtx);
414 }else{
415 p->nVal++;
416 }
dan1c5ed622018-06-05 16:16:17 +0000417 }
418}
dan2a11bb22018-06-11 20:50:25 +0000419static void last_valueInvFunc(
dan1c5ed622018-06-05 16:16:17 +0000420 sqlite3_context *pCtx,
421 int nArg,
422 sqlite3_value **apArg
423){
424 struct LastValueCtx *p;
dan9c277582018-06-20 09:23:49 +0000425 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
426 if( ALWAYS(p) ){
dan1c5ed622018-06-05 16:16:17 +0000427 p->nVal--;
428 if( p->nVal==0 ){
429 sqlite3_value_free(p->pVal);
430 p->pVal = 0;
431 }
432 }
433}
434static void last_valueValueFunc(sqlite3_context *pCtx){
435 struct LastValueCtx *p;
dan9c277582018-06-20 09:23:49 +0000436 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
dan1c5ed622018-06-05 16:16:17 +0000437 if( p && p->pVal ){
438 sqlite3_result_value(pCtx, p->pVal);
439 }
440}
441static void last_valueFinalizeFunc(sqlite3_context *pCtx){
442 struct LastValueCtx *p;
dan9c277582018-06-20 09:23:49 +0000443 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
dan1c5ed622018-06-05 16:16:17 +0000444 if( p && p->pVal ){
445 sqlite3_result_value(pCtx, p->pVal);
446 sqlite3_value_free(p->pVal);
447 p->pVal = 0;
448 }
449}
450
dan2a11bb22018-06-11 20:50:25 +0000451/*
452** No-op implementations of nth_value(), first_value(), lead() and lag().
453** These are all implemented inline using VDBE instructions.
454*/
455static void nth_valueStepFunc(sqlite3_context *pCtx, int n, sqlite3_value **a){}
456static void nth_valueInvFunc(sqlite3_context *pCtx, int n, sqlite3_value **ap){}
457static void nth_valueValueFunc(sqlite3_context *pCtx){}
458static void first_valueStepFunc(sqlite3_context *p, int n, sqlite3_value **ap){}
459static void first_valueInvFunc(sqlite3_context *p, int n, sqlite3_value **ap){}
460static void first_valueValueFunc(sqlite3_context *pCtx){}
461static void leadStepFunc(sqlite3_context *pCtx, int n, sqlite3_value **ap){}
462static void leadInvFunc(sqlite3_context *pCtx, int n, sqlite3_value **ap){}
463static void leadValueFunc(sqlite3_context *pCtx){}
464static void lagStepFunc(sqlite3_context *pCtx, int n, sqlite3_value **ap){}
465static void lagInvFunc(sqlite3_context *pCtx, int n, sqlite3_value **ap){}
466static void lagValueFunc(sqlite3_context *pCtx){}
danfe4e25a2018-06-07 20:08:59 +0000467
dandfa552f2018-06-02 21:04:28 +0000468#define WINDOWFUNC(name,nArg,extra) { \
469 nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
470 name ## StepFunc, name ## ValueFunc, name ## ValueFunc, \
dan2a11bb22018-06-11 20:50:25 +0000471 name ## InvFunc, #name \
dandfa552f2018-06-02 21:04:28 +0000472}
473
dan1c5ed622018-06-05 16:16:17 +0000474#define WINDOWFUNCF(name,nArg,extra) { \
475 nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
476 name ## StepFunc, name ## FinalizeFunc, name ## ValueFunc, \
dan2a11bb22018-06-11 20:50:25 +0000477 name ## InvFunc, #name \
dan1c5ed622018-06-05 16:16:17 +0000478}
479
dandfa552f2018-06-02 21:04:28 +0000480/*
481** Register those built-in window functions that are not also aggregates.
482*/
483void sqlite3WindowFunctions(void){
484 static FuncDef aWindowFuncs[] = {
485 WINDOWFUNC(row_number, 0, 0),
486 WINDOWFUNC(dense_rank, 0, 0),
487 WINDOWFUNC(rank, 0, 0),
488 WINDOWFUNC(percent_rank, 0, SQLITE_FUNC_WINDOW_SIZE),
danf1abe362018-06-04 08:22:09 +0000489 WINDOWFUNC(cume_dist, 0, SQLITE_FUNC_WINDOW_SIZE),
dan6bc5c9e2018-06-04 18:55:11 +0000490 WINDOWFUNC(ntile, 1, SQLITE_FUNC_WINDOW_SIZE),
dan1c5ed622018-06-05 16:16:17 +0000491 WINDOWFUNCF(last_value, 1, 0),
dandfa552f2018-06-02 21:04:28 +0000492 WINDOWFUNC(nth_value, 2, 0),
dan7095c002018-06-07 17:45:22 +0000493 WINDOWFUNC(first_value, 1, 0),
danfe4e25a2018-06-07 20:08:59 +0000494 WINDOWFUNC(lead, 1, 0), WINDOWFUNC(lead, 2, 0), WINDOWFUNC(lead, 3, 0),
495 WINDOWFUNC(lag, 1, 0), WINDOWFUNC(lag, 2, 0), WINDOWFUNC(lag, 3, 0),
dandfa552f2018-06-02 21:04:28 +0000496 };
497 sqlite3InsertBuiltinFuncs(aWindowFuncs, ArraySize(aWindowFuncs));
498}
499
danc0bb4452018-06-12 20:53:38 +0000500/*
501** This function is called immediately after resolving the function name
502** for a window function within a SELECT statement. Argument pList is a
503** linked list of WINDOW definitions for the current SELECT statement.
504** Argument pFunc is the function definition just resolved and pWin
505** is the Window object representing the associated OVER clause. This
506** function updates the contents of pWin as follows:
507**
508** * If the OVER clause refered to a named window (as in "max(x) OVER win"),
509** search list pList for a matching WINDOW definition, and update pWin
510** accordingly. If no such WINDOW clause can be found, leave an error
511** in pParse.
512**
513** * If the function is a built-in window function that requires the
514** window to be coerced (see "BUILT-IN WINDOW FUNCTIONS" at the top
515** of this file), pWin is updated here.
516*/
dane3bf6322018-06-08 20:58:27 +0000517void sqlite3WindowUpdate(
518 Parse *pParse,
danc0bb4452018-06-12 20:53:38 +0000519 Window *pList, /* List of named windows for this SELECT */
520 Window *pWin, /* Window frame to update */
521 FuncDef *pFunc /* Window function definition */
dane3bf6322018-06-08 20:58:27 +0000522){
danc95f38d2018-06-18 20:34:43 +0000523 if( pWin->zName && pWin->eType==0 ){
dane3bf6322018-06-08 20:58:27 +0000524 Window *p;
525 for(p=pList; p; p=p->pNextWin){
526 if( sqlite3StrICmp(p->zName, pWin->zName)==0 ) break;
527 }
528 if( p==0 ){
529 sqlite3ErrorMsg(pParse, "no such window: %s", pWin->zName);
530 return;
531 }
532 pWin->pPartition = sqlite3ExprListDup(pParse->db, p->pPartition, 0);
533 pWin->pOrderBy = sqlite3ExprListDup(pParse->db, p->pOrderBy, 0);
534 pWin->pStart = sqlite3ExprDup(pParse->db, p->pStart, 0);
535 pWin->pEnd = sqlite3ExprDup(pParse->db, p->pEnd, 0);
536 pWin->eStart = p->eStart;
537 pWin->eEnd = p->eEnd;
danc95f38d2018-06-18 20:34:43 +0000538 pWin->eType = p->eType;
dane3bf6322018-06-08 20:58:27 +0000539 }
dandfa552f2018-06-02 21:04:28 +0000540 if( pFunc->funcFlags & SQLITE_FUNC_WINDOW ){
541 sqlite3 *db = pParse->db;
dan8b985602018-06-09 17:43:45 +0000542 if( pWin->pFilter ){
543 sqlite3ErrorMsg(pParse,
544 "FILTER clause may only be used with aggregate window functions"
545 );
546 }else
dan6bc5c9e2018-06-04 18:55:11 +0000547 if( pFunc->xSFunc==row_numberStepFunc || pFunc->xSFunc==ntileStepFunc ){
dandfa552f2018-06-02 21:04:28 +0000548 sqlite3ExprDelete(db, pWin->pStart);
549 sqlite3ExprDelete(db, pWin->pEnd);
550 pWin->pStart = pWin->pEnd = 0;
551 pWin->eType = TK_ROWS;
552 pWin->eStart = TK_UNBOUNDED;
553 pWin->eEnd = TK_CURRENT;
dan8b985602018-06-09 17:43:45 +0000554 }else
dandfa552f2018-06-02 21:04:28 +0000555
556 if( pFunc->xSFunc==dense_rankStepFunc || pFunc->xSFunc==rankStepFunc
danf1abe362018-06-04 08:22:09 +0000557 || pFunc->xSFunc==percent_rankStepFunc || pFunc->xSFunc==cume_distStepFunc
dandfa552f2018-06-02 21:04:28 +0000558 ){
559 sqlite3ExprDelete(db, pWin->pStart);
560 sqlite3ExprDelete(db, pWin->pEnd);
561 pWin->pStart = pWin->pEnd = 0;
562 pWin->eType = TK_RANGE;
563 pWin->eStart = TK_UNBOUNDED;
564 pWin->eEnd = TK_CURRENT;
565 }
566 }
dan2a11bb22018-06-11 20:50:25 +0000567 pWin->pFunc = pFunc;
dandfa552f2018-06-02 21:04:28 +0000568}
569
danc0bb4452018-06-12 20:53:38 +0000570/*
571** Context object passed through sqlite3WalkExprList() to
572** selectWindowRewriteExprCb() by selectWindowRewriteEList().
573*/
dandfa552f2018-06-02 21:04:28 +0000574typedef struct WindowRewrite WindowRewrite;
575struct WindowRewrite {
576 Window *pWin;
577 ExprList *pSub;
578};
579
danc0bb4452018-06-12 20:53:38 +0000580/*
581** Callback function used by selectWindowRewriteEList(). If necessary,
582** this function appends to the output expression-list and updates
583** expression (*ppExpr) in place.
584*/
dandfa552f2018-06-02 21:04:28 +0000585static int selectWindowRewriteExprCb(Walker *pWalker, Expr *pExpr){
586 struct WindowRewrite *p = pWalker->u.pRewrite;
587 Parse *pParse = pWalker->pParse;
588
589 switch( pExpr->op ){
590
591 case TK_FUNCTION:
592 if( pExpr->pWin==0 ){
593 break;
594 }else{
595 Window *pWin;
596 for(pWin=p->pWin; pWin; pWin=pWin->pNextWin){
597 if( pExpr->pWin==pWin ){
dan2a11bb22018-06-11 20:50:25 +0000598 assert( pWin->pOwner==pExpr );
dandfa552f2018-06-02 21:04:28 +0000599 return WRC_Prune;
600 }
601 }
602 }
603 /* Fall through. */
604
dan73925692018-06-12 18:40:17 +0000605 case TK_AGG_FUNCTION:
dandfa552f2018-06-02 21:04:28 +0000606 case TK_COLUMN: {
607 Expr *pDup = sqlite3ExprDup(pParse->db, pExpr, 0);
608 p->pSub = sqlite3ExprListAppend(pParse, p->pSub, pDup);
609 if( p->pSub ){
610 assert( ExprHasProperty(pExpr, EP_Static)==0 );
611 ExprSetProperty(pExpr, EP_Static);
612 sqlite3ExprDelete(pParse->db, pExpr);
613 ExprClearProperty(pExpr, EP_Static);
614 memset(pExpr, 0, sizeof(Expr));
615
616 pExpr->op = TK_COLUMN;
617 pExpr->iColumn = p->pSub->nExpr-1;
618 pExpr->iTable = p->pWin->iEphCsr;
619 }
620
621 break;
622 }
623
624 default: /* no-op */
625 break;
626 }
627
628 return WRC_Continue;
629}
danc0bb4452018-06-12 20:53:38 +0000630static int selectWindowRewriteSelectCb(Walker *pWalker, Select *pSelect){
631 return WRC_Prune;
632}
dandfa552f2018-06-02 21:04:28 +0000633
danc0bb4452018-06-12 20:53:38 +0000634
635/*
636** Iterate through each expression in expression-list pEList. For each:
637**
638** * TK_COLUMN,
639** * aggregate function, or
640** * window function with a Window object that is not a member of the
641** linked list passed as the second argument (pWin)
642**
643** Append the node to output expression-list (*ppSub). And replace it
644** with a TK_COLUMN that reads the (N-1)th element of table
645** pWin->iEphCsr, where N is the number of elements in (*ppSub) after
646** appending the new one.
647*/
dan13b08bb2018-06-15 20:46:12 +0000648static void selectWindowRewriteEList(
dandfa552f2018-06-02 21:04:28 +0000649 Parse *pParse,
650 Window *pWin,
651 ExprList *pEList, /* Rewrite expressions in this list */
652 ExprList **ppSub /* IN/OUT: Sub-select expression-list */
653){
654 Walker sWalker;
655 WindowRewrite sRewrite;
dandfa552f2018-06-02 21:04:28 +0000656
657 memset(&sWalker, 0, sizeof(Walker));
658 memset(&sRewrite, 0, sizeof(WindowRewrite));
659
660 sRewrite.pSub = *ppSub;
661 sRewrite.pWin = pWin;
662
663 sWalker.pParse = pParse;
664 sWalker.xExprCallback = selectWindowRewriteExprCb;
665 sWalker.xSelectCallback = selectWindowRewriteSelectCb;
666 sWalker.u.pRewrite = &sRewrite;
667
dan13b08bb2018-06-15 20:46:12 +0000668 (void)sqlite3WalkExprList(&sWalker, pEList);
dandfa552f2018-06-02 21:04:28 +0000669
670 *ppSub = sRewrite.pSub;
dandfa552f2018-06-02 21:04:28 +0000671}
672
danc0bb4452018-06-12 20:53:38 +0000673/*
674** Append a copy of each expression in expression-list pAppend to
675** expression list pList. Return a pointer to the result list.
676*/
dandfa552f2018-06-02 21:04:28 +0000677static ExprList *exprListAppendList(
678 Parse *pParse, /* Parsing context */
679 ExprList *pList, /* List to which to append. Might be NULL */
680 ExprList *pAppend /* List of values to append. Might be NULL */
681){
682 if( pAppend ){
683 int i;
684 int nInit = pList ? pList->nExpr : 0;
685 for(i=0; i<pAppend->nExpr; i++){
686 Expr *pDup = sqlite3ExprDup(pParse->db, pAppend->a[i].pExpr, 0);
687 pList = sqlite3ExprListAppend(pParse, pList, pDup);
688 if( pList ) pList->a[nInit+i].sortOrder = pAppend->a[i].sortOrder;
689 }
690 }
691 return pList;
692}
693
694/*
695** If the SELECT statement passed as the second argument does not invoke
696** any SQL window functions, this function is a no-op. Otherwise, it
697** rewrites the SELECT statement so that window function xStep functions
danc0bb4452018-06-12 20:53:38 +0000698** are invoked in the correct order as described under "SELECT REWRITING"
699** at the top of this file.
dandfa552f2018-06-02 21:04:28 +0000700*/
701int sqlite3WindowRewrite(Parse *pParse, Select *p){
702 int rc = SQLITE_OK;
703 if( p->pWin ){
704 Vdbe *v = sqlite3GetVdbe(pParse);
dandfa552f2018-06-02 21:04:28 +0000705 sqlite3 *db = pParse->db;
706 Select *pSub = 0; /* The subquery */
707 SrcList *pSrc = p->pSrc;
708 Expr *pWhere = p->pWhere;
709 ExprList *pGroupBy = p->pGroupBy;
710 Expr *pHaving = p->pHaving;
711 ExprList *pSort = 0;
712
713 ExprList *pSublist = 0; /* Expression list for sub-query */
714 Window *pMWin = p->pWin; /* Master window object */
715 Window *pWin; /* Window object iterator */
716
717 p->pSrc = 0;
718 p->pWhere = 0;
719 p->pGroupBy = 0;
720 p->pHaving = 0;
721
danf02cdd32018-06-27 19:48:50 +0000722 /* Create the ORDER BY clause for the sub-select. This is the concatenation
723 ** of the window PARTITION and ORDER BY clauses. Then, if this makes it
724 ** redundant, remove the ORDER BY from the parent SELECT. */
725 pSort = sqlite3ExprListDup(db, pMWin->pPartition, 0);
726 pSort = exprListAppendList(pParse, pSort, pMWin->pOrderBy);
727 if( pSort && p->pOrderBy ){
728 if( sqlite3ExprListCompare(pSort, p->pOrderBy, -1)==0 ){
729 sqlite3ExprListDelete(db, p->pOrderBy);
730 p->pOrderBy = 0;
731 }
732 }
733
dandfa552f2018-06-02 21:04:28 +0000734 /* Assign a cursor number for the ephemeral table used to buffer rows.
735 ** The OpenEphemeral instruction is coded later, after it is known how
736 ** many columns the table will have. */
737 pMWin->iEphCsr = pParse->nTab++;
738
dan13b08bb2018-06-15 20:46:12 +0000739 selectWindowRewriteEList(pParse, pMWin, p->pEList, &pSublist);
740 selectWindowRewriteEList(pParse, pMWin, p->pOrderBy, &pSublist);
dandfa552f2018-06-02 21:04:28 +0000741 pMWin->nBufferCol = (pSublist ? pSublist->nExpr : 0);
742
danf02cdd32018-06-27 19:48:50 +0000743 /* Append the PARTITION BY and ORDER BY expressions to the to the
744 ** sub-select expression list. They are required to figure out where
745 ** boundaries for partitions and sets of peer rows lie. */
746 pSublist = exprListAppendList(pParse, pSublist, pMWin->pPartition);
747 pSublist = exprListAppendList(pParse, pSublist, pMWin->pOrderBy);
dandfa552f2018-06-02 21:04:28 +0000748
749 /* Append the arguments passed to each window function to the
750 ** sub-select expression list. Also allocate two registers for each
751 ** window function - one for the accumulator, another for interim
752 ** results. */
753 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
754 pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);
755 pSublist = exprListAppendList(pParse, pSublist, pWin->pOwner->x.pList);
dan8b985602018-06-09 17:43:45 +0000756 if( pWin->pFilter ){
757 Expr *pFilter = sqlite3ExprDup(db, pWin->pFilter, 0);
758 pSublist = sqlite3ExprListAppend(pParse, pSublist, pFilter);
759 }
dandfa552f2018-06-02 21:04:28 +0000760 pWin->regAccum = ++pParse->nMem;
761 pWin->regResult = ++pParse->nMem;
762 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
763 }
764
dan9c277582018-06-20 09:23:49 +0000765 /* If there is no ORDER BY or PARTITION BY clause, and the window
766 ** function accepts zero arguments, and there are no other columns
767 ** selected (e.g. "SELECT row_number() OVER () FROM t1"), it is possible
768 ** that pSublist is still NULL here. Add a constant expression here to
769 ** keep everything legal in this case.
770 */
771 if( pSublist==0 ){
772 pSublist = sqlite3ExprListAppend(pParse, 0,
773 sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0)
774 );
775 }
776
dandfa552f2018-06-02 21:04:28 +0000777 pSub = sqlite3SelectNew(
778 pParse, pSublist, pSrc, pWhere, pGroupBy, pHaving, pSort, 0, 0
779 );
780 p->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
dan6fde1792018-06-15 19:01:35 +0000781 assert( p->pSrc || db->mallocFailed );
dandfa552f2018-06-02 21:04:28 +0000782 if( p->pSrc ){
dandfa552f2018-06-02 21:04:28 +0000783 p->pSrc->a[0].pSelect = pSub;
784 sqlite3SrcListAssignCursors(pParse, p->pSrc);
785 if( sqlite3ExpandSubquery(pParse, &p->pSrc->a[0]) ){
786 rc = SQLITE_NOMEM;
787 }else{
788 pSub->selFlags |= SF_Expanded;
dan73925692018-06-12 18:40:17 +0000789 p->selFlags &= ~SF_Aggregate;
790 sqlite3SelectPrep(pParse, pSub, 0);
dandfa552f2018-06-02 21:04:28 +0000791 }
dandfa552f2018-06-02 21:04:28 +0000792
dan6fde1792018-06-15 19:01:35 +0000793 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pMWin->iEphCsr, pSublist->nExpr);
794 }else{
795 sqlite3SelectDelete(db, pSub);
796 }
797 if( db->mallocFailed ) rc = SQLITE_NOMEM;
dandfa552f2018-06-02 21:04:28 +0000798 }
799
800 return rc;
801}
802
danc0bb4452018-06-12 20:53:38 +0000803/*
804** Free the Window object passed as the second argument.
805*/
dan86fb6e12018-05-16 20:58:07 +0000806void sqlite3WindowDelete(sqlite3 *db, Window *p){
807 if( p ){
808 sqlite3ExprDelete(db, p->pFilter);
809 sqlite3ExprListDelete(db, p->pPartition);
810 sqlite3ExprListDelete(db, p->pOrderBy);
811 sqlite3ExprDelete(db, p->pEnd);
812 sqlite3ExprDelete(db, p->pStart);
dane3bf6322018-06-08 20:58:27 +0000813 sqlite3DbFree(db, p->zName);
dan86fb6e12018-05-16 20:58:07 +0000814 sqlite3DbFree(db, p);
815 }
816}
817
danc0bb4452018-06-12 20:53:38 +0000818/*
819** Free the linked list of Window objects starting at the second argument.
820*/
dane3bf6322018-06-08 20:58:27 +0000821void sqlite3WindowListDelete(sqlite3 *db, Window *p){
822 while( p ){
823 Window *pNext = p->pNextWin;
824 sqlite3WindowDelete(db, p);
825 p = pNext;
826 }
827}
828
danc0bb4452018-06-12 20:53:38 +0000829/*
drhe4984a22018-07-06 17:19:20 +0000830** The argument expression is an PRECEDING or FOLLOWING offset. The
831** value should be a non-negative integer. If the value is not a
832** constant, change it to NULL. The fact that it is then a non-negative
833** integer will be caught later. But it is important not to leave
834** variable values in the expression tree.
835*/
836static Expr *sqlite3WindowOffsetExpr(Parse *pParse, Expr *pExpr){
837 if( 0==sqlite3ExprIsConstant(pExpr) ){
838 sqlite3ExprDelete(pParse->db, pExpr);
839 pExpr = sqlite3ExprAlloc(pParse->db, TK_NULL, 0, 0);
840 }
841 return pExpr;
842}
843
844/*
845** Allocate and return a new Window object describing a Window Definition.
danc0bb4452018-06-12 20:53:38 +0000846*/
dan86fb6e12018-05-16 20:58:07 +0000847Window *sqlite3WindowAlloc(
drhe4984a22018-07-06 17:19:20 +0000848 Parse *pParse, /* Parsing context */
849 int eType, /* Frame type. TK_RANGE or TK_ROWS */
850 int eStart, /* Start type: CURRENT, PRECEDING, FOLLOWING, UNBOUNDED */
851 Expr *pStart, /* Start window size if TK_PRECEDING or FOLLOWING */
852 int eEnd, /* End type: CURRENT, FOLLOWING, TK_UNBOUNDED, PRECEDING */
853 Expr *pEnd /* End window size if TK_FOLLOWING or PRECEDING */
dan86fb6e12018-05-16 20:58:07 +0000854){
dan7a606e12018-07-05 18:34:53 +0000855 Window *pWin = 0;
856
drhe4984a22018-07-06 17:19:20 +0000857 /* Parser assures the following: */
858 assert( eType==TK_RANGE || eType==TK_ROWS );
859 assert( eStart==TK_CURRENT || eStart==TK_PRECEDING
860 || eStart==TK_UNBOUNDED || eStart==TK_FOLLOWING );
861 assert( eEnd==TK_CURRENT || eEnd==TK_FOLLOWING
862 || eEnd==TK_UNBOUNDED || eEnd==TK_PRECEDING );
863 assert( (eStart==TK_PRECEDING || eStart==TK_FOLLOWING)==(pStart!=0) );
864 assert( (eEnd==TK_FOLLOWING || eEnd==TK_PRECEDING)==(pEnd!=0) );
865
866
dan5d764ac2018-07-06 14:15:49 +0000867 /* If a frame is declared "RANGE" (not "ROWS"), then it may not use
drhe4984a22018-07-06 17:19:20 +0000868 ** either "<expr> PRECEDING" or "<expr> FOLLOWING".
869 */
870 if( eType==TK_RANGE && (pStart!=0 || pEnd!=0) ){
871 sqlite3ErrorMsg(pParse, "RANGE must use only UNBOUNDED or CURRENT ROW");
872 goto windowAllocErr;
873 }
874
875 /* Additionally, the
dan5d764ac2018-07-06 14:15:49 +0000876 ** starting boundary type may not occur earlier in the following list than
877 ** the ending boundary type:
878 **
879 ** UNBOUNDED PRECEDING
880 ** <expr> PRECEDING
881 ** CURRENT ROW
882 ** <expr> FOLLOWING
883 ** UNBOUNDED FOLLOWING
884 **
885 ** The parser ensures that "UNBOUNDED PRECEDING" cannot be used as an ending
886 ** boundary, and than "UNBOUNDED FOLLOWING" cannot be used as a starting
887 ** frame boundary.
888 */
drhe4984a22018-07-06 17:19:20 +0000889 if( (eStart==TK_CURRENT && eEnd==TK_PRECEDING)
dan5d764ac2018-07-06 14:15:49 +0000890 || (eStart==TK_FOLLOWING && (eEnd==TK_PRECEDING || eEnd==TK_CURRENT))
891 ){
drhe4984a22018-07-06 17:19:20 +0000892 sqlite3ErrorMsg(pParse, "unsupported frame delimiter for ROWS");
893 goto windowAllocErr;
dan7a606e12018-07-05 18:34:53 +0000894 }
dan86fb6e12018-05-16 20:58:07 +0000895
drhe4984a22018-07-06 17:19:20 +0000896 pWin = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
897 if( pWin==0 ) goto windowAllocErr;
898 pWin->eType = eType;
899 pWin->eStart = eStart;
900 pWin->eEnd = eEnd;
901 pWin->pEnd = sqlite3WindowOffsetExpr(pParse, pEnd);
902 pWin->pStart = sqlite3WindowOffsetExpr(pParse, pStart);
dan86fb6e12018-05-16 20:58:07 +0000903 return pWin;
drhe4984a22018-07-06 17:19:20 +0000904
905windowAllocErr:
906 sqlite3ExprDelete(pParse->db, pEnd);
907 sqlite3ExprDelete(pParse->db, pStart);
908 return 0;
dan86fb6e12018-05-16 20:58:07 +0000909}
910
danc0bb4452018-06-12 20:53:38 +0000911/*
912** Attach window object pWin to expression p.
913*/
dan86fb6e12018-05-16 20:58:07 +0000914void sqlite3WindowAttach(Parse *pParse, Expr *p, Window *pWin){
915 if( p ){
dane33f6e72018-07-06 07:42:42 +0000916 if( pWin ){
917 p->pWin = pWin;
918 pWin->pOwner = p;
919 if( p->flags & EP_Distinct ){
drhe4984a22018-07-06 17:19:20 +0000920 sqlite3ErrorMsg(pParse,
921 "DISTINCT is not supported for window functions");
dane33f6e72018-07-06 07:42:42 +0000922 }
923 }
dan86fb6e12018-05-16 20:58:07 +0000924 }else{
925 sqlite3WindowDelete(pParse->db, pWin);
926 }
927}
dane2f781b2018-05-17 19:24:08 +0000928
929/*
930** Return 0 if the two window objects are identical, or non-zero otherwise.
dan13078ca2018-06-13 20:29:38 +0000931** Identical window objects can be processed in a single scan.
dane2f781b2018-05-17 19:24:08 +0000932*/
933int sqlite3WindowCompare(Parse *pParse, Window *p1, Window *p2){
934 if( p1->eType!=p2->eType ) return 1;
935 if( p1->eStart!=p2->eStart ) return 1;
936 if( p1->eEnd!=p2->eEnd ) return 1;
937 if( sqlite3ExprCompare(pParse, p1->pStart, p2->pStart, -1) ) return 1;
938 if( sqlite3ExprCompare(pParse, p1->pEnd, p2->pEnd, -1) ) return 1;
939 if( sqlite3ExprListCompare(p1->pPartition, p2->pPartition, -1) ) return 1;
940 if( sqlite3ExprListCompare(p1->pOrderBy, p2->pOrderBy, -1) ) return 1;
941 return 0;
942}
943
dan13078ca2018-06-13 20:29:38 +0000944
945/*
946** This is called by code in select.c before it calls sqlite3WhereBegin()
947** to begin iterating through the sub-query results. It is used to allocate
948** and initialize registers and cursors used by sqlite3WindowCodeStep().
949*/
950void sqlite3WindowCodeInit(Parse *pParse, Window *pMWin){
danc9a86682018-05-30 20:44:58 +0000951 Window *pWin;
dan13078ca2018-06-13 20:29:38 +0000952 Vdbe *v = sqlite3GetVdbe(pParse);
953 int nPart = (pMWin->pPartition ? pMWin->pPartition->nExpr : 0);
954 nPart += (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);
955 if( nPart ){
956 pMWin->regPart = pParse->nMem+1;
957 pParse->nMem += nPart;
958 sqlite3VdbeAddOp3(v, OP_Null, 0, pMWin->regPart, pMWin->regPart+nPart-1);
959 }
960
danc9a86682018-05-30 20:44:58 +0000961 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
danec891fd2018-06-06 20:51:02 +0000962 FuncDef *p = pWin->pFunc;
963 if( (p->funcFlags & SQLITE_FUNC_MINMAX) && pWin->eStart!=TK_UNBOUNDED ){
dan9a947222018-06-14 19:06:36 +0000964 /* The inline versions of min() and max() require a single ephemeral
965 ** table and 3 registers. The registers are used as follows:
966 **
967 ** regApp+0: slot to copy min()/max() argument to for MakeRecord
968 ** regApp+1: integer value used to ensure keys are unique
969 ** regApp+2: output of MakeRecord
970 */
danc9a86682018-05-30 20:44:58 +0000971 ExprList *pList = pWin->pOwner->x.pList;
972 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pList, 0, 0);
danc9a86682018-05-30 20:44:58 +0000973 pWin->csrApp = pParse->nTab++;
974 pWin->regApp = pParse->nMem+1;
975 pParse->nMem += 3;
976 if( pKeyInfo && pWin->pFunc->zName[1]=='i' ){
977 assert( pKeyInfo->aSortOrder[0]==0 );
978 pKeyInfo->aSortOrder[0] = 1;
979 }
980 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pWin->csrApp, 2);
981 sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
982 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
983 }
dan7095c002018-06-07 17:45:22 +0000984 else if( p->xSFunc==nth_valueStepFunc || p->xSFunc==first_valueStepFunc ){
danec891fd2018-06-06 20:51:02 +0000985 /* Allocate two registers at pWin->regApp. These will be used to
986 ** store the start and end index of the current frame. */
987 assert( pMWin->iEphCsr );
988 pWin->regApp = pParse->nMem+1;
989 pWin->csrApp = pParse->nTab++;
990 pParse->nMem += 2;
danec891fd2018-06-06 20:51:02 +0000991 sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
992 }
danfe4e25a2018-06-07 20:08:59 +0000993 else if( p->xSFunc==leadStepFunc || p->xSFunc==lagStepFunc ){
994 assert( pMWin->iEphCsr );
995 pWin->csrApp = pParse->nTab++;
996 sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
997 }
danc9a86682018-05-30 20:44:58 +0000998 }
999}
1000
dan13078ca2018-06-13 20:29:38 +00001001/*
1002** A "PRECEDING <expr>" (bEnd==0) or "FOLLOWING <expr>" (bEnd==1) has just
1003** been evaluated and the result left in register reg. This function generates
1004** VM code to check that the value is a non-negative integer and throws
1005** an exception if it is not.
1006*/
drhe4984a22018-07-06 17:19:20 +00001007static void windowCheckFrameOffset(Parse *pParse, int reg, int bEnd){
danc3a20c12018-05-23 20:55:37 +00001008 static const char *azErr[] = {
1009 "frame starting offset must be a non-negative integer",
1010 "frame ending offset must be a non-negative integer"
1011 };
1012 Vdbe *v = sqlite3GetVdbe(pParse);
dan13078ca2018-06-13 20:29:38 +00001013 int regZero = sqlite3GetTempReg(pParse);
danc3a20c12018-05-23 20:55:37 +00001014 sqlite3VdbeAddOp2(v, OP_Integer, 0, regZero);
1015 sqlite3VdbeAddOp2(v, OP_MustBeInt, reg, sqlite3VdbeCurrentAddr(v)+2);
1016 sqlite3VdbeAddOp3(v, OP_Ge, regZero, sqlite3VdbeCurrentAddr(v)+2, reg);
dan01e12292018-06-27 20:24:59 +00001017 VdbeCoverage(v);
danc3a20c12018-05-23 20:55:37 +00001018 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_ERROR, OE_Abort);
1019 sqlite3VdbeAppendP4(v, (void*)azErr[bEnd], P4_STATIC);
dan13078ca2018-06-13 20:29:38 +00001020 sqlite3ReleaseTempReg(pParse, regZero);
danc3a20c12018-05-23 20:55:37 +00001021}
1022
dan13078ca2018-06-13 20:29:38 +00001023/*
1024** Return the number of arguments passed to the window-function associated
1025** with the object passed as the only argument to this function.
1026*/
dan2a11bb22018-06-11 20:50:25 +00001027static int windowArgCount(Window *pWin){
1028 ExprList *pList = pWin->pOwner->x.pList;
1029 return (pList ? pList->nExpr : 0);
1030}
1031
danc9a86682018-05-30 20:44:58 +00001032/*
1033** Generate VM code to invoke either xStep() (if bInverse is 0) or
1034** xInverse (if bInverse is non-zero) for each window function in the
dan13078ca2018-06-13 20:29:38 +00001035** linked list starting at pMWin. Or, for built-in window functions
1036** that do not use the standard function API, generate the required
1037** inline VM code.
1038**
1039** If argument csr is greater than or equal to 0, then argument reg is
1040** the first register in an array of registers guaranteed to be large
1041** enough to hold the array of arguments for each function. In this case
1042** the arguments are extracted from the current row of csr into the
drh8f26da62018-07-05 21:22:57 +00001043** array of registers before invoking OP_AggStep or OP_AggInverse
dan13078ca2018-06-13 20:29:38 +00001044**
1045** Or, if csr is less than zero, then the array of registers at reg is
1046** already populated with all columns from the current row of the sub-query.
1047**
1048** If argument regPartSize is non-zero, then it is a register containing the
1049** number of rows in the current partition.
danc9a86682018-05-30 20:44:58 +00001050*/
dan31f56392018-05-24 21:10:57 +00001051static void windowAggStep(
1052 Parse *pParse,
dan13078ca2018-06-13 20:29:38 +00001053 Window *pMWin, /* Linked list of window functions */
1054 int csr, /* Read arguments from this cursor */
1055 int bInverse, /* True to invoke xInverse instead of xStep */
1056 int reg, /* Array of registers */
dandfa552f2018-06-02 21:04:28 +00001057 int regPartSize /* Register containing size of partition */
dan31f56392018-05-24 21:10:57 +00001058){
1059 Vdbe *v = sqlite3GetVdbe(pParse);
1060 Window *pWin;
1061 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
dandfa552f2018-06-02 21:04:28 +00001062 int flags = pWin->pFunc->funcFlags;
danc9a86682018-05-30 20:44:58 +00001063 int regArg;
dan2a11bb22018-06-11 20:50:25 +00001064 int nArg = windowArgCount(pWin);
dandfa552f2018-06-02 21:04:28 +00001065
dan6bc5c9e2018-06-04 18:55:11 +00001066 if( csr>=0 ){
danc9a86682018-05-30 20:44:58 +00001067 int i;
dan2a11bb22018-06-11 20:50:25 +00001068 for(i=0; i<nArg; i++){
danc9a86682018-05-30 20:44:58 +00001069 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+i, reg+i);
1070 }
1071 regArg = reg;
dan6bc5c9e2018-06-04 18:55:11 +00001072 if( flags & SQLITE_FUNC_WINDOW_SIZE ){
1073 if( nArg==0 ){
1074 regArg = regPartSize;
1075 }else{
1076 sqlite3VdbeAddOp2(v, OP_SCopy, regPartSize, reg+nArg);
1077 }
1078 nArg++;
1079 }
danc9a86682018-05-30 20:44:58 +00001080 }else{
dan6bc5c9e2018-06-04 18:55:11 +00001081 assert( !(flags & SQLITE_FUNC_WINDOW_SIZE) );
danc9a86682018-05-30 20:44:58 +00001082 regArg = reg + pWin->iArgCol;
dan31f56392018-05-24 21:10:57 +00001083 }
danc9a86682018-05-30 20:44:58 +00001084
danec891fd2018-06-06 20:51:02 +00001085 if( (pWin->pFunc->funcFlags & SQLITE_FUNC_MINMAX)
1086 && pWin->eStart!=TK_UNBOUNDED
1087 ){
dand4fc49f2018-07-07 17:30:44 +00001088 int addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regArg);
1089 VdbeCoverage(v);
danc9a86682018-05-30 20:44:58 +00001090 if( bInverse==0 ){
1091 sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1, 1);
1092 sqlite3VdbeAddOp2(v, OP_SCopy, regArg, pWin->regApp);
1093 sqlite3VdbeAddOp3(v, OP_MakeRecord, pWin->regApp, 2, pWin->regApp+2);
1094 sqlite3VdbeAddOp2(v, OP_IdxInsert, pWin->csrApp, pWin->regApp+2);
1095 }else{
1096 sqlite3VdbeAddOp4Int(v, OP_SeekGE, pWin->csrApp, 0, regArg, 1);
dan01e12292018-06-27 20:24:59 +00001097 VdbeCoverage(v);
danc9a86682018-05-30 20:44:58 +00001098 sqlite3VdbeAddOp1(v, OP_Delete, pWin->csrApp);
1099 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
1100 }
dand4fc49f2018-07-07 17:30:44 +00001101 sqlite3VdbeJumpHere(v, addrIsNull);
danec891fd2018-06-06 20:51:02 +00001102 }else if( pWin->regApp ){
dan7095c002018-06-07 17:45:22 +00001103 assert( pWin->pFunc->xSFunc==nth_valueStepFunc
1104 || pWin->pFunc->xSFunc==first_valueStepFunc
1105 );
danec891fd2018-06-06 20:51:02 +00001106 assert( bInverse==0 || bInverse==1 );
1107 sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1-bInverse, 1);
danfe4e25a2018-06-07 20:08:59 +00001108 }else if( pWin->pFunc->xSFunc==leadStepFunc
1109 || pWin->pFunc->xSFunc==lagStepFunc
1110 ){
1111 /* no-op */
danc9a86682018-05-30 20:44:58 +00001112 }else{
dan8b985602018-06-09 17:43:45 +00001113 int addrIf = 0;
1114 if( pWin->pFilter ){
1115 int regTmp;
dan2a11bb22018-06-11 20:50:25 +00001116 assert( nArg==pWin->pOwner->x.pList->nExpr );
dan8b985602018-06-09 17:43:45 +00001117 if( csr>0 ){
1118 regTmp = sqlite3GetTempReg(pParse);
dan2a11bb22018-06-11 20:50:25 +00001119 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+nArg,regTmp);
dan8b985602018-06-09 17:43:45 +00001120 }else{
dan2a11bb22018-06-11 20:50:25 +00001121 regTmp = regArg + nArg;
dan8b985602018-06-09 17:43:45 +00001122 }
1123 addrIf = sqlite3VdbeAddOp3(v, OP_IfNot, regTmp, 0, 1);
dan01e12292018-06-27 20:24:59 +00001124 VdbeCoverage(v);
dan8b985602018-06-09 17:43:45 +00001125 if( csr>0 ){
1126 sqlite3ReleaseTempReg(pParse, regTmp);
1127 }
1128 }
danc9a86682018-05-30 20:44:58 +00001129 if( pWin->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
1130 CollSeq *pColl;
dan8b985602018-06-09 17:43:45 +00001131 pColl = sqlite3ExprNNCollSeq(pParse, pWin->pOwner->x.pList->a[0].pExpr);
danc9a86682018-05-30 20:44:58 +00001132 sqlite3VdbeAddOp4(v, OP_CollSeq, 0,0,0, (const char*)pColl, P4_COLLSEQ);
1133 }
drh8f26da62018-07-05 21:22:57 +00001134 sqlite3VdbeAddOp3(v, bInverse? OP_AggInverse : OP_AggStep,
1135 bInverse, regArg, pWin->regAccum);
danc9a86682018-05-30 20:44:58 +00001136 sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
dandfa552f2018-06-02 21:04:28 +00001137 sqlite3VdbeChangeP5(v, (u8)nArg);
dan8b985602018-06-09 17:43:45 +00001138 if( addrIf ) sqlite3VdbeJumpHere(v, addrIf);
danc9a86682018-05-30 20:44:58 +00001139 }
dan31f56392018-05-24 21:10:57 +00001140 }
1141}
1142
dan13078ca2018-06-13 20:29:38 +00001143/*
1144** Generate VM code to invoke either xValue() (bFinal==0) or xFinalize()
1145** (bFinal==1) for each window function in the linked list starting at
1146** pMWin. Or, for built-in window-functions that do not use the standard
1147** API, generate the equivalent VM code.
1148*/
dand6f784e2018-05-28 18:30:45 +00001149static void windowAggFinal(Parse *pParse, Window *pMWin, int bFinal){
1150 Vdbe *v = sqlite3GetVdbe(pParse);
1151 Window *pWin;
1152
1153 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
danec891fd2018-06-06 20:51:02 +00001154 if( (pWin->pFunc->funcFlags & SQLITE_FUNC_MINMAX)
1155 && pWin->eStart!=TK_UNBOUNDED
1156 ){
dand6f784e2018-05-28 18:30:45 +00001157 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
danc9a86682018-05-30 20:44:58 +00001158 sqlite3VdbeAddOp1(v, OP_Last, pWin->csrApp);
dan01e12292018-06-27 20:24:59 +00001159 VdbeCoverage(v);
danc9a86682018-05-30 20:44:58 +00001160 sqlite3VdbeAddOp3(v, OP_Column, pWin->csrApp, 0, pWin->regResult);
1161 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
1162 if( bFinal ){
1163 sqlite3VdbeAddOp1(v, OP_ResetSorter, pWin->csrApp);
1164 }
danec891fd2018-06-06 20:51:02 +00001165 }else if( pWin->regApp ){
dand6f784e2018-05-28 18:30:45 +00001166 }else{
danc9a86682018-05-30 20:44:58 +00001167 if( bFinal ){
drh8f26da62018-07-05 21:22:57 +00001168 sqlite3VdbeAddOp2(v, OP_AggFinal, pWin->regAccum, windowArgCount(pWin));
1169 sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
danc9a86682018-05-30 20:44:58 +00001170 sqlite3VdbeAddOp2(v, OP_Copy, pWin->regAccum, pWin->regResult);
dan8b985602018-06-09 17:43:45 +00001171 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
danc9a86682018-05-30 20:44:58 +00001172 }else{
drh8f26da62018-07-05 21:22:57 +00001173 sqlite3VdbeAddOp3(v, OP_AggValue, pWin->regAccum, windowArgCount(pWin),
1174 pWin->regResult);
1175 sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
danc9a86682018-05-30 20:44:58 +00001176 }
dand6f784e2018-05-28 18:30:45 +00001177 }
1178 }
1179}
1180
dan13078ca2018-06-13 20:29:38 +00001181/*
1182** This function generates VM code to invoke the sub-routine at address
1183** lblFlushPart once for each partition with the entire partition cached in
1184** the Window.iEphCsr temp table.
1185*/
danf690b572018-06-01 21:00:08 +00001186static void windowPartitionCache(
1187 Parse *pParse,
dan13078ca2018-06-13 20:29:38 +00001188 Select *p, /* The rewritten SELECT statement */
1189 WhereInfo *pWInfo, /* WhereInfo to call WhereEnd() on */
1190 int regFlushPart, /* Register to use with Gosub lblFlushPart */
1191 int lblFlushPart, /* Subroutine to Gosub to */
1192 int *pRegSize /* OUT: Register containing partition size */
danf690b572018-06-01 21:00:08 +00001193){
1194 Window *pMWin = p->pWin;
1195 Vdbe *v = sqlite3GetVdbe(pParse);
danf690b572018-06-01 21:00:08 +00001196 int iSubCsr = p->pSrc->a[0].iCursor;
1197 int nSub = p->pSrc->a[0].pTab->nCol;
1198 int k;
1199
1200 int reg = pParse->nMem+1;
1201 int regRecord = reg+nSub;
1202 int regRowid = regRecord+1;
1203
dandfa552f2018-06-02 21:04:28 +00001204 *pRegSize = regRowid;
danf690b572018-06-01 21:00:08 +00001205 pParse->nMem += nSub + 2;
1206
1207 /* Martial the row returned by the sub-select into an array of
1208 ** registers. */
1209 for(k=0; k<nSub; k++){
1210 sqlite3VdbeAddOp3(v, OP_Column, iSubCsr, k, reg+k);
1211 }
1212 sqlite3VdbeAddOp3(v, OP_MakeRecord, reg, nSub, regRecord);
1213
1214 /* Check if this is the start of a new partition. If so, call the
1215 ** flush_partition sub-routine. */
1216 if( pMWin->pPartition ){
1217 int addr;
1218 ExprList *pPart = pMWin->pPartition;
dane0a5e202018-06-15 16:10:44 +00001219 int nPart = pPart->nExpr;
danf690b572018-06-01 21:00:08 +00001220 int regNewPart = reg + pMWin->nBufferCol;
1221 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pPart, 0, 0);
1222
1223 addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPart, pMWin->regPart,nPart);
1224 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
1225 sqlite3VdbeAddOp3(v, OP_Jump, addr+2, addr+4, addr+2);
dan01e12292018-06-27 20:24:59 +00001226 VdbeCoverage(v);
danf690b572018-06-01 21:00:08 +00001227 sqlite3VdbeAddOp3(v, OP_Copy, regNewPart, pMWin->regPart, nPart-1);
1228 sqlite3VdbeAddOp2(v, OP_Gosub, regFlushPart, lblFlushPart);
1229 }
1230
1231 /* Buffer the current row in the ephemeral table. */
1232 sqlite3VdbeAddOp2(v, OP_NewRowid, pMWin->iEphCsr, regRowid);
1233 sqlite3VdbeAddOp3(v, OP_Insert, pMWin->iEphCsr, regRecord, regRowid);
1234
1235 /* End of the input loop */
1236 sqlite3WhereEnd(pWInfo);
1237
1238 /* Invoke "flush_partition" to deal with the final (or only) partition */
1239 sqlite3VdbeAddOp2(v, OP_Gosub, regFlushPart, lblFlushPart);
1240}
dand6f784e2018-05-28 18:30:45 +00001241
dan13078ca2018-06-13 20:29:38 +00001242/*
1243** Invoke the sub-routine at regGosub (generated by code in select.c) to
1244** return the current row of Window.iEphCsr. If all window functions are
1245** aggregate window functions that use the standard API, a single
1246** OP_Gosub instruction is all that this routine generates. Extra VM code
1247** for per-row processing is only generated for the following built-in window
1248** functions:
1249**
1250** nth_value()
1251** first_value()
1252** lag()
1253** lead()
1254*/
danec891fd2018-06-06 20:51:02 +00001255static void windowReturnOneRow(
1256 Parse *pParse,
1257 Window *pMWin,
1258 int regGosub,
1259 int addrGosub
1260){
1261 Vdbe *v = sqlite3GetVdbe(pParse);
1262 Window *pWin;
1263 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1264 FuncDef *pFunc = pWin->pFunc;
dan7095c002018-06-07 17:45:22 +00001265 if( pFunc->xSFunc==nth_valueStepFunc
1266 || pFunc->xSFunc==first_valueStepFunc
1267 ){
danec891fd2018-06-06 20:51:02 +00001268 int csr = pWin->csrApp;
1269 int lbl = sqlite3VdbeMakeLabel(v);
1270 int tmpReg = sqlite3GetTempReg(pParse);
1271 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
dan7095c002018-06-07 17:45:22 +00001272
1273 if( pFunc->xSFunc==nth_valueStepFunc ){
dan6fde1792018-06-15 19:01:35 +00001274 sqlite3VdbeAddOp3(v, OP_Column, pMWin->iEphCsr, pWin->iArgCol+1,tmpReg);
dan7095c002018-06-07 17:45:22 +00001275 }else{
1276 sqlite3VdbeAddOp2(v, OP_Integer, 1, tmpReg);
1277 }
danec891fd2018-06-06 20:51:02 +00001278 sqlite3VdbeAddOp3(v, OP_Add, tmpReg, pWin->regApp, tmpReg);
1279 sqlite3VdbeAddOp3(v, OP_Gt, pWin->regApp+1, lbl, tmpReg);
dan01e12292018-06-27 20:24:59 +00001280 VdbeCoverage(v);
danec891fd2018-06-06 20:51:02 +00001281 sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, lbl, tmpReg);
dan01e12292018-06-27 20:24:59 +00001282 VdbeCoverage(v);
danec891fd2018-06-06 20:51:02 +00001283 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
1284 sqlite3VdbeResolveLabel(v, lbl);
1285 sqlite3ReleaseTempReg(pParse, tmpReg);
1286 }
danfe4e25a2018-06-07 20:08:59 +00001287 else if( pFunc->xSFunc==leadStepFunc || pFunc->xSFunc==lagStepFunc ){
dan2a11bb22018-06-11 20:50:25 +00001288 int nArg = pWin->pOwner->x.pList->nExpr;
dane0a5e202018-06-15 16:10:44 +00001289 int iEph = pMWin->iEphCsr;
danfe4e25a2018-06-07 20:08:59 +00001290 int csr = pWin->csrApp;
1291 int lbl = sqlite3VdbeMakeLabel(v);
1292 int tmpReg = sqlite3GetTempReg(pParse);
1293
dan2a11bb22018-06-11 20:50:25 +00001294 if( nArg<3 ){
danfe4e25a2018-06-07 20:08:59 +00001295 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
1296 }else{
1297 sqlite3VdbeAddOp3(v, OP_Column, iEph, pWin->iArgCol+2, pWin->regResult);
1298 }
1299 sqlite3VdbeAddOp2(v, OP_Rowid, iEph, tmpReg);
dan2a11bb22018-06-11 20:50:25 +00001300 if( nArg<2 ){
danfe4e25a2018-06-07 20:08:59 +00001301 int val = (pFunc->xSFunc==leadStepFunc ? 1 : -1);
1302 sqlite3VdbeAddOp2(v, OP_AddImm, tmpReg, val);
1303 }else{
1304 int op = (pFunc->xSFunc==leadStepFunc ? OP_Add : OP_Subtract);
1305 int tmpReg2 = sqlite3GetTempReg(pParse);
1306 sqlite3VdbeAddOp3(v, OP_Column, iEph, pWin->iArgCol+1, tmpReg2);
1307 sqlite3VdbeAddOp3(v, op, tmpReg2, tmpReg, tmpReg);
1308 sqlite3ReleaseTempReg(pParse, tmpReg2);
1309 }
1310
1311 sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, lbl, tmpReg);
dan01e12292018-06-27 20:24:59 +00001312 VdbeCoverage(v);
danfe4e25a2018-06-07 20:08:59 +00001313 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
1314 sqlite3VdbeResolveLabel(v, lbl);
1315 sqlite3ReleaseTempReg(pParse, tmpReg);
1316 }
danec891fd2018-06-06 20:51:02 +00001317 }
1318 sqlite3VdbeAddOp2(v, OP_Gosub, regGosub, addrGosub);
1319}
1320
dan13078ca2018-06-13 20:29:38 +00001321/*
1322** Invoke the code generated by windowReturnOneRow() and, optionally, the
1323** xInverse() function for each window function, for one or more rows
1324** from the Window.iEphCsr temp table. This routine generates VM code
1325** similar to:
1326**
1327** while( regCtr>0 ){
1328** regCtr--;
1329** windowReturnOneRow()
1330** if( bInverse ){
drh8f26da62018-07-05 21:22:57 +00001331** AggInverse
dan13078ca2018-06-13 20:29:38 +00001332** }
1333** Next (Window.iEphCsr)
1334** }
1335*/
danec891fd2018-06-06 20:51:02 +00001336static void windowReturnRows(
1337 Parse *pParse,
dan13078ca2018-06-13 20:29:38 +00001338 Window *pMWin, /* List of window functions */
1339 int regCtr, /* Register containing number of rows */
1340 int regGosub, /* Register for Gosub addrGosub */
1341 int addrGosub, /* Address of sub-routine for ReturnOneRow */
1342 int regInvArg, /* Array of registers for xInverse args */
1343 int regInvSize /* Register containing size of partition */
danec891fd2018-06-06 20:51:02 +00001344){
1345 int addr;
1346 Vdbe *v = sqlite3GetVdbe(pParse);
1347 windowAggFinal(pParse, pMWin, 0);
1348 addr = sqlite3VdbeAddOp3(v, OP_IfPos, regCtr, sqlite3VdbeCurrentAddr(v)+2 ,1);
dan01e12292018-06-27 20:24:59 +00001349 VdbeCoverage(v);
danec891fd2018-06-06 20:51:02 +00001350 sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
1351 windowReturnOneRow(pParse, pMWin, regGosub, addrGosub);
1352 if( regInvArg ){
1353 windowAggStep(pParse, pMWin, pMWin->iEphCsr, 1, regInvArg, regInvSize);
1354 }
1355 sqlite3VdbeAddOp2(v, OP_Next, pMWin->iEphCsr, addr);
dan01e12292018-06-27 20:24:59 +00001356 VdbeCoverage(v);
danec891fd2018-06-06 20:51:02 +00001357 sqlite3VdbeJumpHere(v, addr+1); /* The OP_Goto */
1358}
1359
dan54a9ab32018-06-14 14:27:05 +00001360/*
1361** Generate code to set the accumulator register for each window function
1362** in the linked list passed as the second argument to NULL. And perform
1363** any equivalent initialization required by any built-in window functions
1364** in the list.
1365*/
dan2e605682018-06-07 15:54:26 +00001366static int windowInitAccum(Parse *pParse, Window *pMWin){
1367 Vdbe *v = sqlite3GetVdbe(pParse);
1368 int regArg;
1369 int nArg = 0;
1370 Window *pWin;
1371 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
dan9a947222018-06-14 19:06:36 +00001372 FuncDef *pFunc = pWin->pFunc;
dan2e605682018-06-07 15:54:26 +00001373 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
dan2a11bb22018-06-11 20:50:25 +00001374 nArg = MAX(nArg, windowArgCount(pWin));
dan9a947222018-06-14 19:06:36 +00001375 if( pFunc->xSFunc==nth_valueStepFunc
1376 || pFunc->xSFunc==first_valueStepFunc
dan7095c002018-06-07 17:45:22 +00001377 ){
dan2e605682018-06-07 15:54:26 +00001378 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp);
1379 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
1380 }
dan9a947222018-06-14 19:06:36 +00001381
1382 if( (pFunc->funcFlags & SQLITE_FUNC_MINMAX) && pWin->csrApp ){
1383 assert( pWin->eStart!=TK_UNBOUNDED );
1384 sqlite3VdbeAddOp1(v, OP_ResetSorter, pWin->csrApp);
1385 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
1386 }
dan2e605682018-06-07 15:54:26 +00001387 }
1388 regArg = pParse->nMem+1;
1389 pParse->nMem += nArg;
1390 return regArg;
1391}
1392
1393
dan99652dd2018-05-24 17:49:14 +00001394/*
dan54a9ab32018-06-14 14:27:05 +00001395** This function does the work of sqlite3WindowCodeStep() for all "ROWS"
1396** window frame types except for "BETWEEN UNBOUNDED PRECEDING AND CURRENT
1397** ROW". Pseudo-code for each follows.
1398**
dan09590aa2018-05-25 20:30:17 +00001399** ROWS BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
dan09590aa2018-05-25 20:30:17 +00001400**
1401** ...
1402** if( new partition ){
1403** Gosub flush_partition
1404** }
1405** Insert (record in eph-table)
1406** sqlite3WhereEnd()
1407** Gosub flush_partition
1408**
1409** flush_partition:
1410** Once {
1411** OpenDup (iEphCsr -> csrStart)
1412** OpenDup (iEphCsr -> csrEnd)
dan99652dd2018-05-24 17:49:14 +00001413** }
dan09590aa2018-05-25 20:30:17 +00001414** regStart = <expr1> // PRECEDING expression
1415** regEnd = <expr2> // FOLLOWING expression
1416** if( regStart<0 || regEnd<0 ){ error! }
1417** Rewind (csr,csrStart,csrEnd) // if EOF goto flush_partition_done
1418** Next(csrEnd) // if EOF skip Aggstep
1419** Aggstep (csrEnd)
1420** if( (regEnd--)<=0 ){
1421** AggFinal (xValue)
1422** Gosub addrGosub
1423** Next(csr) // if EOF goto flush_partition_done
1424** if( (regStart--)<=0 ){
drh8f26da62018-07-05 21:22:57 +00001425** AggInverse (csrStart)
dan09590aa2018-05-25 20:30:17 +00001426** Next(csrStart)
1427** }
1428** }
1429** flush_partition_done:
1430** ResetSorter (csr)
1431** Return
dan99652dd2018-05-24 17:49:14 +00001432**
dan09590aa2018-05-25 20:30:17 +00001433** ROWS BETWEEN <expr> PRECEDING AND CURRENT ROW
1434** ROWS BETWEEN CURRENT ROW AND <expr> FOLLOWING
1435** ROWS BETWEEN UNBOUNDED PRECEDING AND <expr> FOLLOWING
1436**
1437** These are similar to the above. For "CURRENT ROW", intialize the
1438** register to 0. For "UNBOUNDED PRECEDING" to infinity.
1439**
1440** ROWS BETWEEN <expr> PRECEDING AND UNBOUNDED FOLLOWING
1441** ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
1442**
1443** Rewind (csr,csrStart,csrEnd) // if EOF goto flush_partition_done
1444** while( 1 ){
1445** Next(csrEnd) // Exit while(1) at EOF
1446** Aggstep (csrEnd)
1447** }
1448** while( 1 ){
dan99652dd2018-05-24 17:49:14 +00001449** AggFinal (xValue)
1450** Gosub addrGosub
dan09590aa2018-05-25 20:30:17 +00001451** Next(csr) // if EOF goto flush_partition_done
dan31f56392018-05-24 21:10:57 +00001452** if( (regStart--)<=0 ){
drh8f26da62018-07-05 21:22:57 +00001453** AggInverse (csrStart)
dan31f56392018-05-24 21:10:57 +00001454** Next(csrStart)
dan99652dd2018-05-24 17:49:14 +00001455** }
1456** }
dan99652dd2018-05-24 17:49:14 +00001457**
dan09590aa2018-05-25 20:30:17 +00001458** For the "CURRENT ROW AND UNBOUNDED FOLLOWING" case, the final if()
1459** condition is always true (as if regStart were initialized to 0).
dan99652dd2018-05-24 17:49:14 +00001460**
dan09590aa2018-05-25 20:30:17 +00001461** RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
1462**
1463** This is the only RANGE case handled by this routine. It modifies the
1464** second while( 1 ) loop in "ROWS BETWEEN CURRENT ... UNBOUNDED..." to
1465** be:
1466**
1467** while( 1 ){
1468** AggFinal (xValue)
1469** while( 1 ){
1470** regPeer++
1471** Gosub addrGosub
1472** Next(csr) // if EOF goto flush_partition_done
1473** if( new peer ) break;
1474** }
1475** while( (regPeer--)>0 ){
drh8f26da62018-07-05 21:22:57 +00001476** AggInverse (csrStart)
dan09590aa2018-05-25 20:30:17 +00001477** Next(csrStart)
1478** }
1479** }
dan99652dd2018-05-24 17:49:14 +00001480**
dan31f56392018-05-24 21:10:57 +00001481** ROWS BETWEEN <expr> FOLLOWING AND <expr> FOLLOWING
1482**
1483** regEnd = regEnd - regStart
1484** Rewind (csr,csrStart,csrEnd) // if EOF goto flush_partition_done
1485** Aggstep (csrEnd)
1486** Next(csrEnd) // if EOF fall-through
1487** if( (regEnd--)<=0 ){
dan31f56392018-05-24 21:10:57 +00001488** if( (regStart--)<=0 ){
1489** AggFinal (xValue)
1490** Gosub addrGosub
1491** Next(csr) // if EOF goto flush_partition_done
1492** }
drh8f26da62018-07-05 21:22:57 +00001493** AggInverse (csrStart)
dane105dd72018-05-25 09:29:11 +00001494** Next (csrStart)
dan31f56392018-05-24 21:10:57 +00001495** }
1496**
1497** ROWS BETWEEN <expr> PRECEDING AND <expr> PRECEDING
1498**
1499** Replace the bit after "Rewind" in the above with:
1500**
1501** if( (regEnd--)<=0 ){
1502** AggStep (csrEnd)
1503** Next (csrEnd)
1504** }
1505** AggFinal (xValue)
1506** Gosub addrGosub
1507** Next(csr) // if EOF goto flush_partition_done
1508** if( (regStart--)<=0 ){
drh8f26da62018-07-05 21:22:57 +00001509** AggInverse (csr2)
dan31f56392018-05-24 21:10:57 +00001510** Next (csr2)
1511** }
1512**
dan99652dd2018-05-24 17:49:14 +00001513*/
danc3a20c12018-05-23 20:55:37 +00001514static void windowCodeRowExprStep(
1515 Parse *pParse,
1516 Select *p,
1517 WhereInfo *pWInfo,
1518 int regGosub,
1519 int addrGosub
1520){
1521 Window *pMWin = p->pWin;
1522 Vdbe *v = sqlite3GetVdbe(pParse);
danc3a20c12018-05-23 20:55:37 +00001523 int regFlushPart; /* Register for "Gosub flush_partition" */
dan31f56392018-05-24 21:10:57 +00001524 int lblFlushPart; /* Label for "Gosub flush_partition" */
1525 int lblFlushDone; /* Label for "Gosub flush_partition_done" */
danc3a20c12018-05-23 20:55:37 +00001526
danf690b572018-06-01 21:00:08 +00001527 int regArg;
danc3a20c12018-05-23 20:55:37 +00001528 int addr;
dan31f56392018-05-24 21:10:57 +00001529 int csrStart = pParse->nTab++;
1530 int csrEnd = pParse->nTab++;
1531 int regStart; /* Value of <expr> PRECEDING */
1532 int regEnd; /* Value of <expr> FOLLOWING */
danc3a20c12018-05-23 20:55:37 +00001533 int addrGoto;
dan31f56392018-05-24 21:10:57 +00001534 int addrTop;
danc3a20c12018-05-23 20:55:37 +00001535 int addrIfPos1;
1536 int addrIfPos2;
dandfa552f2018-06-02 21:04:28 +00001537 int regSize = 0;
dan09590aa2018-05-25 20:30:17 +00001538
dan99652dd2018-05-24 17:49:14 +00001539 assert( pMWin->eStart==TK_PRECEDING
1540 || pMWin->eStart==TK_CURRENT
dane105dd72018-05-25 09:29:11 +00001541 || pMWin->eStart==TK_FOLLOWING
dan99652dd2018-05-24 17:49:14 +00001542 || pMWin->eStart==TK_UNBOUNDED
1543 );
1544 assert( pMWin->eEnd==TK_FOLLOWING
1545 || pMWin->eEnd==TK_CURRENT
1546 || pMWin->eEnd==TK_UNBOUNDED
dan31f56392018-05-24 21:10:57 +00001547 || pMWin->eEnd==TK_PRECEDING
dan99652dd2018-05-24 17:49:14 +00001548 );
1549
danc3a20c12018-05-23 20:55:37 +00001550 /* Allocate register and label for the "flush_partition" sub-routine. */
1551 regFlushPart = ++pParse->nMem;
dan31f56392018-05-24 21:10:57 +00001552 lblFlushPart = sqlite3VdbeMakeLabel(v);
1553 lblFlushDone = sqlite3VdbeMakeLabel(v);
danc3a20c12018-05-23 20:55:37 +00001554
dan31f56392018-05-24 21:10:57 +00001555 regStart = ++pParse->nMem;
1556 regEnd = ++pParse->nMem;
danc3a20c12018-05-23 20:55:37 +00001557
dandfa552f2018-06-02 21:04:28 +00001558 windowPartitionCache(pParse, p, pWInfo, regFlushPart, lblFlushPart, &regSize);
danc3a20c12018-05-23 20:55:37 +00001559
danc3a20c12018-05-23 20:55:37 +00001560 addrGoto = sqlite3VdbeAddOp0(v, OP_Goto);
1561
danc9a86682018-05-30 20:44:58 +00001562 /* Start of "flush_partition" */
dan31f56392018-05-24 21:10:57 +00001563 sqlite3VdbeResolveLabel(v, lblFlushPart);
danc3a20c12018-05-23 20:55:37 +00001564 sqlite3VdbeAddOp2(v, OP_Once, 0, sqlite3VdbeCurrentAddr(v)+3);
dan01e12292018-06-27 20:24:59 +00001565 VdbeCoverage(v);
dan31f56392018-05-24 21:10:57 +00001566 sqlite3VdbeAddOp2(v, OP_OpenDup, csrStart, pMWin->iEphCsr);
1567 sqlite3VdbeAddOp2(v, OP_OpenDup, csrEnd, pMWin->iEphCsr);
danc3a20c12018-05-23 20:55:37 +00001568
dan31f56392018-05-24 21:10:57 +00001569 /* If either regStart or regEnd are not non-negative integers, throw
dan99652dd2018-05-24 17:49:14 +00001570 ** an exception. */
1571 if( pMWin->pStart ){
dan31f56392018-05-24 21:10:57 +00001572 sqlite3ExprCode(pParse, pMWin->pStart, regStart);
drhe4984a22018-07-06 17:19:20 +00001573 windowCheckFrameOffset(pParse, regStart, 0);
dan99652dd2018-05-24 17:49:14 +00001574 }
1575 if( pMWin->pEnd ){
dan31f56392018-05-24 21:10:57 +00001576 sqlite3ExprCode(pParse, pMWin->pEnd, regEnd);
drhe4984a22018-07-06 17:19:20 +00001577 windowCheckFrameOffset(pParse, regEnd, 1);
dan99652dd2018-05-24 17:49:14 +00001578 }
danc3a20c12018-05-23 20:55:37 +00001579
danc9a86682018-05-30 20:44:58 +00001580 /* If this is "ROWS <expr1> FOLLOWING AND ROWS <expr2> FOLLOWING", do:
1581 **
dan26522d12018-06-11 18:16:51 +00001582 ** if( regEnd<regStart ){
1583 ** // The frame always consists of 0 rows
1584 ** regStart = regSize;
1585 ** }
danc9a86682018-05-30 20:44:58 +00001586 ** regEnd = regEnd - regStart;
1587 */
1588 if( pMWin->pEnd && pMWin->pStart && pMWin->eStart==TK_FOLLOWING ){
1589 assert( pMWin->eEnd==TK_FOLLOWING );
dan26522d12018-06-11 18:16:51 +00001590 sqlite3VdbeAddOp3(v, OP_Ge, regStart, sqlite3VdbeCurrentAddr(v)+2, regEnd);
dan01e12292018-06-27 20:24:59 +00001591 VdbeCoverage(v);
dan26522d12018-06-11 18:16:51 +00001592 sqlite3VdbeAddOp2(v, OP_Copy, regSize, regStart);
danc9a86682018-05-30 20:44:58 +00001593 sqlite3VdbeAddOp3(v, OP_Subtract, regStart, regEnd, regEnd);
1594 }
1595
dan26522d12018-06-11 18:16:51 +00001596 if( pMWin->pEnd && pMWin->pStart && pMWin->eEnd==TK_PRECEDING ){
1597 assert( pMWin->eStart==TK_PRECEDING );
1598 sqlite3VdbeAddOp3(v, OP_Le, regStart, sqlite3VdbeCurrentAddr(v)+3, regEnd);
dan01e12292018-06-27 20:24:59 +00001599 VdbeCoverage(v);
dan26522d12018-06-11 18:16:51 +00001600 sqlite3VdbeAddOp2(v, OP_Copy, regSize, regStart);
1601 sqlite3VdbeAddOp2(v, OP_Copy, regSize, regEnd);
1602 }
1603
danc9a86682018-05-30 20:44:58 +00001604 /* Initialize the accumulator register for each window function to NULL */
dan2e605682018-06-07 15:54:26 +00001605 regArg = windowInitAccum(pParse, pMWin);
danc3a20c12018-05-23 20:55:37 +00001606
dan31f56392018-05-24 21:10:57 +00001607 sqlite3VdbeAddOp2(v, OP_Rewind, pMWin->iEphCsr, lblFlushDone);
dan01e12292018-06-27 20:24:59 +00001608 VdbeCoverage(v);
dan31f56392018-05-24 21:10:57 +00001609 sqlite3VdbeAddOp2(v, OP_Rewind, csrStart, lblFlushDone);
dan01e12292018-06-27 20:24:59 +00001610 VdbeCoverageNeverTaken(v);
danc3a20c12018-05-23 20:55:37 +00001611 sqlite3VdbeChangeP5(v, 1);
dan31f56392018-05-24 21:10:57 +00001612 sqlite3VdbeAddOp2(v, OP_Rewind, csrEnd, lblFlushDone);
dan01e12292018-06-27 20:24:59 +00001613 VdbeCoverageNeverTaken(v);
danc3a20c12018-05-23 20:55:37 +00001614 sqlite3VdbeChangeP5(v, 1);
1615
1616 /* Invoke AggStep function for each window function using the row that
dan31f56392018-05-24 21:10:57 +00001617 ** csrEnd currently points to. Or, if csrEnd is already at EOF,
danc3a20c12018-05-23 20:55:37 +00001618 ** do nothing. */
dan31f56392018-05-24 21:10:57 +00001619 addrTop = sqlite3VdbeCurrentAddr(v);
1620 if( pMWin->eEnd==TK_PRECEDING ){
1621 addrIfPos1 = sqlite3VdbeAddOp3(v, OP_IfPos, regEnd, 0 , 1);
dan01e12292018-06-27 20:24:59 +00001622 VdbeCoverage(v);
danc3a20c12018-05-23 20:55:37 +00001623 }
dan31f56392018-05-24 21:10:57 +00001624 sqlite3VdbeAddOp2(v, OP_Next, csrEnd, sqlite3VdbeCurrentAddr(v)+2);
dan01e12292018-06-27 20:24:59 +00001625 VdbeCoverage(v);
dan31f56392018-05-24 21:10:57 +00001626 addr = sqlite3VdbeAddOp0(v, OP_Goto);
dandfa552f2018-06-02 21:04:28 +00001627 windowAggStep(pParse, pMWin, csrEnd, 0, regArg, regSize);
dan99652dd2018-05-24 17:49:14 +00001628 if( pMWin->eEnd==TK_UNBOUNDED ){
dan31f56392018-05-24 21:10:57 +00001629 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
1630 sqlite3VdbeJumpHere(v, addr);
1631 addrTop = sqlite3VdbeCurrentAddr(v);
dan99652dd2018-05-24 17:49:14 +00001632 }else{
dan31f56392018-05-24 21:10:57 +00001633 sqlite3VdbeJumpHere(v, addr);
1634 if( pMWin->eEnd==TK_PRECEDING ){
1635 sqlite3VdbeJumpHere(v, addrIfPos1);
1636 }
dan99652dd2018-05-24 17:49:14 +00001637 }
danc3a20c12018-05-23 20:55:37 +00001638
dan99652dd2018-05-24 17:49:14 +00001639 if( pMWin->eEnd==TK_FOLLOWING ){
dan31f56392018-05-24 21:10:57 +00001640 addrIfPos1 = sqlite3VdbeAddOp3(v, OP_IfPos, regEnd, 0 , 1);
dan01e12292018-06-27 20:24:59 +00001641 VdbeCoverage(v);
dan99652dd2018-05-24 17:49:14 +00001642 }
dane105dd72018-05-25 09:29:11 +00001643 if( pMWin->eStart==TK_FOLLOWING ){
1644 addrIfPos2 = sqlite3VdbeAddOp3(v, OP_IfPos, regStart, 0 , 1);
dan01e12292018-06-27 20:24:59 +00001645 VdbeCoverage(v);
dane105dd72018-05-25 09:29:11 +00001646 }
dand6f784e2018-05-28 18:30:45 +00001647 windowAggFinal(pParse, pMWin, 0);
danec891fd2018-06-06 20:51:02 +00001648 windowReturnOneRow(pParse, pMWin, regGosub, addrGosub);
danc3a20c12018-05-23 20:55:37 +00001649 sqlite3VdbeAddOp2(v, OP_Next, pMWin->iEphCsr, sqlite3VdbeCurrentAddr(v)+2);
dan01e12292018-06-27 20:24:59 +00001650 VdbeCoverage(v);
dan31f56392018-05-24 21:10:57 +00001651 sqlite3VdbeAddOp2(v, OP_Goto, 0, lblFlushDone);
dane105dd72018-05-25 09:29:11 +00001652 if( pMWin->eStart==TK_FOLLOWING ){
1653 sqlite3VdbeJumpHere(v, addrIfPos2);
1654 }
danc3a20c12018-05-23 20:55:37 +00001655
dane105dd72018-05-25 09:29:11 +00001656 if( pMWin->eStart==TK_CURRENT
1657 || pMWin->eStart==TK_PRECEDING
1658 || pMWin->eStart==TK_FOLLOWING
1659 ){
dan7262ca92018-07-02 12:07:32 +00001660 int lblSkipInverse = sqlite3VdbeMakeLabel(v);;
dan99652dd2018-05-24 17:49:14 +00001661 if( pMWin->eStart==TK_PRECEDING ){
dan7262ca92018-07-02 12:07:32 +00001662 sqlite3VdbeAddOp3(v, OP_IfPos, regStart, lblSkipInverse, 1);
dan01e12292018-06-27 20:24:59 +00001663 VdbeCoverage(v);
dan09590aa2018-05-25 20:30:17 +00001664 }
dan7262ca92018-07-02 12:07:32 +00001665 if( pMWin->eStart==TK_FOLLOWING ){
1666 sqlite3VdbeAddOp2(v, OP_Next, csrStart, sqlite3VdbeCurrentAddr(v)+2);
1667 VdbeCoverage(v);
1668 sqlite3VdbeAddOp2(v, OP_Goto, 0, lblSkipInverse);
1669 }else{
1670 sqlite3VdbeAddOp2(v, OP_Next, csrStart, sqlite3VdbeCurrentAddr(v)+1);
1671 VdbeCoverage(v);
dan99652dd2018-05-24 17:49:14 +00001672 }
dan7262ca92018-07-02 12:07:32 +00001673 windowAggStep(pParse, pMWin, csrStart, 1, regArg, regSize);
1674 sqlite3VdbeResolveLabel(v, lblSkipInverse);
danc3a20c12018-05-23 20:55:37 +00001675 }
dan99652dd2018-05-24 17:49:14 +00001676 if( pMWin->eEnd==TK_FOLLOWING ){
1677 sqlite3VdbeJumpHere(v, addrIfPos1);
1678 }
dan31f56392018-05-24 21:10:57 +00001679 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
danc3a20c12018-05-23 20:55:37 +00001680
1681 /* flush_partition_done: */
dan31f56392018-05-24 21:10:57 +00001682 sqlite3VdbeResolveLabel(v, lblFlushDone);
danc3a20c12018-05-23 20:55:37 +00001683 sqlite3VdbeAddOp1(v, OP_ResetSorter, pMWin->iEphCsr);
1684 sqlite3VdbeAddOp1(v, OP_Return, regFlushPart);
1685
1686 /* Jump to here to skip over flush_partition */
1687 sqlite3VdbeJumpHere(v, addrGoto);
1688}
1689
dan79d45442018-05-26 21:17:29 +00001690/*
dan54a9ab32018-06-14 14:27:05 +00001691** This function does the work of sqlite3WindowCodeStep() for cases that
1692** would normally be handled by windowCodeDefaultStep() when there are
1693** one or more built-in window-functions that require the entire partition
1694** to be cached in a temp table before any rows can be returned. Additionally.
1695** "RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING" is always handled by
1696** this function.
1697**
1698** Pseudo-code corresponding to the VM code generated by this function
1699** for each type of window follows.
1700**
dan79d45442018-05-26 21:17:29 +00001701** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
1702**
danf690b572018-06-01 21:00:08 +00001703** flush_partition:
1704** Once {
1705** OpenDup (iEphCsr -> csrLead)
1706** }
1707** Integer ctr 0
1708** foreach row (csrLead){
1709** if( new peer ){
1710** AggFinal (xValue)
1711** for(i=0; i<ctr; i++){
1712** Gosub addrGosub
1713** Next iEphCsr
1714** }
1715** Integer ctr 0
1716** }
1717** AggStep (csrLead)
1718** Incr ctr
1719** }
1720**
1721** AggFinal (xFinalize)
1722** for(i=0; i<ctr; i++){
1723** Gosub addrGosub
1724** Next iEphCsr
1725** }
1726**
1727** ResetSorter (csr)
1728** Return
1729**
1730** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
dan54a9ab32018-06-14 14:27:05 +00001731**
1732** As above, except that the "if( new peer )" branch is always taken.
1733**
danf690b572018-06-01 21:00:08 +00001734** RANGE BETWEEN CURRENT ROW AND CURRENT ROW
dan54a9ab32018-06-14 14:27:05 +00001735**
1736** As above, except that each of the for() loops becomes:
1737**
1738** for(i=0; i<ctr; i++){
1739** Gosub addrGosub
drh8f26da62018-07-05 21:22:57 +00001740** AggInverse (iEphCsr)
dan54a9ab32018-06-14 14:27:05 +00001741** Next iEphCsr
1742** }
1743**
1744** RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
1745**
1746** flush_partition:
1747** Once {
1748** OpenDup (iEphCsr -> csrLead)
1749** }
1750** foreach row (csrLead) {
1751** AggStep (csrLead)
1752** }
1753** foreach row (iEphCsr) {
1754** Gosub addrGosub
1755** }
1756**
1757** RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
1758**
1759** flush_partition:
1760** Once {
1761** OpenDup (iEphCsr -> csrLead)
1762** }
1763** foreach row (csrLead){
1764** AggStep (csrLead)
1765** }
1766** Rewind (csrLead)
1767** Integer ctr 0
1768** foreach row (csrLead){
1769** if( new peer ){
1770** AggFinal (xValue)
1771** for(i=0; i<ctr; i++){
1772** Gosub addrGosub
drh8f26da62018-07-05 21:22:57 +00001773** AggInverse (iEphCsr)
dan54a9ab32018-06-14 14:27:05 +00001774** Next iEphCsr
1775** }
1776** Integer ctr 0
1777** }
1778** Incr ctr
1779** }
1780**
1781** AggFinal (xFinalize)
1782** for(i=0; i<ctr; i++){
1783** Gosub addrGosub
1784** Next iEphCsr
1785** }
1786**
1787** ResetSorter (csr)
1788** Return
danf690b572018-06-01 21:00:08 +00001789*/
1790static void windowCodeCacheStep(
1791 Parse *pParse,
1792 Select *p,
1793 WhereInfo *pWInfo,
1794 int regGosub,
1795 int addrGosub
1796){
1797 Window *pMWin = p->pWin;
1798 Vdbe *v = sqlite3GetVdbe(pParse);
danf690b572018-06-01 21:00:08 +00001799 int k;
1800 int addr;
1801 ExprList *pPart = pMWin->pPartition;
1802 ExprList *pOrderBy = pMWin->pOrderBy;
dan54a9ab32018-06-14 14:27:05 +00001803 int nPeer = pOrderBy ? pOrderBy->nExpr : 0;
danf690b572018-06-01 21:00:08 +00001804 int regNewPeer;
1805
1806 int addrGoto; /* Address of Goto used to jump flush_par.. */
dan13078ca2018-06-13 20:29:38 +00001807 int addrNext; /* Jump here for next iteration of loop */
danf690b572018-06-01 21:00:08 +00001808 int regFlushPart;
1809 int lblFlushPart;
1810 int csrLead;
1811 int regCtr;
1812 int regArg; /* Register array to martial function args */
dandfa552f2018-06-02 21:04:28 +00001813 int regSize;
dan13078ca2018-06-13 20:29:38 +00001814 int lblEmpty;
dan54a9ab32018-06-14 14:27:05 +00001815 int bReverse = pMWin->pOrderBy && pMWin->eStart==TK_CURRENT
1816 && pMWin->eEnd==TK_UNBOUNDED;
danf690b572018-06-01 21:00:08 +00001817
1818 assert( (pMWin->eStart==TK_UNBOUNDED && pMWin->eEnd==TK_CURRENT)
danec891fd2018-06-06 20:51:02 +00001819 || (pMWin->eStart==TK_UNBOUNDED && pMWin->eEnd==TK_UNBOUNDED)
1820 || (pMWin->eStart==TK_CURRENT && pMWin->eEnd==TK_CURRENT)
dan13078ca2018-06-13 20:29:38 +00001821 || (pMWin->eStart==TK_CURRENT && pMWin->eEnd==TK_UNBOUNDED)
danf690b572018-06-01 21:00:08 +00001822 );
1823
dan13078ca2018-06-13 20:29:38 +00001824 lblEmpty = sqlite3VdbeMakeLabel(v);
danf690b572018-06-01 21:00:08 +00001825 regNewPeer = pParse->nMem+1;
1826 pParse->nMem += nPeer;
1827
1828 /* Allocate register and label for the "flush_partition" sub-routine. */
1829 regFlushPart = ++pParse->nMem;
1830 lblFlushPart = sqlite3VdbeMakeLabel(v);
1831
1832 csrLead = pParse->nTab++;
1833 regCtr = ++pParse->nMem;
1834
dandfa552f2018-06-02 21:04:28 +00001835 windowPartitionCache(pParse, p, pWInfo, regFlushPart, lblFlushPart, &regSize);
danf690b572018-06-01 21:00:08 +00001836 addrGoto = sqlite3VdbeAddOp0(v, OP_Goto);
1837
1838 /* Start of "flush_partition" */
1839 sqlite3VdbeResolveLabel(v, lblFlushPart);
1840 sqlite3VdbeAddOp2(v, OP_Once, 0, sqlite3VdbeCurrentAddr(v)+2);
dan01e12292018-06-27 20:24:59 +00001841 VdbeCoverage(v);
danf690b572018-06-01 21:00:08 +00001842 sqlite3VdbeAddOp2(v, OP_OpenDup, csrLead, pMWin->iEphCsr);
1843
1844 /* Initialize the accumulator register for each window function to NULL */
dan2e605682018-06-07 15:54:26 +00001845 regArg = windowInitAccum(pParse, pMWin);
danf690b572018-06-01 21:00:08 +00001846
1847 sqlite3VdbeAddOp2(v, OP_Integer, 0, regCtr);
dan13078ca2018-06-13 20:29:38 +00001848 sqlite3VdbeAddOp2(v, OP_Rewind, csrLead, lblEmpty);
dan01e12292018-06-27 20:24:59 +00001849 VdbeCoverage(v);
dan13078ca2018-06-13 20:29:38 +00001850 sqlite3VdbeAddOp2(v, OP_Rewind, pMWin->iEphCsr, lblEmpty);
dan01e12292018-06-27 20:24:59 +00001851 VdbeCoverageNeverTaken(v);
danf690b572018-06-01 21:00:08 +00001852
dan13078ca2018-06-13 20:29:38 +00001853 if( bReverse ){
1854 int addr = sqlite3VdbeCurrentAddr(v);
1855 windowAggStep(pParse, pMWin, csrLead, 0, regArg, regSize);
1856 sqlite3VdbeAddOp2(v, OP_Next, csrLead, addr);
dan01e12292018-06-27 20:24:59 +00001857 VdbeCoverage(v);
dan13078ca2018-06-13 20:29:38 +00001858 sqlite3VdbeAddOp2(v, OP_Rewind, csrLead, lblEmpty);
dan01e12292018-06-27 20:24:59 +00001859 VdbeCoverageNeverTaken(v);
dan13078ca2018-06-13 20:29:38 +00001860 }
1861 addrNext = sqlite3VdbeCurrentAddr(v);
1862
1863 if( pOrderBy && (pMWin->eEnd==TK_CURRENT || pMWin->eStart==TK_CURRENT) ){
1864 int bCurrent = (pMWin->eStart==TK_CURRENT);
danec891fd2018-06-06 20:51:02 +00001865 int addrJump = 0; /* Address of OP_Jump below */
1866 if( pMWin->eType==TK_RANGE ){
1867 int iOff = pMWin->nBufferCol + (pPart ? pPart->nExpr : 0);
1868 int regPeer = pMWin->regPart + (pPart ? pPart->nExpr : 0);
1869 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pOrderBy, 0, 0);
1870 for(k=0; k<nPeer; k++){
1871 sqlite3VdbeAddOp3(v, OP_Column, csrLead, iOff+k, regNewPeer+k);
1872 }
1873 addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPeer, regPeer, nPeer);
1874 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
1875 addrJump = sqlite3VdbeAddOp3(v, OP_Jump, addr+2, 0, addr+2);
dan01e12292018-06-27 20:24:59 +00001876 VdbeCoverage(v);
danec891fd2018-06-06 20:51:02 +00001877 sqlite3VdbeAddOp3(v, OP_Copy, regNewPeer, regPeer, nPeer-1);
danf690b572018-06-01 21:00:08 +00001878 }
1879
dan13078ca2018-06-13 20:29:38 +00001880 windowReturnRows(pParse, pMWin, regCtr, regGosub, addrGosub,
danec891fd2018-06-06 20:51:02 +00001881 (bCurrent ? regArg : 0), (bCurrent ? regSize : 0)
1882 );
1883 if( addrJump ) sqlite3VdbeJumpHere(v, addrJump);
danf690b572018-06-01 21:00:08 +00001884 }
1885
dan13078ca2018-06-13 20:29:38 +00001886 if( bReverse==0 ){
1887 windowAggStep(pParse, pMWin, csrLead, 0, regArg, regSize);
1888 }
danf690b572018-06-01 21:00:08 +00001889 sqlite3VdbeAddOp2(v, OP_AddImm, regCtr, 1);
dan13078ca2018-06-13 20:29:38 +00001890 sqlite3VdbeAddOp2(v, OP_Next, csrLead, addrNext);
dan01e12292018-06-27 20:24:59 +00001891 VdbeCoverage(v);
danf690b572018-06-01 21:00:08 +00001892
dan13078ca2018-06-13 20:29:38 +00001893 windowReturnRows(pParse, pMWin, regCtr, regGosub, addrGosub, 0, 0);
danf690b572018-06-01 21:00:08 +00001894
dan13078ca2018-06-13 20:29:38 +00001895 sqlite3VdbeResolveLabel(v, lblEmpty);
danf690b572018-06-01 21:00:08 +00001896 sqlite3VdbeAddOp1(v, OP_ResetSorter, pMWin->iEphCsr);
1897 sqlite3VdbeAddOp1(v, OP_Return, regFlushPart);
1898
1899 /* Jump to here to skip over flush_partition */
1900 sqlite3VdbeJumpHere(v, addrGoto);
1901}
1902
1903
1904/*
1905** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
1906**
dan79d45442018-05-26 21:17:29 +00001907** ...
1908** if( new partition ){
1909** AggFinal (xFinalize)
1910** Gosub addrGosub
1911** ResetSorter eph-table
1912** }
1913** else if( new peer ){
1914** AggFinal (xValue)
1915** Gosub addrGosub
1916** ResetSorter eph-table
1917** }
1918** AggStep
1919** Insert (record into eph-table)
1920** sqlite3WhereEnd()
1921** AggFinal (xFinalize)
1922** Gosub addrGosub
danf690b572018-06-01 21:00:08 +00001923**
1924** RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
1925**
1926** As above, except take no action for a "new peer". Invoke
1927** the sub-routine once only for each partition.
1928**
1929** RANGE BETWEEN CURRENT ROW AND CURRENT ROW
1930**
1931** As above, except that the "new peer" condition is handled in the
1932** same way as "new partition" (so there is no "else if" block).
1933**
1934** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
1935**
1936** As above, except assume every row is a "new peer".
dan79d45442018-05-26 21:17:29 +00001937*/
danc3a20c12018-05-23 20:55:37 +00001938static void windowCodeDefaultStep(
1939 Parse *pParse,
1940 Select *p,
1941 WhereInfo *pWInfo,
1942 int regGosub,
1943 int addrGosub
1944){
1945 Window *pMWin = p->pWin;
1946 Vdbe *v = sqlite3GetVdbe(pParse);
danc3a20c12018-05-23 20:55:37 +00001947 int k;
1948 int iSubCsr = p->pSrc->a[0].iCursor;
1949 int nSub = p->pSrc->a[0].pTab->nCol;
1950 int reg = pParse->nMem+1;
1951 int regRecord = reg+nSub;
1952 int regRowid = regRecord+1;
1953 int addr;
dand6f784e2018-05-28 18:30:45 +00001954 ExprList *pPart = pMWin->pPartition;
1955 ExprList *pOrderBy = pMWin->pOrderBy;
danc3a20c12018-05-23 20:55:37 +00001956
dan79d45442018-05-26 21:17:29 +00001957 assert( pMWin->eType==TK_RANGE
1958 || (pMWin->eStart==TK_UNBOUNDED && pMWin->eEnd==TK_CURRENT)
1959 );
1960
dand6f784e2018-05-28 18:30:45 +00001961 assert( (pMWin->eStart==TK_UNBOUNDED && pMWin->eEnd==TK_CURRENT)
1962 || (pMWin->eStart==TK_UNBOUNDED && pMWin->eEnd==TK_UNBOUNDED)
1963 || (pMWin->eStart==TK_CURRENT && pMWin->eEnd==TK_CURRENT)
1964 || (pMWin->eStart==TK_CURRENT && pMWin->eEnd==TK_UNBOUNDED && !pOrderBy)
1965 );
1966
1967 if( pMWin->eEnd==TK_UNBOUNDED ){
1968 pOrderBy = 0;
1969 }
1970
danc3a20c12018-05-23 20:55:37 +00001971 pParse->nMem += nSub + 2;
1972
1973 /* Martial the row returned by the sub-select into an array of
1974 ** registers. */
1975 for(k=0; k<nSub; k++){
1976 sqlite3VdbeAddOp3(v, OP_Column, iSubCsr, k, reg+k);
1977 }
1978
1979 /* Check if this is the start of a new partition or peer group. */
dand6f784e2018-05-28 18:30:45 +00001980 if( pPart || pOrderBy ){
danc3a20c12018-05-23 20:55:37 +00001981 int nPart = (pPart ? pPart->nExpr : 0);
danc3a20c12018-05-23 20:55:37 +00001982 int addrGoto = 0;
1983 int addrJump = 0;
dand6f784e2018-05-28 18:30:45 +00001984 int nPeer = (pOrderBy ? pOrderBy->nExpr : 0);
danc3a20c12018-05-23 20:55:37 +00001985
1986 if( pPart ){
1987 int regNewPart = reg + pMWin->nBufferCol;
1988 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pPart, 0, 0);
1989 addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPart, pMWin->regPart,nPart);
1990 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
1991 addrJump = sqlite3VdbeAddOp3(v, OP_Jump, addr+2, 0, addr+2);
dan01e12292018-06-27 20:24:59 +00001992 VdbeCoverage(v);
dand6f784e2018-05-28 18:30:45 +00001993 windowAggFinal(pParse, pMWin, 1);
danc3a20c12018-05-23 20:55:37 +00001994 if( pOrderBy ){
1995 addrGoto = sqlite3VdbeAddOp0(v, OP_Goto);
1996 }
1997 }
1998
1999 if( pOrderBy ){
2000 int regNewPeer = reg + pMWin->nBufferCol + nPart;
2001 int regPeer = pMWin->regPart + nPart;
2002
danc3a20c12018-05-23 20:55:37 +00002003 if( addrJump ) sqlite3VdbeJumpHere(v, addrJump);
dan79d45442018-05-26 21:17:29 +00002004 if( pMWin->eType==TK_RANGE ){
2005 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pOrderBy, 0, 0);
2006 addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPeer, regPeer, nPeer);
2007 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
2008 addrJump = sqlite3VdbeAddOp3(v, OP_Jump, addr+2, 0, addr+2);
dan01e12292018-06-27 20:24:59 +00002009 VdbeCoverage(v);
dan79d45442018-05-26 21:17:29 +00002010 }else{
2011 addrJump = 0;
2012 }
dand6f784e2018-05-28 18:30:45 +00002013 windowAggFinal(pParse, pMWin, pMWin->eStart==TK_CURRENT);
danc3a20c12018-05-23 20:55:37 +00002014 if( addrGoto ) sqlite3VdbeJumpHere(v, addrGoto);
2015 }
2016
dandacf1de2018-06-08 16:11:55 +00002017 sqlite3VdbeAddOp2(v, OP_Rewind, pMWin->iEphCsr,sqlite3VdbeCurrentAddr(v)+3);
dan01e12292018-06-27 20:24:59 +00002018 VdbeCoverage(v);
danc3a20c12018-05-23 20:55:37 +00002019 sqlite3VdbeAddOp2(v, OP_Gosub, regGosub, addrGosub);
dandacf1de2018-06-08 16:11:55 +00002020 sqlite3VdbeAddOp2(v, OP_Next, pMWin->iEphCsr, sqlite3VdbeCurrentAddr(v)-1);
dan01e12292018-06-27 20:24:59 +00002021 VdbeCoverage(v);
dandacf1de2018-06-08 16:11:55 +00002022
danc3a20c12018-05-23 20:55:37 +00002023 sqlite3VdbeAddOp1(v, OP_ResetSorter, pMWin->iEphCsr);
2024 sqlite3VdbeAddOp3(
2025 v, OP_Copy, reg+pMWin->nBufferCol, pMWin->regPart, nPart+nPeer-1
2026 );
2027
dan79d45442018-05-26 21:17:29 +00002028 if( addrJump ) sqlite3VdbeJumpHere(v, addrJump);
danc3a20c12018-05-23 20:55:37 +00002029 }
2030
2031 /* Invoke step function for window functions */
dandfa552f2018-06-02 21:04:28 +00002032 windowAggStep(pParse, pMWin, -1, 0, reg, 0);
danc3a20c12018-05-23 20:55:37 +00002033
2034 /* Buffer the current row in the ephemeral table. */
2035 if( pMWin->nBufferCol>0 ){
2036 sqlite3VdbeAddOp3(v, OP_MakeRecord, reg, pMWin->nBufferCol, regRecord);
2037 }else{
2038 sqlite3VdbeAddOp2(v, OP_Blob, 0, regRecord);
2039 sqlite3VdbeAppendP4(v, (void*)"", 0);
2040 }
2041 sqlite3VdbeAddOp2(v, OP_NewRowid, pMWin->iEphCsr, regRowid);
2042 sqlite3VdbeAddOp3(v, OP_Insert, pMWin->iEphCsr, regRecord, regRowid);
2043
2044 /* End the database scan loop. */
2045 sqlite3WhereEnd(pWInfo);
2046
dand6f784e2018-05-28 18:30:45 +00002047 windowAggFinal(pParse, pMWin, 1);
dandacf1de2018-06-08 16:11:55 +00002048 sqlite3VdbeAddOp2(v, OP_Rewind, pMWin->iEphCsr,sqlite3VdbeCurrentAddr(v)+3);
dan01e12292018-06-27 20:24:59 +00002049 VdbeCoverage(v);
danc3a20c12018-05-23 20:55:37 +00002050 sqlite3VdbeAddOp2(v, OP_Gosub, regGosub, addrGosub);
dandacf1de2018-06-08 16:11:55 +00002051 sqlite3VdbeAddOp2(v, OP_Next, pMWin->iEphCsr, sqlite3VdbeCurrentAddr(v)-1);
dan01e12292018-06-27 20:24:59 +00002052 VdbeCoverage(v);
danc3a20c12018-05-23 20:55:37 +00002053}
2054
dan13078ca2018-06-13 20:29:38 +00002055/*
2056** Allocate and return a duplicate of the Window object indicated by the
2057** third argument. Set the Window.pOwner field of the new object to
2058** pOwner.
2059*/
dan2a11bb22018-06-11 20:50:25 +00002060Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p){
dandacf1de2018-06-08 16:11:55 +00002061 Window *pNew = 0;
2062 if( p ){
2063 pNew = sqlite3DbMallocZero(db, sizeof(Window));
2064 if( pNew ){
danc95f38d2018-06-18 20:34:43 +00002065 pNew->zName = sqlite3DbStrDup(db, p->zName);
dandacf1de2018-06-08 16:11:55 +00002066 pNew->pFilter = sqlite3ExprDup(db, p->pFilter, 0);
2067 pNew->pPartition = sqlite3ExprListDup(db, p->pPartition, 0);
2068 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, 0);
2069 pNew->eType = p->eType;
2070 pNew->eEnd = p->eEnd;
2071 pNew->eStart = p->eStart;
dan303451a2018-06-14 20:52:08 +00002072 pNew->pStart = sqlite3ExprDup(db, p->pStart, 0);
2073 pNew->pEnd = sqlite3ExprDup(db, p->pEnd, 0);
dan2a11bb22018-06-11 20:50:25 +00002074 pNew->pOwner = pOwner;
dandacf1de2018-06-08 16:11:55 +00002075 }
2076 }
2077 return pNew;
2078}
danc3a20c12018-05-23 20:55:37 +00002079
danf9eae182018-05-21 19:45:11 +00002080/*
danc95f38d2018-06-18 20:34:43 +00002081** Return a copy of the linked list of Window objects passed as the
2082** second argument.
2083*/
2084Window *sqlite3WindowListDup(sqlite3 *db, Window *p){
2085 Window *pWin;
2086 Window *pRet = 0;
2087 Window **pp = &pRet;
2088
2089 for(pWin=p; pWin; pWin=pWin->pNextWin){
2090 *pp = sqlite3WindowDup(db, 0, pWin);
2091 if( *pp==0 ) break;
2092 pp = &((*pp)->pNextWin);
2093 }
2094
2095 return pRet;
2096}
2097
2098/*
dan2a11bb22018-06-11 20:50:25 +00002099** sqlite3WhereBegin() has already been called for the SELECT statement
2100** passed as the second argument when this function is invoked. It generates
2101** code to populate the Window.regResult register for each window function and
2102** invoke the sub-routine at instruction addrGosub once for each row.
2103** This function calls sqlite3WhereEnd() before returning.
danf9eae182018-05-21 19:45:11 +00002104*/
2105void sqlite3WindowCodeStep(
dan2a11bb22018-06-11 20:50:25 +00002106 Parse *pParse, /* Parse context */
2107 Select *p, /* Rewritten SELECT statement */
2108 WhereInfo *pWInfo, /* Context returned by sqlite3WhereBegin() */
2109 int regGosub, /* Register for OP_Gosub */
2110 int addrGosub /* OP_Gosub here to return each row */
danf9eae182018-05-21 19:45:11 +00002111){
danf9eae182018-05-21 19:45:11 +00002112 Window *pMWin = p->pWin;
danf9eae182018-05-21 19:45:11 +00002113
dan54a9ab32018-06-14 14:27:05 +00002114 /* There are three different functions that may be used to do the work
2115 ** of this one, depending on the window frame and the specific built-in
2116 ** window functions used (if any).
2117 **
2118 ** windowCodeRowExprStep() handles all "ROWS" window frames, except for:
dan26522d12018-06-11 18:16:51 +00002119 **
dan13078ca2018-06-13 20:29:38 +00002120 ** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
dan54a9ab32018-06-14 14:27:05 +00002121 **
2122 ** The exception is because windowCodeRowExprStep() implements all window
2123 ** frame types by caching the entire partition in a temp table, and
2124 ** "ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW" is easy enough to
2125 ** implement without such a cache.
2126 **
2127 ** windowCodeCacheStep() is used for:
2128 **
2129 ** RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
2130 **
2131 ** It is also used for anything not handled by windowCodeRowExprStep()
2132 ** that invokes a built-in window function that requires the entire
2133 ** partition to be cached in a temp table before any rows are returned
2134 ** (e.g. nth_value() or percent_rank()).
2135 **
2136 ** Finally, assuming there is no built-in window function that requires
2137 ** the partition to be cached, windowCodeDefaultStep() is used for:
2138 **
2139 ** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
2140 ** RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
2141 ** RANGE BETWEEN CURRENT ROW AND CURRENT ROW
2142 ** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
2143 **
2144 ** windowCodeDefaultStep() is the only one of the three functions that
2145 ** does not cache each partition in a temp table before beginning to
2146 ** return rows.
dan26522d12018-06-11 18:16:51 +00002147 */
dan54a9ab32018-06-14 14:27:05 +00002148 if( pMWin->eType==TK_ROWS
2149 && (pMWin->eStart!=TK_UNBOUNDED||pMWin->eEnd!=TK_CURRENT||!pMWin->pOrderBy)
dan09590aa2018-05-25 20:30:17 +00002150 ){
danc3a20c12018-05-23 20:55:37 +00002151 windowCodeRowExprStep(pParse, p, pWInfo, regGosub, addrGosub);
dan13078ca2018-06-13 20:29:38 +00002152 }else{
2153 Window *pWin;
dan54a9ab32018-06-14 14:27:05 +00002154 int bCache = 0; /* True to use CacheStep() */
danf9eae182018-05-21 19:45:11 +00002155
dan54a9ab32018-06-14 14:27:05 +00002156 if( pMWin->eStart==TK_CURRENT && pMWin->eEnd==TK_UNBOUNDED ){
dan13078ca2018-06-13 20:29:38 +00002157 bCache = 1;
2158 }else{
dan13078ca2018-06-13 20:29:38 +00002159 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
2160 FuncDef *pFunc = pWin->pFunc;
2161 if( (pFunc->funcFlags & SQLITE_FUNC_WINDOW_SIZE)
dan54a9ab32018-06-14 14:27:05 +00002162 || (pFunc->xSFunc==nth_valueStepFunc)
2163 || (pFunc->xSFunc==first_valueStepFunc)
2164 || (pFunc->xSFunc==leadStepFunc)
2165 || (pFunc->xSFunc==lagStepFunc)
2166 ){
dan13078ca2018-06-13 20:29:38 +00002167 bCache = 1;
2168 break;
2169 }
2170 }
2171 }
2172
2173 /* Otherwise, call windowCodeDefaultStep(). */
2174 if( bCache ){
dandfa552f2018-06-02 21:04:28 +00002175 windowCodeCacheStep(pParse, p, pWInfo, regGosub, addrGosub);
dan13078ca2018-06-13 20:29:38 +00002176 }else{
2177 windowCodeDefaultStep(pParse, p, pWInfo, regGosub, addrGosub);
dandfa552f2018-06-02 21:04:28 +00002178 }
danf690b572018-06-01 21:00:08 +00002179 }
danf9eae182018-05-21 19:45:11 +00002180}
2181
dan67a9b8e2018-06-22 20:51:35 +00002182#endif /* SQLITE_OMIT_WINDOWFUNC */