blob: b31ed156d7c3d3bd91c913c929c246defe206aad [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
dan9c277582018-06-20 09:23:49 +0000258 assert( sqlite3VdbeAssertAggContext(pCtx) );
dandfa552f2018-06-02 21:04:28 +0000259 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
dan9c277582018-06-20 09:23:49 +0000260 if( ALWAYS(p) ){
dandfa552f2018-06-02 21:04:28 +0000261 if( p->nTotal==0 ){
262 p->nTotal = sqlite3_value_int64(apArg[0]);
263 }
264 p->nStep++;
265 if( p->nValue==0 ){
266 p->nValue = p->nStep;
267 }
268 }
269}
dan2a11bb22018-06-11 20:50:25 +0000270static void percent_rankInvFunc(
dandfa552f2018-06-02 21:04:28 +0000271 sqlite3_context *pCtx,
272 int nArg,
273 sqlite3_value **apArg
274){
275}
276static void percent_rankValueFunc(sqlite3_context *pCtx){
277 struct CallCount *p;
278 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
279 if( p ){
280 if( p->nTotal>1 ){
281 double r = (double)(p->nValue-1) / (double)(p->nTotal-1);
282 sqlite3_result_double(pCtx, r);
283 }else{
danb7306f62018-06-21 19:20:39 +0000284 sqlite3_result_double(pCtx, 0.0);
dandfa552f2018-06-02 21:04:28 +0000285 }
286 p->nValue = 0;
287 }
288}
289
dan9c277582018-06-20 09:23:49 +0000290/*
291** Implementation of built-in window function cume_dist(). Assumes that
292** the window frame has been set to:
293**
294** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
295*/
danf1abe362018-06-04 08:22:09 +0000296static void cume_distStepFunc(
297 sqlite3_context *pCtx,
298 int nArg,
299 sqlite3_value **apArg
300){
301 struct CallCount *p;
302 assert( nArg==1 );
303
dan9c277582018-06-20 09:23:49 +0000304 assert( sqlite3VdbeAssertAggContext(pCtx) );
danf1abe362018-06-04 08:22:09 +0000305 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
dan9c277582018-06-20 09:23:49 +0000306 if( ALWAYS(p) ){
danf1abe362018-06-04 08:22:09 +0000307 if( p->nTotal==0 ){
308 p->nTotal = sqlite3_value_int64(apArg[0]);
309 }
310 p->nStep++;
311 }
312}
dan2a11bb22018-06-11 20:50:25 +0000313static void cume_distInvFunc(
danf1abe362018-06-04 08:22:09 +0000314 sqlite3_context *pCtx,
315 int nArg,
316 sqlite3_value **apArg
317){
318}
319static void cume_distValueFunc(sqlite3_context *pCtx){
320 struct CallCount *p;
321 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
dan660af932018-06-18 16:55:22 +0000322 if( p && p->nTotal ){
danf1abe362018-06-04 08:22:09 +0000323 double r = (double)(p->nStep) / (double)(p->nTotal);
324 sqlite3_result_double(pCtx, r);
325 }
326}
327
dan2a11bb22018-06-11 20:50:25 +0000328/*
329** Context object for ntile() window function.
330*/
dan6bc5c9e2018-06-04 18:55:11 +0000331struct NtileCtx {
332 i64 nTotal; /* Total rows in partition */
333 i64 nParam; /* Parameter passed to ntile(N) */
334 i64 iRow; /* Current row */
335};
336
337/*
338** Implementation of ntile(). This assumes that the window frame has
339** been coerced to:
340**
341** ROWS UNBOUNDED PRECEDING AND CURRENT ROW
dan6bc5c9e2018-06-04 18:55:11 +0000342*/
343static void ntileStepFunc(
344 sqlite3_context *pCtx,
345 int nArg,
346 sqlite3_value **apArg
347){
348 struct NtileCtx *p;
349 assert( nArg==2 );
350 p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
dan17074e32018-06-22 17:57:10 +0000351 if( p ){
dan6bc5c9e2018-06-04 18:55:11 +0000352 if( p->nTotal==0 ){
353 p->nParam = sqlite3_value_int64(apArg[0]);
354 p->nTotal = sqlite3_value_int64(apArg[1]);
355 if( p->nParam<=0 ){
356 sqlite3_result_error(
357 pCtx, "argument of ntile must be a positive integer", -1
358 );
359 }
360 }
361 p->iRow++;
362 }
363}
dan2a11bb22018-06-11 20:50:25 +0000364static void ntileInvFunc(
dan6bc5c9e2018-06-04 18:55:11 +0000365 sqlite3_context *pCtx,
366 int nArg,
367 sqlite3_value **apArg
368){
369}
370static void ntileValueFunc(sqlite3_context *pCtx){
371 struct NtileCtx *p;
372 p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
373 if( p && p->nParam>0 ){
374 int nSize = (p->nTotal / p->nParam);
375 if( nSize==0 ){
376 sqlite3_result_int64(pCtx, p->iRow);
377 }else{
378 i64 nLarge = p->nTotal - p->nParam*nSize;
379 i64 iSmall = nLarge*(nSize+1);
380 i64 iRow = p->iRow-1;
381
382 assert( (nLarge*(nSize+1) + (p->nParam-nLarge)*nSize)==p->nTotal );
383
384 if( iRow<iSmall ){
385 sqlite3_result_int64(pCtx, 1 + iRow/(nSize+1));
386 }else{
387 sqlite3_result_int64(pCtx, 1 + nLarge + (iRow-iSmall)/nSize);
388 }
389 }
390 }
391}
392
dan2a11bb22018-06-11 20:50:25 +0000393/*
394** Context object for last_value() window function.
395*/
dan1c5ed622018-06-05 16:16:17 +0000396struct LastValueCtx {
397 sqlite3_value *pVal;
398 int nVal;
399};
400
401/*
402** Implementation of last_value().
403*/
404static void last_valueStepFunc(
405 sqlite3_context *pCtx,
406 int nArg,
407 sqlite3_value **apArg
408){
409 struct LastValueCtx *p;
dan9c277582018-06-20 09:23:49 +0000410 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
dan1c5ed622018-06-05 16:16:17 +0000411 if( p ){
412 sqlite3_value_free(p->pVal);
413 p->pVal = sqlite3_value_dup(apArg[0]);
dan6fde1792018-06-15 19:01:35 +0000414 if( p->pVal==0 ){
415 sqlite3_result_error_nomem(pCtx);
416 }else{
417 p->nVal++;
418 }
dan1c5ed622018-06-05 16:16:17 +0000419 }
420}
dan2a11bb22018-06-11 20:50:25 +0000421static void last_valueInvFunc(
dan1c5ed622018-06-05 16:16:17 +0000422 sqlite3_context *pCtx,
423 int nArg,
424 sqlite3_value **apArg
425){
426 struct LastValueCtx *p;
dan9c277582018-06-20 09:23:49 +0000427 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
428 if( ALWAYS(p) ){
dan1c5ed622018-06-05 16:16:17 +0000429 p->nVal--;
430 if( p->nVal==0 ){
431 sqlite3_value_free(p->pVal);
432 p->pVal = 0;
433 }
434 }
435}
436static void last_valueValueFunc(sqlite3_context *pCtx){
437 struct LastValueCtx *p;
dan9c277582018-06-20 09:23:49 +0000438 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
dan1c5ed622018-06-05 16:16:17 +0000439 if( p && p->pVal ){
440 sqlite3_result_value(pCtx, p->pVal);
441 }
442}
443static void last_valueFinalizeFunc(sqlite3_context *pCtx){
444 struct LastValueCtx *p;
dan9c277582018-06-20 09:23:49 +0000445 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
dan1c5ed622018-06-05 16:16:17 +0000446 if( p && p->pVal ){
447 sqlite3_result_value(pCtx, p->pVal);
448 sqlite3_value_free(p->pVal);
449 p->pVal = 0;
450 }
451}
452
dan2a11bb22018-06-11 20:50:25 +0000453/*
454** No-op implementations of nth_value(), first_value(), lead() and lag().
455** These are all implemented inline using VDBE instructions.
456*/
457static void nth_valueStepFunc(sqlite3_context *pCtx, int n, sqlite3_value **a){}
458static void nth_valueInvFunc(sqlite3_context *pCtx, int n, sqlite3_value **ap){}
459static void nth_valueValueFunc(sqlite3_context *pCtx){}
460static void first_valueStepFunc(sqlite3_context *p, int n, sqlite3_value **ap){}
461static void first_valueInvFunc(sqlite3_context *p, int n, sqlite3_value **ap){}
462static void first_valueValueFunc(sqlite3_context *pCtx){}
463static void leadStepFunc(sqlite3_context *pCtx, int n, sqlite3_value **ap){}
464static void leadInvFunc(sqlite3_context *pCtx, int n, sqlite3_value **ap){}
465static void leadValueFunc(sqlite3_context *pCtx){}
466static void lagStepFunc(sqlite3_context *pCtx, int n, sqlite3_value **ap){}
467static void lagInvFunc(sqlite3_context *pCtx, int n, sqlite3_value **ap){}
468static void lagValueFunc(sqlite3_context *pCtx){}
danfe4e25a2018-06-07 20:08:59 +0000469
dandfa552f2018-06-02 21:04:28 +0000470#define WINDOWFUNC(name,nArg,extra) { \
471 nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
472 name ## StepFunc, name ## ValueFunc, name ## ValueFunc, \
dan2a11bb22018-06-11 20:50:25 +0000473 name ## InvFunc, #name \
dandfa552f2018-06-02 21:04:28 +0000474}
475
dan1c5ed622018-06-05 16:16:17 +0000476#define WINDOWFUNCF(name,nArg,extra) { \
477 nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
478 name ## StepFunc, name ## FinalizeFunc, name ## ValueFunc, \
dan2a11bb22018-06-11 20:50:25 +0000479 name ## InvFunc, #name \
dan1c5ed622018-06-05 16:16:17 +0000480}
481
dandfa552f2018-06-02 21:04:28 +0000482/*
483** Register those built-in window functions that are not also aggregates.
484*/
485void sqlite3WindowFunctions(void){
486 static FuncDef aWindowFuncs[] = {
487 WINDOWFUNC(row_number, 0, 0),
488 WINDOWFUNC(dense_rank, 0, 0),
489 WINDOWFUNC(rank, 0, 0),
490 WINDOWFUNC(percent_rank, 0, SQLITE_FUNC_WINDOW_SIZE),
danf1abe362018-06-04 08:22:09 +0000491 WINDOWFUNC(cume_dist, 0, SQLITE_FUNC_WINDOW_SIZE),
dan6bc5c9e2018-06-04 18:55:11 +0000492 WINDOWFUNC(ntile, 1, SQLITE_FUNC_WINDOW_SIZE),
dan1c5ed622018-06-05 16:16:17 +0000493 WINDOWFUNCF(last_value, 1, 0),
dandfa552f2018-06-02 21:04:28 +0000494 WINDOWFUNC(nth_value, 2, 0),
dan7095c002018-06-07 17:45:22 +0000495 WINDOWFUNC(first_value, 1, 0),
danfe4e25a2018-06-07 20:08:59 +0000496 WINDOWFUNC(lead, 1, 0), WINDOWFUNC(lead, 2, 0), WINDOWFUNC(lead, 3, 0),
497 WINDOWFUNC(lag, 1, 0), WINDOWFUNC(lag, 2, 0), WINDOWFUNC(lag, 3, 0),
dandfa552f2018-06-02 21:04:28 +0000498 };
499 sqlite3InsertBuiltinFuncs(aWindowFuncs, ArraySize(aWindowFuncs));
500}
501
danc0bb4452018-06-12 20:53:38 +0000502/*
503** This function is called immediately after resolving the function name
504** for a window function within a SELECT statement. Argument pList is a
505** linked list of WINDOW definitions for the current SELECT statement.
506** Argument pFunc is the function definition just resolved and pWin
507** is the Window object representing the associated OVER clause. This
508** function updates the contents of pWin as follows:
509**
510** * If the OVER clause refered to a named window (as in "max(x) OVER win"),
511** search list pList for a matching WINDOW definition, and update pWin
512** accordingly. If no such WINDOW clause can be found, leave an error
513** in pParse.
514**
515** * If the function is a built-in window function that requires the
516** window to be coerced (see "BUILT-IN WINDOW FUNCTIONS" at the top
517** of this file), pWin is updated here.
518*/
dane3bf6322018-06-08 20:58:27 +0000519void sqlite3WindowUpdate(
520 Parse *pParse,
danc0bb4452018-06-12 20:53:38 +0000521 Window *pList, /* List of named windows for this SELECT */
522 Window *pWin, /* Window frame to update */
523 FuncDef *pFunc /* Window function definition */
dane3bf6322018-06-08 20:58:27 +0000524){
danc95f38d2018-06-18 20:34:43 +0000525 if( pWin->zName && pWin->eType==0 ){
dane3bf6322018-06-08 20:58:27 +0000526 Window *p;
527 for(p=pList; p; p=p->pNextWin){
528 if( sqlite3StrICmp(p->zName, pWin->zName)==0 ) break;
529 }
530 if( p==0 ){
531 sqlite3ErrorMsg(pParse, "no such window: %s", pWin->zName);
532 return;
533 }
534 pWin->pPartition = sqlite3ExprListDup(pParse->db, p->pPartition, 0);
535 pWin->pOrderBy = sqlite3ExprListDup(pParse->db, p->pOrderBy, 0);
536 pWin->pStart = sqlite3ExprDup(pParse->db, p->pStart, 0);
537 pWin->pEnd = sqlite3ExprDup(pParse->db, p->pEnd, 0);
538 pWin->eStart = p->eStart;
539 pWin->eEnd = p->eEnd;
danc95f38d2018-06-18 20:34:43 +0000540 pWin->eType = p->eType;
dane3bf6322018-06-08 20:58:27 +0000541 }
dandfa552f2018-06-02 21:04:28 +0000542 if( pFunc->funcFlags & SQLITE_FUNC_WINDOW ){
543 sqlite3 *db = pParse->db;
dan8b985602018-06-09 17:43:45 +0000544 if( pWin->pFilter ){
545 sqlite3ErrorMsg(pParse,
546 "FILTER clause may only be used with aggregate window functions"
547 );
548 }else
dan6bc5c9e2018-06-04 18:55:11 +0000549 if( pFunc->xSFunc==row_numberStepFunc || pFunc->xSFunc==ntileStepFunc ){
dandfa552f2018-06-02 21:04:28 +0000550 sqlite3ExprDelete(db, pWin->pStart);
551 sqlite3ExprDelete(db, pWin->pEnd);
552 pWin->pStart = pWin->pEnd = 0;
553 pWin->eType = TK_ROWS;
554 pWin->eStart = TK_UNBOUNDED;
555 pWin->eEnd = TK_CURRENT;
dan8b985602018-06-09 17:43:45 +0000556 }else
dandfa552f2018-06-02 21:04:28 +0000557
558 if( pFunc->xSFunc==dense_rankStepFunc || pFunc->xSFunc==rankStepFunc
danf1abe362018-06-04 08:22:09 +0000559 || pFunc->xSFunc==percent_rankStepFunc || pFunc->xSFunc==cume_distStepFunc
dandfa552f2018-06-02 21:04:28 +0000560 ){
561 sqlite3ExprDelete(db, pWin->pStart);
562 sqlite3ExprDelete(db, pWin->pEnd);
563 pWin->pStart = pWin->pEnd = 0;
564 pWin->eType = TK_RANGE;
565 pWin->eStart = TK_UNBOUNDED;
566 pWin->eEnd = TK_CURRENT;
567 }
568 }
dan2a11bb22018-06-11 20:50:25 +0000569 pWin->pFunc = pFunc;
dandfa552f2018-06-02 21:04:28 +0000570}
571
danc0bb4452018-06-12 20:53:38 +0000572/*
573** Context object passed through sqlite3WalkExprList() to
574** selectWindowRewriteExprCb() by selectWindowRewriteEList().
575*/
dandfa552f2018-06-02 21:04:28 +0000576typedef struct WindowRewrite WindowRewrite;
577struct WindowRewrite {
578 Window *pWin;
579 ExprList *pSub;
580};
581
danc0bb4452018-06-12 20:53:38 +0000582/*
583** Callback function used by selectWindowRewriteEList(). If necessary,
584** this function appends to the output expression-list and updates
585** expression (*ppExpr) in place.
586*/
dandfa552f2018-06-02 21:04:28 +0000587static int selectWindowRewriteExprCb(Walker *pWalker, Expr *pExpr){
588 struct WindowRewrite *p = pWalker->u.pRewrite;
589 Parse *pParse = pWalker->pParse;
590
591 switch( pExpr->op ){
592
593 case TK_FUNCTION:
594 if( pExpr->pWin==0 ){
595 break;
596 }else{
597 Window *pWin;
598 for(pWin=p->pWin; pWin; pWin=pWin->pNextWin){
599 if( pExpr->pWin==pWin ){
dan2a11bb22018-06-11 20:50:25 +0000600 assert( pWin->pOwner==pExpr );
dandfa552f2018-06-02 21:04:28 +0000601 return WRC_Prune;
602 }
603 }
604 }
605 /* Fall through. */
606
dan73925692018-06-12 18:40:17 +0000607 case TK_AGG_FUNCTION:
dandfa552f2018-06-02 21:04:28 +0000608 case TK_COLUMN: {
609 Expr *pDup = sqlite3ExprDup(pParse->db, pExpr, 0);
610 p->pSub = sqlite3ExprListAppend(pParse, p->pSub, pDup);
611 if( p->pSub ){
612 assert( ExprHasProperty(pExpr, EP_Static)==0 );
613 ExprSetProperty(pExpr, EP_Static);
614 sqlite3ExprDelete(pParse->db, pExpr);
615 ExprClearProperty(pExpr, EP_Static);
616 memset(pExpr, 0, sizeof(Expr));
617
618 pExpr->op = TK_COLUMN;
619 pExpr->iColumn = p->pSub->nExpr-1;
620 pExpr->iTable = p->pWin->iEphCsr;
621 }
622
623 break;
624 }
625
626 default: /* no-op */
627 break;
628 }
629
630 return WRC_Continue;
631}
danc0bb4452018-06-12 20:53:38 +0000632static int selectWindowRewriteSelectCb(Walker *pWalker, Select *pSelect){
633 return WRC_Prune;
634}
dandfa552f2018-06-02 21:04:28 +0000635
danc0bb4452018-06-12 20:53:38 +0000636
637/*
638** Iterate through each expression in expression-list pEList. For each:
639**
640** * TK_COLUMN,
641** * aggregate function, or
642** * window function with a Window object that is not a member of the
643** linked list passed as the second argument (pWin)
644**
645** Append the node to output expression-list (*ppSub). And replace it
646** with a TK_COLUMN that reads the (N-1)th element of table
647** pWin->iEphCsr, where N is the number of elements in (*ppSub) after
648** appending the new one.
649*/
dan13b08bb2018-06-15 20:46:12 +0000650static void selectWindowRewriteEList(
dandfa552f2018-06-02 21:04:28 +0000651 Parse *pParse,
652 Window *pWin,
653 ExprList *pEList, /* Rewrite expressions in this list */
654 ExprList **ppSub /* IN/OUT: Sub-select expression-list */
655){
656 Walker sWalker;
657 WindowRewrite sRewrite;
dandfa552f2018-06-02 21:04:28 +0000658
659 memset(&sWalker, 0, sizeof(Walker));
660 memset(&sRewrite, 0, sizeof(WindowRewrite));
661
662 sRewrite.pSub = *ppSub;
663 sRewrite.pWin = pWin;
664
665 sWalker.pParse = pParse;
666 sWalker.xExprCallback = selectWindowRewriteExprCb;
667 sWalker.xSelectCallback = selectWindowRewriteSelectCb;
668 sWalker.u.pRewrite = &sRewrite;
669
dan13b08bb2018-06-15 20:46:12 +0000670 (void)sqlite3WalkExprList(&sWalker, pEList);
dandfa552f2018-06-02 21:04:28 +0000671
672 *ppSub = sRewrite.pSub;
dandfa552f2018-06-02 21:04:28 +0000673}
674
danc0bb4452018-06-12 20:53:38 +0000675/*
676** Append a copy of each expression in expression-list pAppend to
677** expression list pList. Return a pointer to the result list.
678*/
dandfa552f2018-06-02 21:04:28 +0000679static ExprList *exprListAppendList(
680 Parse *pParse, /* Parsing context */
681 ExprList *pList, /* List to which to append. Might be NULL */
682 ExprList *pAppend /* List of values to append. Might be NULL */
683){
684 if( pAppend ){
685 int i;
686 int nInit = pList ? pList->nExpr : 0;
687 for(i=0; i<pAppend->nExpr; i++){
688 Expr *pDup = sqlite3ExprDup(pParse->db, pAppend->a[i].pExpr, 0);
689 pList = sqlite3ExprListAppend(pParse, pList, pDup);
690 if( pList ) pList->a[nInit+i].sortOrder = pAppend->a[i].sortOrder;
691 }
692 }
693 return pList;
694}
695
696/*
697** If the SELECT statement passed as the second argument does not invoke
698** any SQL window functions, this function is a no-op. Otherwise, it
699** rewrites the SELECT statement so that window function xStep functions
danc0bb4452018-06-12 20:53:38 +0000700** are invoked in the correct order as described under "SELECT REWRITING"
701** at the top of this file.
dandfa552f2018-06-02 21:04:28 +0000702*/
703int sqlite3WindowRewrite(Parse *pParse, Select *p){
704 int rc = SQLITE_OK;
705 if( p->pWin ){
706 Vdbe *v = sqlite3GetVdbe(pParse);
dandfa552f2018-06-02 21:04:28 +0000707 sqlite3 *db = pParse->db;
708 Select *pSub = 0; /* The subquery */
709 SrcList *pSrc = p->pSrc;
710 Expr *pWhere = p->pWhere;
711 ExprList *pGroupBy = p->pGroupBy;
712 Expr *pHaving = p->pHaving;
713 ExprList *pSort = 0;
714
715 ExprList *pSublist = 0; /* Expression list for sub-query */
716 Window *pMWin = p->pWin; /* Master window object */
717 Window *pWin; /* Window object iterator */
718
719 p->pSrc = 0;
720 p->pWhere = 0;
721 p->pGroupBy = 0;
722 p->pHaving = 0;
723
danf02cdd32018-06-27 19:48:50 +0000724 /* Create the ORDER BY clause for the sub-select. This is the concatenation
725 ** of the window PARTITION and ORDER BY clauses. Then, if this makes it
726 ** redundant, remove the ORDER BY from the parent SELECT. */
727 pSort = sqlite3ExprListDup(db, pMWin->pPartition, 0);
728 pSort = exprListAppendList(pParse, pSort, pMWin->pOrderBy);
729 if( pSort && p->pOrderBy ){
730 if( sqlite3ExprListCompare(pSort, p->pOrderBy, -1)==0 ){
731 sqlite3ExprListDelete(db, p->pOrderBy);
732 p->pOrderBy = 0;
733 }
734 }
735
dandfa552f2018-06-02 21:04:28 +0000736 /* Assign a cursor number for the ephemeral table used to buffer rows.
737 ** The OpenEphemeral instruction is coded later, after it is known how
738 ** many columns the table will have. */
739 pMWin->iEphCsr = pParse->nTab++;
740
dan13b08bb2018-06-15 20:46:12 +0000741 selectWindowRewriteEList(pParse, pMWin, p->pEList, &pSublist);
742 selectWindowRewriteEList(pParse, pMWin, p->pOrderBy, &pSublist);
dandfa552f2018-06-02 21:04:28 +0000743 pMWin->nBufferCol = (pSublist ? pSublist->nExpr : 0);
744
danf02cdd32018-06-27 19:48:50 +0000745 /* Append the PARTITION BY and ORDER BY expressions to the to the
746 ** sub-select expression list. They are required to figure out where
747 ** boundaries for partitions and sets of peer rows lie. */
748 pSublist = exprListAppendList(pParse, pSublist, pMWin->pPartition);
749 pSublist = exprListAppendList(pParse, pSublist, pMWin->pOrderBy);
dandfa552f2018-06-02 21:04:28 +0000750
751 /* Append the arguments passed to each window function to the
752 ** sub-select expression list. Also allocate two registers for each
753 ** window function - one for the accumulator, another for interim
754 ** results. */
755 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
756 pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);
757 pSublist = exprListAppendList(pParse, pSublist, pWin->pOwner->x.pList);
dan8b985602018-06-09 17:43:45 +0000758 if( pWin->pFilter ){
759 Expr *pFilter = sqlite3ExprDup(db, pWin->pFilter, 0);
760 pSublist = sqlite3ExprListAppend(pParse, pSublist, pFilter);
761 }
dandfa552f2018-06-02 21:04:28 +0000762 pWin->regAccum = ++pParse->nMem;
763 pWin->regResult = ++pParse->nMem;
764 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
765 }
766
dan9c277582018-06-20 09:23:49 +0000767 /* If there is no ORDER BY or PARTITION BY clause, and the window
768 ** function accepts zero arguments, and there are no other columns
769 ** selected (e.g. "SELECT row_number() OVER () FROM t1"), it is possible
770 ** that pSublist is still NULL here. Add a constant expression here to
771 ** keep everything legal in this case.
772 */
773 if( pSublist==0 ){
774 pSublist = sqlite3ExprListAppend(pParse, 0,
775 sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0)
776 );
777 }
778
dandfa552f2018-06-02 21:04:28 +0000779 pSub = sqlite3SelectNew(
780 pParse, pSublist, pSrc, pWhere, pGroupBy, pHaving, pSort, 0, 0
781 );
782 p->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
dan6fde1792018-06-15 19:01:35 +0000783 assert( p->pSrc || db->mallocFailed );
dandfa552f2018-06-02 21:04:28 +0000784 if( p->pSrc ){
dandfa552f2018-06-02 21:04:28 +0000785 p->pSrc->a[0].pSelect = pSub;
786 sqlite3SrcListAssignCursors(pParse, p->pSrc);
787 if( sqlite3ExpandSubquery(pParse, &p->pSrc->a[0]) ){
788 rc = SQLITE_NOMEM;
789 }else{
790 pSub->selFlags |= SF_Expanded;
dan73925692018-06-12 18:40:17 +0000791 p->selFlags &= ~SF_Aggregate;
792 sqlite3SelectPrep(pParse, pSub, 0);
dandfa552f2018-06-02 21:04:28 +0000793 }
dandfa552f2018-06-02 21:04:28 +0000794
dan6fde1792018-06-15 19:01:35 +0000795 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pMWin->iEphCsr, pSublist->nExpr);
796 }else{
797 sqlite3SelectDelete(db, pSub);
798 }
799 if( db->mallocFailed ) rc = SQLITE_NOMEM;
dandfa552f2018-06-02 21:04:28 +0000800 }
801
802 return rc;
803}
804
danc0bb4452018-06-12 20:53:38 +0000805/*
806** Free the Window object passed as the second argument.
807*/
dan86fb6e12018-05-16 20:58:07 +0000808void sqlite3WindowDelete(sqlite3 *db, Window *p){
809 if( p ){
810 sqlite3ExprDelete(db, p->pFilter);
811 sqlite3ExprListDelete(db, p->pPartition);
812 sqlite3ExprListDelete(db, p->pOrderBy);
813 sqlite3ExprDelete(db, p->pEnd);
814 sqlite3ExprDelete(db, p->pStart);
dane3bf6322018-06-08 20:58:27 +0000815 sqlite3DbFree(db, p->zName);
dan86fb6e12018-05-16 20:58:07 +0000816 sqlite3DbFree(db, p);
817 }
818}
819
danc0bb4452018-06-12 20:53:38 +0000820/*
821** Free the linked list of Window objects starting at the second argument.
822*/
dane3bf6322018-06-08 20:58:27 +0000823void sqlite3WindowListDelete(sqlite3 *db, Window *p){
824 while( p ){
825 Window *pNext = p->pNextWin;
826 sqlite3WindowDelete(db, p);
827 p = pNext;
828 }
829}
830
danc0bb4452018-06-12 20:53:38 +0000831/*
832** Allocate and return a new Window object.
833*/
dan86fb6e12018-05-16 20:58:07 +0000834Window *sqlite3WindowAlloc(
835 Parse *pParse,
836 int eType,
danc3a20c12018-05-23 20:55:37 +0000837 int eStart, Expr *pStart,
838 int eEnd, Expr *pEnd
dan86fb6e12018-05-16 20:58:07 +0000839){
dan7a606e12018-07-05 18:34:53 +0000840 Window *pWin = 0;
841
842 if( eType==TK_RANGE && (pStart || pEnd) ){
843 sqlite3ErrorMsg(pParse, "RANGE %s is only supported with UNBOUNDED",
844 (pStart ? "PRECEDING" : "FOLLOWING")
845 );
846 }else{
847 pWin = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
848 }
dan86fb6e12018-05-16 20:58:07 +0000849
850 if( pWin ){
danc95f38d2018-06-18 20:34:43 +0000851 assert( eType );
dan86fb6e12018-05-16 20:58:07 +0000852 pWin->eType = eType;
853 pWin->eStart = eStart;
854 pWin->eEnd = eEnd;
855 pWin->pEnd = pEnd;
856 pWin->pStart = pStart;
857 }else{
858 sqlite3ExprDelete(pParse->db, pEnd);
859 sqlite3ExprDelete(pParse->db, pStart);
860 }
861
862 return pWin;
863}
864
danc0bb4452018-06-12 20:53:38 +0000865/*
866** Attach window object pWin to expression p.
867*/
dan86fb6e12018-05-16 20:58:07 +0000868void sqlite3WindowAttach(Parse *pParse, Expr *p, Window *pWin){
869 if( p ){
dane33f6e72018-07-06 07:42:42 +0000870 if( pWin ){
871 p->pWin = pWin;
872 pWin->pOwner = p;
873 if( p->flags & EP_Distinct ){
874 sqlite3ErrorMsg(pParse,"DISTINCT is not supported for window functions");
875 }
876 }
dan86fb6e12018-05-16 20:58:07 +0000877 }else{
878 sqlite3WindowDelete(pParse->db, pWin);
879 }
880}
dane2f781b2018-05-17 19:24:08 +0000881
882/*
883** Return 0 if the two window objects are identical, or non-zero otherwise.
dan13078ca2018-06-13 20:29:38 +0000884** Identical window objects can be processed in a single scan.
dane2f781b2018-05-17 19:24:08 +0000885*/
886int sqlite3WindowCompare(Parse *pParse, Window *p1, Window *p2){
887 if( p1->eType!=p2->eType ) return 1;
888 if( p1->eStart!=p2->eStart ) return 1;
889 if( p1->eEnd!=p2->eEnd ) return 1;
890 if( sqlite3ExprCompare(pParse, p1->pStart, p2->pStart, -1) ) return 1;
891 if( sqlite3ExprCompare(pParse, p1->pEnd, p2->pEnd, -1) ) return 1;
892 if( sqlite3ExprListCompare(p1->pPartition, p2->pPartition, -1) ) return 1;
893 if( sqlite3ExprListCompare(p1->pOrderBy, p2->pOrderBy, -1) ) return 1;
894 return 0;
895}
896
dan13078ca2018-06-13 20:29:38 +0000897
898/*
899** This is called by code in select.c before it calls sqlite3WhereBegin()
900** to begin iterating through the sub-query results. It is used to allocate
901** and initialize registers and cursors used by sqlite3WindowCodeStep().
902*/
903void sqlite3WindowCodeInit(Parse *pParse, Window *pMWin){
danc9a86682018-05-30 20:44:58 +0000904 Window *pWin;
dan13078ca2018-06-13 20:29:38 +0000905 Vdbe *v = sqlite3GetVdbe(pParse);
906 int nPart = (pMWin->pPartition ? pMWin->pPartition->nExpr : 0);
907 nPart += (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);
908 if( nPart ){
909 pMWin->regPart = pParse->nMem+1;
910 pParse->nMem += nPart;
911 sqlite3VdbeAddOp3(v, OP_Null, 0, pMWin->regPart, pMWin->regPart+nPart-1);
912 }
913
danc9a86682018-05-30 20:44:58 +0000914 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
danec891fd2018-06-06 20:51:02 +0000915 FuncDef *p = pWin->pFunc;
916 if( (p->funcFlags & SQLITE_FUNC_MINMAX) && pWin->eStart!=TK_UNBOUNDED ){
dan9a947222018-06-14 19:06:36 +0000917 /* The inline versions of min() and max() require a single ephemeral
918 ** table and 3 registers. The registers are used as follows:
919 **
920 ** regApp+0: slot to copy min()/max() argument to for MakeRecord
921 ** regApp+1: integer value used to ensure keys are unique
922 ** regApp+2: output of MakeRecord
923 */
danc9a86682018-05-30 20:44:58 +0000924 ExprList *pList = pWin->pOwner->x.pList;
925 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pList, 0, 0);
danc9a86682018-05-30 20:44:58 +0000926 pWin->csrApp = pParse->nTab++;
927 pWin->regApp = pParse->nMem+1;
928 pParse->nMem += 3;
929 if( pKeyInfo && pWin->pFunc->zName[1]=='i' ){
930 assert( pKeyInfo->aSortOrder[0]==0 );
931 pKeyInfo->aSortOrder[0] = 1;
932 }
933 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pWin->csrApp, 2);
934 sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
935 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
936 }
dan7095c002018-06-07 17:45:22 +0000937 else if( p->xSFunc==nth_valueStepFunc || p->xSFunc==first_valueStepFunc ){
danec891fd2018-06-06 20:51:02 +0000938 /* Allocate two registers at pWin->regApp. These will be used to
939 ** store the start and end index of the current frame. */
940 assert( pMWin->iEphCsr );
941 pWin->regApp = pParse->nMem+1;
942 pWin->csrApp = pParse->nTab++;
943 pParse->nMem += 2;
danec891fd2018-06-06 20:51:02 +0000944 sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
945 }
danfe4e25a2018-06-07 20:08:59 +0000946 else if( p->xSFunc==leadStepFunc || p->xSFunc==lagStepFunc ){
947 assert( pMWin->iEphCsr );
948 pWin->csrApp = pParse->nTab++;
949 sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
950 }
danc9a86682018-05-30 20:44:58 +0000951 }
952}
953
dan13078ca2018-06-13 20:29:38 +0000954/*
955** A "PRECEDING <expr>" (bEnd==0) or "FOLLOWING <expr>" (bEnd==1) has just
956** been evaluated and the result left in register reg. This function generates
957** VM code to check that the value is a non-negative integer and throws
958** an exception if it is not.
959*/
danc3a20c12018-05-23 20:55:37 +0000960static void windowCheckFrameValue(Parse *pParse, int reg, int bEnd){
961 static const char *azErr[] = {
962 "frame starting offset must be a non-negative integer",
963 "frame ending offset must be a non-negative integer"
964 };
965 Vdbe *v = sqlite3GetVdbe(pParse);
dan13078ca2018-06-13 20:29:38 +0000966 int regZero = sqlite3GetTempReg(pParse);
danc3a20c12018-05-23 20:55:37 +0000967 sqlite3VdbeAddOp2(v, OP_Integer, 0, regZero);
968 sqlite3VdbeAddOp2(v, OP_MustBeInt, reg, sqlite3VdbeCurrentAddr(v)+2);
969 sqlite3VdbeAddOp3(v, OP_Ge, regZero, sqlite3VdbeCurrentAddr(v)+2, reg);
dan01e12292018-06-27 20:24:59 +0000970 VdbeCoverage(v);
danc3a20c12018-05-23 20:55:37 +0000971 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_ERROR, OE_Abort);
972 sqlite3VdbeAppendP4(v, (void*)azErr[bEnd], P4_STATIC);
dan13078ca2018-06-13 20:29:38 +0000973 sqlite3ReleaseTempReg(pParse, regZero);
danc3a20c12018-05-23 20:55:37 +0000974}
975
dan13078ca2018-06-13 20:29:38 +0000976/*
977** Return the number of arguments passed to the window-function associated
978** with the object passed as the only argument to this function.
979*/
dan2a11bb22018-06-11 20:50:25 +0000980static int windowArgCount(Window *pWin){
981 ExprList *pList = pWin->pOwner->x.pList;
982 return (pList ? pList->nExpr : 0);
983}
984
danc9a86682018-05-30 20:44:58 +0000985/*
986** Generate VM code to invoke either xStep() (if bInverse is 0) or
987** xInverse (if bInverse is non-zero) for each window function in the
dan13078ca2018-06-13 20:29:38 +0000988** linked list starting at pMWin. Or, for built-in window functions
989** that do not use the standard function API, generate the required
990** inline VM code.
991**
992** If argument csr is greater than or equal to 0, then argument reg is
993** the first register in an array of registers guaranteed to be large
994** enough to hold the array of arguments for each function. In this case
995** the arguments are extracted from the current row of csr into the
drh8f26da62018-07-05 21:22:57 +0000996** array of registers before invoking OP_AggStep or OP_AggInverse
dan13078ca2018-06-13 20:29:38 +0000997**
998** Or, if csr is less than zero, then the array of registers at reg is
999** already populated with all columns from the current row of the sub-query.
1000**
1001** If argument regPartSize is non-zero, then it is a register containing the
1002** number of rows in the current partition.
danc9a86682018-05-30 20:44:58 +00001003*/
dan31f56392018-05-24 21:10:57 +00001004static void windowAggStep(
1005 Parse *pParse,
dan13078ca2018-06-13 20:29:38 +00001006 Window *pMWin, /* Linked list of window functions */
1007 int csr, /* Read arguments from this cursor */
1008 int bInverse, /* True to invoke xInverse instead of xStep */
1009 int reg, /* Array of registers */
dandfa552f2018-06-02 21:04:28 +00001010 int regPartSize /* Register containing size of partition */
dan31f56392018-05-24 21:10:57 +00001011){
1012 Vdbe *v = sqlite3GetVdbe(pParse);
1013 Window *pWin;
1014 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
dandfa552f2018-06-02 21:04:28 +00001015 int flags = pWin->pFunc->funcFlags;
danc9a86682018-05-30 20:44:58 +00001016 int regArg;
dan2a11bb22018-06-11 20:50:25 +00001017 int nArg = windowArgCount(pWin);
dandfa552f2018-06-02 21:04:28 +00001018
dan6bc5c9e2018-06-04 18:55:11 +00001019 if( csr>=0 ){
danc9a86682018-05-30 20:44:58 +00001020 int i;
dan2a11bb22018-06-11 20:50:25 +00001021 for(i=0; i<nArg; i++){
danc9a86682018-05-30 20:44:58 +00001022 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+i, reg+i);
1023 }
1024 regArg = reg;
dan6bc5c9e2018-06-04 18:55:11 +00001025 if( flags & SQLITE_FUNC_WINDOW_SIZE ){
1026 if( nArg==0 ){
1027 regArg = regPartSize;
1028 }else{
1029 sqlite3VdbeAddOp2(v, OP_SCopy, regPartSize, reg+nArg);
1030 }
1031 nArg++;
1032 }
danc9a86682018-05-30 20:44:58 +00001033 }else{
dan6bc5c9e2018-06-04 18:55:11 +00001034 assert( !(flags & SQLITE_FUNC_WINDOW_SIZE) );
danc9a86682018-05-30 20:44:58 +00001035 regArg = reg + pWin->iArgCol;
dan31f56392018-05-24 21:10:57 +00001036 }
danc9a86682018-05-30 20:44:58 +00001037
danec891fd2018-06-06 20:51:02 +00001038 if( (pWin->pFunc->funcFlags & SQLITE_FUNC_MINMAX)
1039 && pWin->eStart!=TK_UNBOUNDED
1040 ){
danc9a86682018-05-30 20:44:58 +00001041 if( bInverse==0 ){
1042 sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1, 1);
1043 sqlite3VdbeAddOp2(v, OP_SCopy, regArg, pWin->regApp);
1044 sqlite3VdbeAddOp3(v, OP_MakeRecord, pWin->regApp, 2, pWin->regApp+2);
1045 sqlite3VdbeAddOp2(v, OP_IdxInsert, pWin->csrApp, pWin->regApp+2);
1046 }else{
1047 sqlite3VdbeAddOp4Int(v, OP_SeekGE, pWin->csrApp, 0, regArg, 1);
dan01e12292018-06-27 20:24:59 +00001048 VdbeCoverage(v);
danc9a86682018-05-30 20:44:58 +00001049 sqlite3VdbeAddOp1(v, OP_Delete, pWin->csrApp);
1050 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
1051 }
danec891fd2018-06-06 20:51:02 +00001052 }else if( pWin->regApp ){
dan7095c002018-06-07 17:45:22 +00001053 assert( pWin->pFunc->xSFunc==nth_valueStepFunc
1054 || pWin->pFunc->xSFunc==first_valueStepFunc
1055 );
danec891fd2018-06-06 20:51:02 +00001056 assert( bInverse==0 || bInverse==1 );
1057 sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1-bInverse, 1);
danfe4e25a2018-06-07 20:08:59 +00001058 }else if( pWin->pFunc->xSFunc==leadStepFunc
1059 || pWin->pFunc->xSFunc==lagStepFunc
1060 ){
1061 /* no-op */
danc9a86682018-05-30 20:44:58 +00001062 }else{
dan8b985602018-06-09 17:43:45 +00001063 int addrIf = 0;
1064 if( pWin->pFilter ){
1065 int regTmp;
dan2a11bb22018-06-11 20:50:25 +00001066 assert( nArg==pWin->pOwner->x.pList->nExpr );
dan8b985602018-06-09 17:43:45 +00001067 if( csr>0 ){
1068 regTmp = sqlite3GetTempReg(pParse);
dan2a11bb22018-06-11 20:50:25 +00001069 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+nArg,regTmp);
dan8b985602018-06-09 17:43:45 +00001070 }else{
dan2a11bb22018-06-11 20:50:25 +00001071 regTmp = regArg + nArg;
dan8b985602018-06-09 17:43:45 +00001072 }
1073 addrIf = sqlite3VdbeAddOp3(v, OP_IfNot, regTmp, 0, 1);
dan01e12292018-06-27 20:24:59 +00001074 VdbeCoverage(v);
dan8b985602018-06-09 17:43:45 +00001075 if( csr>0 ){
1076 sqlite3ReleaseTempReg(pParse, regTmp);
1077 }
1078 }
danc9a86682018-05-30 20:44:58 +00001079 if( pWin->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
1080 CollSeq *pColl;
dan8b985602018-06-09 17:43:45 +00001081 pColl = sqlite3ExprNNCollSeq(pParse, pWin->pOwner->x.pList->a[0].pExpr);
danc9a86682018-05-30 20:44:58 +00001082 sqlite3VdbeAddOp4(v, OP_CollSeq, 0,0,0, (const char*)pColl, P4_COLLSEQ);
1083 }
drh8f26da62018-07-05 21:22:57 +00001084 sqlite3VdbeAddOp3(v, bInverse? OP_AggInverse : OP_AggStep,
1085 bInverse, regArg, pWin->regAccum);
danc9a86682018-05-30 20:44:58 +00001086 sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
dandfa552f2018-06-02 21:04:28 +00001087 sqlite3VdbeChangeP5(v, (u8)nArg);
dan8b985602018-06-09 17:43:45 +00001088 if( addrIf ) sqlite3VdbeJumpHere(v, addrIf);
danc9a86682018-05-30 20:44:58 +00001089 }
dan31f56392018-05-24 21:10:57 +00001090 }
1091}
1092
dan13078ca2018-06-13 20:29:38 +00001093/*
1094** Generate VM code to invoke either xValue() (bFinal==0) or xFinalize()
1095** (bFinal==1) for each window function in the linked list starting at
1096** pMWin. Or, for built-in window-functions that do not use the standard
1097** API, generate the equivalent VM code.
1098*/
dand6f784e2018-05-28 18:30:45 +00001099static void windowAggFinal(Parse *pParse, Window *pMWin, int bFinal){
1100 Vdbe *v = sqlite3GetVdbe(pParse);
1101 Window *pWin;
1102
1103 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
danec891fd2018-06-06 20:51:02 +00001104 if( (pWin->pFunc->funcFlags & SQLITE_FUNC_MINMAX)
1105 && pWin->eStart!=TK_UNBOUNDED
1106 ){
dand6f784e2018-05-28 18:30:45 +00001107 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
danc9a86682018-05-30 20:44:58 +00001108 sqlite3VdbeAddOp1(v, OP_Last, pWin->csrApp);
dan01e12292018-06-27 20:24:59 +00001109 VdbeCoverage(v);
danc9a86682018-05-30 20:44:58 +00001110 sqlite3VdbeAddOp3(v, OP_Column, pWin->csrApp, 0, pWin->regResult);
1111 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
1112 if( bFinal ){
1113 sqlite3VdbeAddOp1(v, OP_ResetSorter, pWin->csrApp);
1114 }
danec891fd2018-06-06 20:51:02 +00001115 }else if( pWin->regApp ){
dand6f784e2018-05-28 18:30:45 +00001116 }else{
danc9a86682018-05-30 20:44:58 +00001117 if( bFinal ){
drh8f26da62018-07-05 21:22:57 +00001118 sqlite3VdbeAddOp2(v, OP_AggFinal, pWin->regAccum, windowArgCount(pWin));
1119 sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
danc9a86682018-05-30 20:44:58 +00001120 sqlite3VdbeAddOp2(v, OP_Copy, pWin->regAccum, pWin->regResult);
dan8b985602018-06-09 17:43:45 +00001121 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
danc9a86682018-05-30 20:44:58 +00001122 }else{
drh8f26da62018-07-05 21:22:57 +00001123 sqlite3VdbeAddOp3(v, OP_AggValue, pWin->regAccum, windowArgCount(pWin),
1124 pWin->regResult);
1125 sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
danc9a86682018-05-30 20:44:58 +00001126 }
dand6f784e2018-05-28 18:30:45 +00001127 }
1128 }
1129}
1130
dan13078ca2018-06-13 20:29:38 +00001131/*
1132** This function generates VM code to invoke the sub-routine at address
1133** lblFlushPart once for each partition with the entire partition cached in
1134** the Window.iEphCsr temp table.
1135*/
danf690b572018-06-01 21:00:08 +00001136static void windowPartitionCache(
1137 Parse *pParse,
dan13078ca2018-06-13 20:29:38 +00001138 Select *p, /* The rewritten SELECT statement */
1139 WhereInfo *pWInfo, /* WhereInfo to call WhereEnd() on */
1140 int regFlushPart, /* Register to use with Gosub lblFlushPart */
1141 int lblFlushPart, /* Subroutine to Gosub to */
1142 int *pRegSize /* OUT: Register containing partition size */
danf690b572018-06-01 21:00:08 +00001143){
1144 Window *pMWin = p->pWin;
1145 Vdbe *v = sqlite3GetVdbe(pParse);
danf690b572018-06-01 21:00:08 +00001146 int iSubCsr = p->pSrc->a[0].iCursor;
1147 int nSub = p->pSrc->a[0].pTab->nCol;
1148 int k;
1149
1150 int reg = pParse->nMem+1;
1151 int regRecord = reg+nSub;
1152 int regRowid = regRecord+1;
1153
dandfa552f2018-06-02 21:04:28 +00001154 *pRegSize = regRowid;
danf690b572018-06-01 21:00:08 +00001155 pParse->nMem += nSub + 2;
1156
1157 /* Martial the row returned by the sub-select into an array of
1158 ** registers. */
1159 for(k=0; k<nSub; k++){
1160 sqlite3VdbeAddOp3(v, OP_Column, iSubCsr, k, reg+k);
1161 }
1162 sqlite3VdbeAddOp3(v, OP_MakeRecord, reg, nSub, regRecord);
1163
1164 /* Check if this is the start of a new partition. If so, call the
1165 ** flush_partition sub-routine. */
1166 if( pMWin->pPartition ){
1167 int addr;
1168 ExprList *pPart = pMWin->pPartition;
dane0a5e202018-06-15 16:10:44 +00001169 int nPart = pPart->nExpr;
danf690b572018-06-01 21:00:08 +00001170 int regNewPart = reg + pMWin->nBufferCol;
1171 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pPart, 0, 0);
1172
1173 addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPart, pMWin->regPart,nPart);
1174 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
1175 sqlite3VdbeAddOp3(v, OP_Jump, addr+2, addr+4, addr+2);
dan01e12292018-06-27 20:24:59 +00001176 VdbeCoverage(v);
danf690b572018-06-01 21:00:08 +00001177 sqlite3VdbeAddOp3(v, OP_Copy, regNewPart, pMWin->regPart, nPart-1);
1178 sqlite3VdbeAddOp2(v, OP_Gosub, regFlushPart, lblFlushPart);
1179 }
1180
1181 /* Buffer the current row in the ephemeral table. */
1182 sqlite3VdbeAddOp2(v, OP_NewRowid, pMWin->iEphCsr, regRowid);
1183 sqlite3VdbeAddOp3(v, OP_Insert, pMWin->iEphCsr, regRecord, regRowid);
1184
1185 /* End of the input loop */
1186 sqlite3WhereEnd(pWInfo);
1187
1188 /* Invoke "flush_partition" to deal with the final (or only) partition */
1189 sqlite3VdbeAddOp2(v, OP_Gosub, regFlushPart, lblFlushPart);
1190}
dand6f784e2018-05-28 18:30:45 +00001191
dan13078ca2018-06-13 20:29:38 +00001192/*
1193** Invoke the sub-routine at regGosub (generated by code in select.c) to
1194** return the current row of Window.iEphCsr. If all window functions are
1195** aggregate window functions that use the standard API, a single
1196** OP_Gosub instruction is all that this routine generates. Extra VM code
1197** for per-row processing is only generated for the following built-in window
1198** functions:
1199**
1200** nth_value()
1201** first_value()
1202** lag()
1203** lead()
1204*/
danec891fd2018-06-06 20:51:02 +00001205static void windowReturnOneRow(
1206 Parse *pParse,
1207 Window *pMWin,
1208 int regGosub,
1209 int addrGosub
1210){
1211 Vdbe *v = sqlite3GetVdbe(pParse);
1212 Window *pWin;
1213 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1214 FuncDef *pFunc = pWin->pFunc;
dan7095c002018-06-07 17:45:22 +00001215 if( pFunc->xSFunc==nth_valueStepFunc
1216 || pFunc->xSFunc==first_valueStepFunc
1217 ){
danec891fd2018-06-06 20:51:02 +00001218 int csr = pWin->csrApp;
1219 int lbl = sqlite3VdbeMakeLabel(v);
1220 int tmpReg = sqlite3GetTempReg(pParse);
1221 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
dan7095c002018-06-07 17:45:22 +00001222
1223 if( pFunc->xSFunc==nth_valueStepFunc ){
dan6fde1792018-06-15 19:01:35 +00001224 sqlite3VdbeAddOp3(v, OP_Column, pMWin->iEphCsr, pWin->iArgCol+1,tmpReg);
dan7095c002018-06-07 17:45:22 +00001225 }else{
1226 sqlite3VdbeAddOp2(v, OP_Integer, 1, tmpReg);
1227 }
danec891fd2018-06-06 20:51:02 +00001228 sqlite3VdbeAddOp3(v, OP_Add, tmpReg, pWin->regApp, tmpReg);
1229 sqlite3VdbeAddOp3(v, OP_Gt, pWin->regApp+1, lbl, tmpReg);
dan01e12292018-06-27 20:24:59 +00001230 VdbeCoverage(v);
danec891fd2018-06-06 20:51:02 +00001231 sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, lbl, tmpReg);
dan01e12292018-06-27 20:24:59 +00001232 VdbeCoverage(v);
danec891fd2018-06-06 20:51:02 +00001233 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
1234 sqlite3VdbeResolveLabel(v, lbl);
1235 sqlite3ReleaseTempReg(pParse, tmpReg);
1236 }
danfe4e25a2018-06-07 20:08:59 +00001237 else if( pFunc->xSFunc==leadStepFunc || pFunc->xSFunc==lagStepFunc ){
dan2a11bb22018-06-11 20:50:25 +00001238 int nArg = pWin->pOwner->x.pList->nExpr;
dane0a5e202018-06-15 16:10:44 +00001239 int iEph = pMWin->iEphCsr;
danfe4e25a2018-06-07 20:08:59 +00001240 int csr = pWin->csrApp;
1241 int lbl = sqlite3VdbeMakeLabel(v);
1242 int tmpReg = sqlite3GetTempReg(pParse);
1243
dan2a11bb22018-06-11 20:50:25 +00001244 if( nArg<3 ){
danfe4e25a2018-06-07 20:08:59 +00001245 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
1246 }else{
1247 sqlite3VdbeAddOp3(v, OP_Column, iEph, pWin->iArgCol+2, pWin->regResult);
1248 }
1249 sqlite3VdbeAddOp2(v, OP_Rowid, iEph, tmpReg);
dan2a11bb22018-06-11 20:50:25 +00001250 if( nArg<2 ){
danfe4e25a2018-06-07 20:08:59 +00001251 int val = (pFunc->xSFunc==leadStepFunc ? 1 : -1);
1252 sqlite3VdbeAddOp2(v, OP_AddImm, tmpReg, val);
1253 }else{
1254 int op = (pFunc->xSFunc==leadStepFunc ? OP_Add : OP_Subtract);
1255 int tmpReg2 = sqlite3GetTempReg(pParse);
1256 sqlite3VdbeAddOp3(v, OP_Column, iEph, pWin->iArgCol+1, tmpReg2);
1257 sqlite3VdbeAddOp3(v, op, tmpReg2, tmpReg, tmpReg);
1258 sqlite3ReleaseTempReg(pParse, tmpReg2);
1259 }
1260
1261 sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, lbl, tmpReg);
dan01e12292018-06-27 20:24:59 +00001262 VdbeCoverage(v);
danfe4e25a2018-06-07 20:08:59 +00001263 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
1264 sqlite3VdbeResolveLabel(v, lbl);
1265 sqlite3ReleaseTempReg(pParse, tmpReg);
1266 }
danec891fd2018-06-06 20:51:02 +00001267 }
1268 sqlite3VdbeAddOp2(v, OP_Gosub, regGosub, addrGosub);
1269}
1270
dan13078ca2018-06-13 20:29:38 +00001271/*
1272** Invoke the code generated by windowReturnOneRow() and, optionally, the
1273** xInverse() function for each window function, for one or more rows
1274** from the Window.iEphCsr temp table. This routine generates VM code
1275** similar to:
1276**
1277** while( regCtr>0 ){
1278** regCtr--;
1279** windowReturnOneRow()
1280** if( bInverse ){
drh8f26da62018-07-05 21:22:57 +00001281** AggInverse
dan13078ca2018-06-13 20:29:38 +00001282** }
1283** Next (Window.iEphCsr)
1284** }
1285*/
danec891fd2018-06-06 20:51:02 +00001286static void windowReturnRows(
1287 Parse *pParse,
dan13078ca2018-06-13 20:29:38 +00001288 Window *pMWin, /* List of window functions */
1289 int regCtr, /* Register containing number of rows */
1290 int regGosub, /* Register for Gosub addrGosub */
1291 int addrGosub, /* Address of sub-routine for ReturnOneRow */
1292 int regInvArg, /* Array of registers for xInverse args */
1293 int regInvSize /* Register containing size of partition */
danec891fd2018-06-06 20:51:02 +00001294){
1295 int addr;
1296 Vdbe *v = sqlite3GetVdbe(pParse);
1297 windowAggFinal(pParse, pMWin, 0);
1298 addr = sqlite3VdbeAddOp3(v, OP_IfPos, regCtr, sqlite3VdbeCurrentAddr(v)+2 ,1);
dan01e12292018-06-27 20:24:59 +00001299 VdbeCoverage(v);
danec891fd2018-06-06 20:51:02 +00001300 sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
1301 windowReturnOneRow(pParse, pMWin, regGosub, addrGosub);
1302 if( regInvArg ){
1303 windowAggStep(pParse, pMWin, pMWin->iEphCsr, 1, regInvArg, regInvSize);
1304 }
1305 sqlite3VdbeAddOp2(v, OP_Next, pMWin->iEphCsr, addr);
dan01e12292018-06-27 20:24:59 +00001306 VdbeCoverage(v);
danec891fd2018-06-06 20:51:02 +00001307 sqlite3VdbeJumpHere(v, addr+1); /* The OP_Goto */
1308}
1309
dan54a9ab32018-06-14 14:27:05 +00001310/*
1311** Generate code to set the accumulator register for each window function
1312** in the linked list passed as the second argument to NULL. And perform
1313** any equivalent initialization required by any built-in window functions
1314** in the list.
1315*/
dan2e605682018-06-07 15:54:26 +00001316static int windowInitAccum(Parse *pParse, Window *pMWin){
1317 Vdbe *v = sqlite3GetVdbe(pParse);
1318 int regArg;
1319 int nArg = 0;
1320 Window *pWin;
1321 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
dan9a947222018-06-14 19:06:36 +00001322 FuncDef *pFunc = pWin->pFunc;
dan2e605682018-06-07 15:54:26 +00001323 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
dan2a11bb22018-06-11 20:50:25 +00001324 nArg = MAX(nArg, windowArgCount(pWin));
dan9a947222018-06-14 19:06:36 +00001325 if( pFunc->xSFunc==nth_valueStepFunc
1326 || pFunc->xSFunc==first_valueStepFunc
dan7095c002018-06-07 17:45:22 +00001327 ){
dan2e605682018-06-07 15:54:26 +00001328 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp);
1329 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
1330 }
dan9a947222018-06-14 19:06:36 +00001331
1332 if( (pFunc->funcFlags & SQLITE_FUNC_MINMAX) && pWin->csrApp ){
1333 assert( pWin->eStart!=TK_UNBOUNDED );
1334 sqlite3VdbeAddOp1(v, OP_ResetSorter, pWin->csrApp);
1335 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
1336 }
dan2e605682018-06-07 15:54:26 +00001337 }
1338 regArg = pParse->nMem+1;
1339 pParse->nMem += nArg;
1340 return regArg;
1341}
1342
1343
dan99652dd2018-05-24 17:49:14 +00001344/*
dan54a9ab32018-06-14 14:27:05 +00001345** This function does the work of sqlite3WindowCodeStep() for all "ROWS"
1346** window frame types except for "BETWEEN UNBOUNDED PRECEDING AND CURRENT
1347** ROW". Pseudo-code for each follows.
1348**
dan09590aa2018-05-25 20:30:17 +00001349** ROWS BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
dan09590aa2018-05-25 20:30:17 +00001350**
1351** ...
1352** if( new partition ){
1353** Gosub flush_partition
1354** }
1355** Insert (record in eph-table)
1356** sqlite3WhereEnd()
1357** Gosub flush_partition
1358**
1359** flush_partition:
1360** Once {
1361** OpenDup (iEphCsr -> csrStart)
1362** OpenDup (iEphCsr -> csrEnd)
dan99652dd2018-05-24 17:49:14 +00001363** }
dan09590aa2018-05-25 20:30:17 +00001364** regStart = <expr1> // PRECEDING expression
1365** regEnd = <expr2> // FOLLOWING expression
1366** if( regStart<0 || regEnd<0 ){ error! }
1367** Rewind (csr,csrStart,csrEnd) // if EOF goto flush_partition_done
1368** Next(csrEnd) // if EOF skip Aggstep
1369** Aggstep (csrEnd)
1370** if( (regEnd--)<=0 ){
1371** AggFinal (xValue)
1372** Gosub addrGosub
1373** Next(csr) // if EOF goto flush_partition_done
1374** if( (regStart--)<=0 ){
drh8f26da62018-07-05 21:22:57 +00001375** AggInverse (csrStart)
dan09590aa2018-05-25 20:30:17 +00001376** Next(csrStart)
1377** }
1378** }
1379** flush_partition_done:
1380** ResetSorter (csr)
1381** Return
dan99652dd2018-05-24 17:49:14 +00001382**
dan09590aa2018-05-25 20:30:17 +00001383** ROWS BETWEEN <expr> PRECEDING AND CURRENT ROW
1384** ROWS BETWEEN CURRENT ROW AND <expr> FOLLOWING
1385** ROWS BETWEEN UNBOUNDED PRECEDING AND <expr> FOLLOWING
1386**
1387** These are similar to the above. For "CURRENT ROW", intialize the
1388** register to 0. For "UNBOUNDED PRECEDING" to infinity.
1389**
1390** ROWS BETWEEN <expr> PRECEDING AND UNBOUNDED FOLLOWING
1391** ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
1392**
1393** Rewind (csr,csrStart,csrEnd) // if EOF goto flush_partition_done
1394** while( 1 ){
1395** Next(csrEnd) // Exit while(1) at EOF
1396** Aggstep (csrEnd)
1397** }
1398** while( 1 ){
dan99652dd2018-05-24 17:49:14 +00001399** AggFinal (xValue)
1400** Gosub addrGosub
dan09590aa2018-05-25 20:30:17 +00001401** Next(csr) // if EOF goto flush_partition_done
dan31f56392018-05-24 21:10:57 +00001402** if( (regStart--)<=0 ){
drh8f26da62018-07-05 21:22:57 +00001403** AggInverse (csrStart)
dan31f56392018-05-24 21:10:57 +00001404** Next(csrStart)
dan99652dd2018-05-24 17:49:14 +00001405** }
1406** }
dan99652dd2018-05-24 17:49:14 +00001407**
dan09590aa2018-05-25 20:30:17 +00001408** For the "CURRENT ROW AND UNBOUNDED FOLLOWING" case, the final if()
1409** condition is always true (as if regStart were initialized to 0).
dan99652dd2018-05-24 17:49:14 +00001410**
dan09590aa2018-05-25 20:30:17 +00001411** RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
1412**
1413** This is the only RANGE case handled by this routine. It modifies the
1414** second while( 1 ) loop in "ROWS BETWEEN CURRENT ... UNBOUNDED..." to
1415** be:
1416**
1417** while( 1 ){
1418** AggFinal (xValue)
1419** while( 1 ){
1420** regPeer++
1421** Gosub addrGosub
1422** Next(csr) // if EOF goto flush_partition_done
1423** if( new peer ) break;
1424** }
1425** while( (regPeer--)>0 ){
drh8f26da62018-07-05 21:22:57 +00001426** AggInverse (csrStart)
dan09590aa2018-05-25 20:30:17 +00001427** Next(csrStart)
1428** }
1429** }
dan99652dd2018-05-24 17:49:14 +00001430**
dan31f56392018-05-24 21:10:57 +00001431** ROWS BETWEEN <expr> FOLLOWING AND <expr> FOLLOWING
1432**
1433** regEnd = regEnd - regStart
1434** Rewind (csr,csrStart,csrEnd) // if EOF goto flush_partition_done
1435** Aggstep (csrEnd)
1436** Next(csrEnd) // if EOF fall-through
1437** if( (regEnd--)<=0 ){
dan31f56392018-05-24 21:10:57 +00001438** if( (regStart--)<=0 ){
1439** AggFinal (xValue)
1440** Gosub addrGosub
1441** Next(csr) // if EOF goto flush_partition_done
1442** }
drh8f26da62018-07-05 21:22:57 +00001443** AggInverse (csrStart)
dane105dd72018-05-25 09:29:11 +00001444** Next (csrStart)
dan31f56392018-05-24 21:10:57 +00001445** }
1446**
1447** ROWS BETWEEN <expr> PRECEDING AND <expr> PRECEDING
1448**
1449** Replace the bit after "Rewind" in the above with:
1450**
1451** if( (regEnd--)<=0 ){
1452** AggStep (csrEnd)
1453** Next (csrEnd)
1454** }
1455** AggFinal (xValue)
1456** Gosub addrGosub
1457** Next(csr) // if EOF goto flush_partition_done
1458** if( (regStart--)<=0 ){
drh8f26da62018-07-05 21:22:57 +00001459** AggInverse (csr2)
dan31f56392018-05-24 21:10:57 +00001460** Next (csr2)
1461** }
1462**
dan99652dd2018-05-24 17:49:14 +00001463*/
danc3a20c12018-05-23 20:55:37 +00001464static void windowCodeRowExprStep(
1465 Parse *pParse,
1466 Select *p,
1467 WhereInfo *pWInfo,
1468 int regGosub,
1469 int addrGosub
1470){
1471 Window *pMWin = p->pWin;
1472 Vdbe *v = sqlite3GetVdbe(pParse);
danc3a20c12018-05-23 20:55:37 +00001473 int regFlushPart; /* Register for "Gosub flush_partition" */
dan31f56392018-05-24 21:10:57 +00001474 int lblFlushPart; /* Label for "Gosub flush_partition" */
1475 int lblFlushDone; /* Label for "Gosub flush_partition_done" */
danc3a20c12018-05-23 20:55:37 +00001476
danf690b572018-06-01 21:00:08 +00001477 int regArg;
danc3a20c12018-05-23 20:55:37 +00001478 int addr;
dan31f56392018-05-24 21:10:57 +00001479 int csrStart = pParse->nTab++;
1480 int csrEnd = pParse->nTab++;
1481 int regStart; /* Value of <expr> PRECEDING */
1482 int regEnd; /* Value of <expr> FOLLOWING */
danc3a20c12018-05-23 20:55:37 +00001483 int addrGoto;
dan31f56392018-05-24 21:10:57 +00001484 int addrTop;
danc3a20c12018-05-23 20:55:37 +00001485 int addrIfPos1;
1486 int addrIfPos2;
dandfa552f2018-06-02 21:04:28 +00001487 int regSize = 0;
dan09590aa2018-05-25 20:30:17 +00001488
dan99652dd2018-05-24 17:49:14 +00001489 assert( pMWin->eStart==TK_PRECEDING
1490 || pMWin->eStart==TK_CURRENT
dane105dd72018-05-25 09:29:11 +00001491 || pMWin->eStart==TK_FOLLOWING
dan99652dd2018-05-24 17:49:14 +00001492 || pMWin->eStart==TK_UNBOUNDED
1493 );
1494 assert( pMWin->eEnd==TK_FOLLOWING
1495 || pMWin->eEnd==TK_CURRENT
1496 || pMWin->eEnd==TK_UNBOUNDED
dan31f56392018-05-24 21:10:57 +00001497 || pMWin->eEnd==TK_PRECEDING
dan99652dd2018-05-24 17:49:14 +00001498 );
1499
danc3a20c12018-05-23 20:55:37 +00001500 /* Allocate register and label for the "flush_partition" sub-routine. */
1501 regFlushPart = ++pParse->nMem;
dan31f56392018-05-24 21:10:57 +00001502 lblFlushPart = sqlite3VdbeMakeLabel(v);
1503 lblFlushDone = sqlite3VdbeMakeLabel(v);
danc3a20c12018-05-23 20:55:37 +00001504
dan31f56392018-05-24 21:10:57 +00001505 regStart = ++pParse->nMem;
1506 regEnd = ++pParse->nMem;
danc3a20c12018-05-23 20:55:37 +00001507
dandfa552f2018-06-02 21:04:28 +00001508 windowPartitionCache(pParse, p, pWInfo, regFlushPart, lblFlushPart, &regSize);
danc3a20c12018-05-23 20:55:37 +00001509
danc3a20c12018-05-23 20:55:37 +00001510 addrGoto = sqlite3VdbeAddOp0(v, OP_Goto);
1511
danc9a86682018-05-30 20:44:58 +00001512 /* Start of "flush_partition" */
dan31f56392018-05-24 21:10:57 +00001513 sqlite3VdbeResolveLabel(v, lblFlushPart);
danc3a20c12018-05-23 20:55:37 +00001514 sqlite3VdbeAddOp2(v, OP_Once, 0, sqlite3VdbeCurrentAddr(v)+3);
dan01e12292018-06-27 20:24:59 +00001515 VdbeCoverage(v);
dan31f56392018-05-24 21:10:57 +00001516 sqlite3VdbeAddOp2(v, OP_OpenDup, csrStart, pMWin->iEphCsr);
1517 sqlite3VdbeAddOp2(v, OP_OpenDup, csrEnd, pMWin->iEphCsr);
danc3a20c12018-05-23 20:55:37 +00001518
dan31f56392018-05-24 21:10:57 +00001519 /* If either regStart or regEnd are not non-negative integers, throw
dan99652dd2018-05-24 17:49:14 +00001520 ** an exception. */
1521 if( pMWin->pStart ){
dan31f56392018-05-24 21:10:57 +00001522 sqlite3ExprCode(pParse, pMWin->pStart, regStart);
1523 windowCheckFrameValue(pParse, regStart, 0);
dan99652dd2018-05-24 17:49:14 +00001524 }
1525 if( pMWin->pEnd ){
dan31f56392018-05-24 21:10:57 +00001526 sqlite3ExprCode(pParse, pMWin->pEnd, regEnd);
1527 windowCheckFrameValue(pParse, regEnd, 1);
dan99652dd2018-05-24 17:49:14 +00001528 }
danc3a20c12018-05-23 20:55:37 +00001529
danc9a86682018-05-30 20:44:58 +00001530 /* If this is "ROWS <expr1> FOLLOWING AND ROWS <expr2> FOLLOWING", do:
1531 **
dan26522d12018-06-11 18:16:51 +00001532 ** if( regEnd<regStart ){
1533 ** // The frame always consists of 0 rows
1534 ** regStart = regSize;
1535 ** }
danc9a86682018-05-30 20:44:58 +00001536 ** regEnd = regEnd - regStart;
1537 */
1538 if( pMWin->pEnd && pMWin->pStart && pMWin->eStart==TK_FOLLOWING ){
1539 assert( pMWin->eEnd==TK_FOLLOWING );
dan26522d12018-06-11 18:16:51 +00001540 sqlite3VdbeAddOp3(v, OP_Ge, regStart, sqlite3VdbeCurrentAddr(v)+2, regEnd);
dan01e12292018-06-27 20:24:59 +00001541 VdbeCoverage(v);
dan26522d12018-06-11 18:16:51 +00001542 sqlite3VdbeAddOp2(v, OP_Copy, regSize, regStart);
danc9a86682018-05-30 20:44:58 +00001543 sqlite3VdbeAddOp3(v, OP_Subtract, regStart, regEnd, regEnd);
1544 }
1545
dan26522d12018-06-11 18:16:51 +00001546 if( pMWin->pEnd && pMWin->pStart && pMWin->eEnd==TK_PRECEDING ){
1547 assert( pMWin->eStart==TK_PRECEDING );
1548 sqlite3VdbeAddOp3(v, OP_Le, regStart, sqlite3VdbeCurrentAddr(v)+3, regEnd);
dan01e12292018-06-27 20:24:59 +00001549 VdbeCoverage(v);
dan26522d12018-06-11 18:16:51 +00001550 sqlite3VdbeAddOp2(v, OP_Copy, regSize, regStart);
1551 sqlite3VdbeAddOp2(v, OP_Copy, regSize, regEnd);
1552 }
1553
danc9a86682018-05-30 20:44:58 +00001554 /* Initialize the accumulator register for each window function to NULL */
dan2e605682018-06-07 15:54:26 +00001555 regArg = windowInitAccum(pParse, pMWin);
danc3a20c12018-05-23 20:55:37 +00001556
dan31f56392018-05-24 21:10:57 +00001557 sqlite3VdbeAddOp2(v, OP_Rewind, pMWin->iEphCsr, lblFlushDone);
dan01e12292018-06-27 20:24:59 +00001558 VdbeCoverage(v);
dan31f56392018-05-24 21:10:57 +00001559 sqlite3VdbeAddOp2(v, OP_Rewind, csrStart, lblFlushDone);
dan01e12292018-06-27 20:24:59 +00001560 VdbeCoverageNeverTaken(v);
danc3a20c12018-05-23 20:55:37 +00001561 sqlite3VdbeChangeP5(v, 1);
dan31f56392018-05-24 21:10:57 +00001562 sqlite3VdbeAddOp2(v, OP_Rewind, csrEnd, lblFlushDone);
dan01e12292018-06-27 20:24:59 +00001563 VdbeCoverageNeverTaken(v);
danc3a20c12018-05-23 20:55:37 +00001564 sqlite3VdbeChangeP5(v, 1);
1565
1566 /* Invoke AggStep function for each window function using the row that
dan31f56392018-05-24 21:10:57 +00001567 ** csrEnd currently points to. Or, if csrEnd is already at EOF,
danc3a20c12018-05-23 20:55:37 +00001568 ** do nothing. */
dan31f56392018-05-24 21:10:57 +00001569 addrTop = sqlite3VdbeCurrentAddr(v);
1570 if( pMWin->eEnd==TK_PRECEDING ){
1571 addrIfPos1 = sqlite3VdbeAddOp3(v, OP_IfPos, regEnd, 0 , 1);
dan01e12292018-06-27 20:24:59 +00001572 VdbeCoverage(v);
danc3a20c12018-05-23 20:55:37 +00001573 }
dan31f56392018-05-24 21:10:57 +00001574 sqlite3VdbeAddOp2(v, OP_Next, csrEnd, sqlite3VdbeCurrentAddr(v)+2);
dan01e12292018-06-27 20:24:59 +00001575 VdbeCoverage(v);
dan31f56392018-05-24 21:10:57 +00001576 addr = sqlite3VdbeAddOp0(v, OP_Goto);
dandfa552f2018-06-02 21:04:28 +00001577 windowAggStep(pParse, pMWin, csrEnd, 0, regArg, regSize);
dan99652dd2018-05-24 17:49:14 +00001578 if( pMWin->eEnd==TK_UNBOUNDED ){
dan31f56392018-05-24 21:10:57 +00001579 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
1580 sqlite3VdbeJumpHere(v, addr);
1581 addrTop = sqlite3VdbeCurrentAddr(v);
dan99652dd2018-05-24 17:49:14 +00001582 }else{
dan31f56392018-05-24 21:10:57 +00001583 sqlite3VdbeJumpHere(v, addr);
1584 if( pMWin->eEnd==TK_PRECEDING ){
1585 sqlite3VdbeJumpHere(v, addrIfPos1);
1586 }
dan99652dd2018-05-24 17:49:14 +00001587 }
danc3a20c12018-05-23 20:55:37 +00001588
dan99652dd2018-05-24 17:49:14 +00001589 if( pMWin->eEnd==TK_FOLLOWING ){
dan31f56392018-05-24 21:10:57 +00001590 addrIfPos1 = sqlite3VdbeAddOp3(v, OP_IfPos, regEnd, 0 , 1);
dan01e12292018-06-27 20:24:59 +00001591 VdbeCoverage(v);
dan99652dd2018-05-24 17:49:14 +00001592 }
dane105dd72018-05-25 09:29:11 +00001593 if( pMWin->eStart==TK_FOLLOWING ){
1594 addrIfPos2 = sqlite3VdbeAddOp3(v, OP_IfPos, regStart, 0 , 1);
dan01e12292018-06-27 20:24:59 +00001595 VdbeCoverage(v);
dane105dd72018-05-25 09:29:11 +00001596 }
dand6f784e2018-05-28 18:30:45 +00001597 windowAggFinal(pParse, pMWin, 0);
danec891fd2018-06-06 20:51:02 +00001598 windowReturnOneRow(pParse, pMWin, regGosub, addrGosub);
danc3a20c12018-05-23 20:55:37 +00001599 sqlite3VdbeAddOp2(v, OP_Next, pMWin->iEphCsr, sqlite3VdbeCurrentAddr(v)+2);
dan01e12292018-06-27 20:24:59 +00001600 VdbeCoverage(v);
dan31f56392018-05-24 21:10:57 +00001601 sqlite3VdbeAddOp2(v, OP_Goto, 0, lblFlushDone);
dane105dd72018-05-25 09:29:11 +00001602 if( pMWin->eStart==TK_FOLLOWING ){
1603 sqlite3VdbeJumpHere(v, addrIfPos2);
1604 }
danc3a20c12018-05-23 20:55:37 +00001605
dane105dd72018-05-25 09:29:11 +00001606 if( pMWin->eStart==TK_CURRENT
1607 || pMWin->eStart==TK_PRECEDING
1608 || pMWin->eStart==TK_FOLLOWING
1609 ){
dan7262ca92018-07-02 12:07:32 +00001610 int lblSkipInverse = sqlite3VdbeMakeLabel(v);;
dan99652dd2018-05-24 17:49:14 +00001611 if( pMWin->eStart==TK_PRECEDING ){
dan7262ca92018-07-02 12:07:32 +00001612 sqlite3VdbeAddOp3(v, OP_IfPos, regStart, lblSkipInverse, 1);
dan01e12292018-06-27 20:24:59 +00001613 VdbeCoverage(v);
dan09590aa2018-05-25 20:30:17 +00001614 }
dan7262ca92018-07-02 12:07:32 +00001615 if( pMWin->eStart==TK_FOLLOWING ){
1616 sqlite3VdbeAddOp2(v, OP_Next, csrStart, sqlite3VdbeCurrentAddr(v)+2);
1617 VdbeCoverage(v);
1618 sqlite3VdbeAddOp2(v, OP_Goto, 0, lblSkipInverse);
1619 }else{
1620 sqlite3VdbeAddOp2(v, OP_Next, csrStart, sqlite3VdbeCurrentAddr(v)+1);
1621 VdbeCoverage(v);
dan99652dd2018-05-24 17:49:14 +00001622 }
dan7262ca92018-07-02 12:07:32 +00001623 windowAggStep(pParse, pMWin, csrStart, 1, regArg, regSize);
1624 sqlite3VdbeResolveLabel(v, lblSkipInverse);
danc3a20c12018-05-23 20:55:37 +00001625 }
dan99652dd2018-05-24 17:49:14 +00001626 if( pMWin->eEnd==TK_FOLLOWING ){
1627 sqlite3VdbeJumpHere(v, addrIfPos1);
1628 }
dan31f56392018-05-24 21:10:57 +00001629 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
danc3a20c12018-05-23 20:55:37 +00001630
1631 /* flush_partition_done: */
dan31f56392018-05-24 21:10:57 +00001632 sqlite3VdbeResolveLabel(v, lblFlushDone);
danc3a20c12018-05-23 20:55:37 +00001633 sqlite3VdbeAddOp1(v, OP_ResetSorter, pMWin->iEphCsr);
1634 sqlite3VdbeAddOp1(v, OP_Return, regFlushPart);
1635
1636 /* Jump to here to skip over flush_partition */
1637 sqlite3VdbeJumpHere(v, addrGoto);
1638}
1639
dan79d45442018-05-26 21:17:29 +00001640/*
dan54a9ab32018-06-14 14:27:05 +00001641** This function does the work of sqlite3WindowCodeStep() for cases that
1642** would normally be handled by windowCodeDefaultStep() when there are
1643** one or more built-in window-functions that require the entire partition
1644** to be cached in a temp table before any rows can be returned. Additionally.
1645** "RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING" is always handled by
1646** this function.
1647**
1648** Pseudo-code corresponding to the VM code generated by this function
1649** for each type of window follows.
1650**
dan79d45442018-05-26 21:17:29 +00001651** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
1652**
danf690b572018-06-01 21:00:08 +00001653** flush_partition:
1654** Once {
1655** OpenDup (iEphCsr -> csrLead)
1656** }
1657** Integer ctr 0
1658** foreach row (csrLead){
1659** if( new peer ){
1660** AggFinal (xValue)
1661** for(i=0; i<ctr; i++){
1662** Gosub addrGosub
1663** Next iEphCsr
1664** }
1665** Integer ctr 0
1666** }
1667** AggStep (csrLead)
1668** Incr ctr
1669** }
1670**
1671** AggFinal (xFinalize)
1672** for(i=0; i<ctr; i++){
1673** Gosub addrGosub
1674** Next iEphCsr
1675** }
1676**
1677** ResetSorter (csr)
1678** Return
1679**
1680** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
dan54a9ab32018-06-14 14:27:05 +00001681**
1682** As above, except that the "if( new peer )" branch is always taken.
1683**
danf690b572018-06-01 21:00:08 +00001684** RANGE BETWEEN CURRENT ROW AND CURRENT ROW
dan54a9ab32018-06-14 14:27:05 +00001685**
1686** As above, except that each of the for() loops becomes:
1687**
1688** for(i=0; i<ctr; i++){
1689** Gosub addrGosub
drh8f26da62018-07-05 21:22:57 +00001690** AggInverse (iEphCsr)
dan54a9ab32018-06-14 14:27:05 +00001691** Next iEphCsr
1692** }
1693**
1694** RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
1695**
1696** flush_partition:
1697** Once {
1698** OpenDup (iEphCsr -> csrLead)
1699** }
1700** foreach row (csrLead) {
1701** AggStep (csrLead)
1702** }
1703** foreach row (iEphCsr) {
1704** Gosub addrGosub
1705** }
1706**
1707** RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
1708**
1709** flush_partition:
1710** Once {
1711** OpenDup (iEphCsr -> csrLead)
1712** }
1713** foreach row (csrLead){
1714** AggStep (csrLead)
1715** }
1716** Rewind (csrLead)
1717** Integer ctr 0
1718** foreach row (csrLead){
1719** if( new peer ){
1720** AggFinal (xValue)
1721** for(i=0; i<ctr; i++){
1722** Gosub addrGosub
drh8f26da62018-07-05 21:22:57 +00001723** AggInverse (iEphCsr)
dan54a9ab32018-06-14 14:27:05 +00001724** Next iEphCsr
1725** }
1726** Integer ctr 0
1727** }
1728** Incr ctr
1729** }
1730**
1731** AggFinal (xFinalize)
1732** for(i=0; i<ctr; i++){
1733** Gosub addrGosub
1734** Next iEphCsr
1735** }
1736**
1737** ResetSorter (csr)
1738** Return
danf690b572018-06-01 21:00:08 +00001739*/
1740static void windowCodeCacheStep(
1741 Parse *pParse,
1742 Select *p,
1743 WhereInfo *pWInfo,
1744 int regGosub,
1745 int addrGosub
1746){
1747 Window *pMWin = p->pWin;
1748 Vdbe *v = sqlite3GetVdbe(pParse);
danf690b572018-06-01 21:00:08 +00001749 int k;
1750 int addr;
1751 ExprList *pPart = pMWin->pPartition;
1752 ExprList *pOrderBy = pMWin->pOrderBy;
dan54a9ab32018-06-14 14:27:05 +00001753 int nPeer = pOrderBy ? pOrderBy->nExpr : 0;
danf690b572018-06-01 21:00:08 +00001754 int regNewPeer;
1755
1756 int addrGoto; /* Address of Goto used to jump flush_par.. */
dan13078ca2018-06-13 20:29:38 +00001757 int addrNext; /* Jump here for next iteration of loop */
danf690b572018-06-01 21:00:08 +00001758 int regFlushPart;
1759 int lblFlushPart;
1760 int csrLead;
1761 int regCtr;
1762 int regArg; /* Register array to martial function args */
dandfa552f2018-06-02 21:04:28 +00001763 int regSize;
dan13078ca2018-06-13 20:29:38 +00001764 int lblEmpty;
dan54a9ab32018-06-14 14:27:05 +00001765 int bReverse = pMWin->pOrderBy && pMWin->eStart==TK_CURRENT
1766 && pMWin->eEnd==TK_UNBOUNDED;
danf690b572018-06-01 21:00:08 +00001767
1768 assert( (pMWin->eStart==TK_UNBOUNDED && pMWin->eEnd==TK_CURRENT)
danec891fd2018-06-06 20:51:02 +00001769 || (pMWin->eStart==TK_UNBOUNDED && pMWin->eEnd==TK_UNBOUNDED)
1770 || (pMWin->eStart==TK_CURRENT && pMWin->eEnd==TK_CURRENT)
dan13078ca2018-06-13 20:29:38 +00001771 || (pMWin->eStart==TK_CURRENT && pMWin->eEnd==TK_UNBOUNDED)
danf690b572018-06-01 21:00:08 +00001772 );
1773
dan13078ca2018-06-13 20:29:38 +00001774 lblEmpty = sqlite3VdbeMakeLabel(v);
danf690b572018-06-01 21:00:08 +00001775 regNewPeer = pParse->nMem+1;
1776 pParse->nMem += nPeer;
1777
1778 /* Allocate register and label for the "flush_partition" sub-routine. */
1779 regFlushPart = ++pParse->nMem;
1780 lblFlushPart = sqlite3VdbeMakeLabel(v);
1781
1782 csrLead = pParse->nTab++;
1783 regCtr = ++pParse->nMem;
1784
dandfa552f2018-06-02 21:04:28 +00001785 windowPartitionCache(pParse, p, pWInfo, regFlushPart, lblFlushPart, &regSize);
danf690b572018-06-01 21:00:08 +00001786 addrGoto = sqlite3VdbeAddOp0(v, OP_Goto);
1787
1788 /* Start of "flush_partition" */
1789 sqlite3VdbeResolveLabel(v, lblFlushPart);
1790 sqlite3VdbeAddOp2(v, OP_Once, 0, sqlite3VdbeCurrentAddr(v)+2);
dan01e12292018-06-27 20:24:59 +00001791 VdbeCoverage(v);
danf690b572018-06-01 21:00:08 +00001792 sqlite3VdbeAddOp2(v, OP_OpenDup, csrLead, pMWin->iEphCsr);
1793
1794 /* Initialize the accumulator register for each window function to NULL */
dan2e605682018-06-07 15:54:26 +00001795 regArg = windowInitAccum(pParse, pMWin);
danf690b572018-06-01 21:00:08 +00001796
1797 sqlite3VdbeAddOp2(v, OP_Integer, 0, regCtr);
dan13078ca2018-06-13 20:29:38 +00001798 sqlite3VdbeAddOp2(v, OP_Rewind, csrLead, lblEmpty);
dan01e12292018-06-27 20:24:59 +00001799 VdbeCoverage(v);
dan13078ca2018-06-13 20:29:38 +00001800 sqlite3VdbeAddOp2(v, OP_Rewind, pMWin->iEphCsr, lblEmpty);
dan01e12292018-06-27 20:24:59 +00001801 VdbeCoverageNeverTaken(v);
danf690b572018-06-01 21:00:08 +00001802
dan13078ca2018-06-13 20:29:38 +00001803 if( bReverse ){
1804 int addr = sqlite3VdbeCurrentAddr(v);
1805 windowAggStep(pParse, pMWin, csrLead, 0, regArg, regSize);
1806 sqlite3VdbeAddOp2(v, OP_Next, csrLead, addr);
dan01e12292018-06-27 20:24:59 +00001807 VdbeCoverage(v);
dan13078ca2018-06-13 20:29:38 +00001808 sqlite3VdbeAddOp2(v, OP_Rewind, csrLead, lblEmpty);
dan01e12292018-06-27 20:24:59 +00001809 VdbeCoverageNeverTaken(v);
dan13078ca2018-06-13 20:29:38 +00001810 }
1811 addrNext = sqlite3VdbeCurrentAddr(v);
1812
1813 if( pOrderBy && (pMWin->eEnd==TK_CURRENT || pMWin->eStart==TK_CURRENT) ){
1814 int bCurrent = (pMWin->eStart==TK_CURRENT);
danec891fd2018-06-06 20:51:02 +00001815 int addrJump = 0; /* Address of OP_Jump below */
1816 if( pMWin->eType==TK_RANGE ){
1817 int iOff = pMWin->nBufferCol + (pPart ? pPart->nExpr : 0);
1818 int regPeer = pMWin->regPart + (pPart ? pPart->nExpr : 0);
1819 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pOrderBy, 0, 0);
1820 for(k=0; k<nPeer; k++){
1821 sqlite3VdbeAddOp3(v, OP_Column, csrLead, iOff+k, regNewPeer+k);
1822 }
1823 addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPeer, regPeer, nPeer);
1824 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
1825 addrJump = sqlite3VdbeAddOp3(v, OP_Jump, addr+2, 0, addr+2);
dan01e12292018-06-27 20:24:59 +00001826 VdbeCoverage(v);
danec891fd2018-06-06 20:51:02 +00001827 sqlite3VdbeAddOp3(v, OP_Copy, regNewPeer, regPeer, nPeer-1);
danf690b572018-06-01 21:00:08 +00001828 }
1829
dan13078ca2018-06-13 20:29:38 +00001830 windowReturnRows(pParse, pMWin, regCtr, regGosub, addrGosub,
danec891fd2018-06-06 20:51:02 +00001831 (bCurrent ? regArg : 0), (bCurrent ? regSize : 0)
1832 );
1833 if( addrJump ) sqlite3VdbeJumpHere(v, addrJump);
danf690b572018-06-01 21:00:08 +00001834 }
1835
dan13078ca2018-06-13 20:29:38 +00001836 if( bReverse==0 ){
1837 windowAggStep(pParse, pMWin, csrLead, 0, regArg, regSize);
1838 }
danf690b572018-06-01 21:00:08 +00001839 sqlite3VdbeAddOp2(v, OP_AddImm, regCtr, 1);
dan13078ca2018-06-13 20:29:38 +00001840 sqlite3VdbeAddOp2(v, OP_Next, csrLead, addrNext);
dan01e12292018-06-27 20:24:59 +00001841 VdbeCoverage(v);
danf690b572018-06-01 21:00:08 +00001842
dan13078ca2018-06-13 20:29:38 +00001843 windowReturnRows(pParse, pMWin, regCtr, regGosub, addrGosub, 0, 0);
danf690b572018-06-01 21:00:08 +00001844
dan13078ca2018-06-13 20:29:38 +00001845 sqlite3VdbeResolveLabel(v, lblEmpty);
danf690b572018-06-01 21:00:08 +00001846 sqlite3VdbeAddOp1(v, OP_ResetSorter, pMWin->iEphCsr);
1847 sqlite3VdbeAddOp1(v, OP_Return, regFlushPart);
1848
1849 /* Jump to here to skip over flush_partition */
1850 sqlite3VdbeJumpHere(v, addrGoto);
1851}
1852
1853
1854/*
1855** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
1856**
dan79d45442018-05-26 21:17:29 +00001857** ...
1858** if( new partition ){
1859** AggFinal (xFinalize)
1860** Gosub addrGosub
1861** ResetSorter eph-table
1862** }
1863** else if( new peer ){
1864** AggFinal (xValue)
1865** Gosub addrGosub
1866** ResetSorter eph-table
1867** }
1868** AggStep
1869** Insert (record into eph-table)
1870** sqlite3WhereEnd()
1871** AggFinal (xFinalize)
1872** Gosub addrGosub
danf690b572018-06-01 21:00:08 +00001873**
1874** RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
1875**
1876** As above, except take no action for a "new peer". Invoke
1877** the sub-routine once only for each partition.
1878**
1879** RANGE BETWEEN CURRENT ROW AND CURRENT ROW
1880**
1881** As above, except that the "new peer" condition is handled in the
1882** same way as "new partition" (so there is no "else if" block).
1883**
1884** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
1885**
1886** As above, except assume every row is a "new peer".
dan79d45442018-05-26 21:17:29 +00001887*/
danc3a20c12018-05-23 20:55:37 +00001888static void windowCodeDefaultStep(
1889 Parse *pParse,
1890 Select *p,
1891 WhereInfo *pWInfo,
1892 int regGosub,
1893 int addrGosub
1894){
1895 Window *pMWin = p->pWin;
1896 Vdbe *v = sqlite3GetVdbe(pParse);
danc3a20c12018-05-23 20:55:37 +00001897 int k;
1898 int iSubCsr = p->pSrc->a[0].iCursor;
1899 int nSub = p->pSrc->a[0].pTab->nCol;
1900 int reg = pParse->nMem+1;
1901 int regRecord = reg+nSub;
1902 int regRowid = regRecord+1;
1903 int addr;
dand6f784e2018-05-28 18:30:45 +00001904 ExprList *pPart = pMWin->pPartition;
1905 ExprList *pOrderBy = pMWin->pOrderBy;
danc3a20c12018-05-23 20:55:37 +00001906
dan79d45442018-05-26 21:17:29 +00001907 assert( pMWin->eType==TK_RANGE
1908 || (pMWin->eStart==TK_UNBOUNDED && pMWin->eEnd==TK_CURRENT)
1909 );
1910
dand6f784e2018-05-28 18:30:45 +00001911 assert( (pMWin->eStart==TK_UNBOUNDED && pMWin->eEnd==TK_CURRENT)
1912 || (pMWin->eStart==TK_UNBOUNDED && pMWin->eEnd==TK_UNBOUNDED)
1913 || (pMWin->eStart==TK_CURRENT && pMWin->eEnd==TK_CURRENT)
1914 || (pMWin->eStart==TK_CURRENT && pMWin->eEnd==TK_UNBOUNDED && !pOrderBy)
1915 );
1916
1917 if( pMWin->eEnd==TK_UNBOUNDED ){
1918 pOrderBy = 0;
1919 }
1920
danc3a20c12018-05-23 20:55:37 +00001921 pParse->nMem += nSub + 2;
1922
1923 /* Martial the row returned by the sub-select into an array of
1924 ** registers. */
1925 for(k=0; k<nSub; k++){
1926 sqlite3VdbeAddOp3(v, OP_Column, iSubCsr, k, reg+k);
1927 }
1928
1929 /* Check if this is the start of a new partition or peer group. */
dand6f784e2018-05-28 18:30:45 +00001930 if( pPart || pOrderBy ){
danc3a20c12018-05-23 20:55:37 +00001931 int nPart = (pPart ? pPart->nExpr : 0);
danc3a20c12018-05-23 20:55:37 +00001932 int addrGoto = 0;
1933 int addrJump = 0;
dand6f784e2018-05-28 18:30:45 +00001934 int nPeer = (pOrderBy ? pOrderBy->nExpr : 0);
danc3a20c12018-05-23 20:55:37 +00001935
1936 if( pPart ){
1937 int regNewPart = reg + pMWin->nBufferCol;
1938 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pPart, 0, 0);
1939 addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPart, pMWin->regPart,nPart);
1940 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
1941 addrJump = sqlite3VdbeAddOp3(v, OP_Jump, addr+2, 0, addr+2);
dan01e12292018-06-27 20:24:59 +00001942 VdbeCoverage(v);
dand6f784e2018-05-28 18:30:45 +00001943 windowAggFinal(pParse, pMWin, 1);
danc3a20c12018-05-23 20:55:37 +00001944 if( pOrderBy ){
1945 addrGoto = sqlite3VdbeAddOp0(v, OP_Goto);
1946 }
1947 }
1948
1949 if( pOrderBy ){
1950 int regNewPeer = reg + pMWin->nBufferCol + nPart;
1951 int regPeer = pMWin->regPart + nPart;
1952
danc3a20c12018-05-23 20:55:37 +00001953 if( addrJump ) sqlite3VdbeJumpHere(v, addrJump);
dan79d45442018-05-26 21:17:29 +00001954 if( pMWin->eType==TK_RANGE ){
1955 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pOrderBy, 0, 0);
1956 addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPeer, regPeer, nPeer);
1957 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
1958 addrJump = sqlite3VdbeAddOp3(v, OP_Jump, addr+2, 0, addr+2);
dan01e12292018-06-27 20:24:59 +00001959 VdbeCoverage(v);
dan79d45442018-05-26 21:17:29 +00001960 }else{
1961 addrJump = 0;
1962 }
dand6f784e2018-05-28 18:30:45 +00001963 windowAggFinal(pParse, pMWin, pMWin->eStart==TK_CURRENT);
danc3a20c12018-05-23 20:55:37 +00001964 if( addrGoto ) sqlite3VdbeJumpHere(v, addrGoto);
1965 }
1966
dandacf1de2018-06-08 16:11:55 +00001967 sqlite3VdbeAddOp2(v, OP_Rewind, pMWin->iEphCsr,sqlite3VdbeCurrentAddr(v)+3);
dan01e12292018-06-27 20:24:59 +00001968 VdbeCoverage(v);
danc3a20c12018-05-23 20:55:37 +00001969 sqlite3VdbeAddOp2(v, OP_Gosub, regGosub, addrGosub);
dandacf1de2018-06-08 16:11:55 +00001970 sqlite3VdbeAddOp2(v, OP_Next, pMWin->iEphCsr, sqlite3VdbeCurrentAddr(v)-1);
dan01e12292018-06-27 20:24:59 +00001971 VdbeCoverage(v);
dandacf1de2018-06-08 16:11:55 +00001972
danc3a20c12018-05-23 20:55:37 +00001973 sqlite3VdbeAddOp1(v, OP_ResetSorter, pMWin->iEphCsr);
1974 sqlite3VdbeAddOp3(
1975 v, OP_Copy, reg+pMWin->nBufferCol, pMWin->regPart, nPart+nPeer-1
1976 );
1977
dan79d45442018-05-26 21:17:29 +00001978 if( addrJump ) sqlite3VdbeJumpHere(v, addrJump);
danc3a20c12018-05-23 20:55:37 +00001979 }
1980
1981 /* Invoke step function for window functions */
dandfa552f2018-06-02 21:04:28 +00001982 windowAggStep(pParse, pMWin, -1, 0, reg, 0);
danc3a20c12018-05-23 20:55:37 +00001983
1984 /* Buffer the current row in the ephemeral table. */
1985 if( pMWin->nBufferCol>0 ){
1986 sqlite3VdbeAddOp3(v, OP_MakeRecord, reg, pMWin->nBufferCol, regRecord);
1987 }else{
1988 sqlite3VdbeAddOp2(v, OP_Blob, 0, regRecord);
1989 sqlite3VdbeAppendP4(v, (void*)"", 0);
1990 }
1991 sqlite3VdbeAddOp2(v, OP_NewRowid, pMWin->iEphCsr, regRowid);
1992 sqlite3VdbeAddOp3(v, OP_Insert, pMWin->iEphCsr, regRecord, regRowid);
1993
1994 /* End the database scan loop. */
1995 sqlite3WhereEnd(pWInfo);
1996
dand6f784e2018-05-28 18:30:45 +00001997 windowAggFinal(pParse, pMWin, 1);
dandacf1de2018-06-08 16:11:55 +00001998 sqlite3VdbeAddOp2(v, OP_Rewind, pMWin->iEphCsr,sqlite3VdbeCurrentAddr(v)+3);
dan01e12292018-06-27 20:24:59 +00001999 VdbeCoverage(v);
danc3a20c12018-05-23 20:55:37 +00002000 sqlite3VdbeAddOp2(v, OP_Gosub, regGosub, addrGosub);
dandacf1de2018-06-08 16:11:55 +00002001 sqlite3VdbeAddOp2(v, OP_Next, pMWin->iEphCsr, sqlite3VdbeCurrentAddr(v)-1);
dan01e12292018-06-27 20:24:59 +00002002 VdbeCoverage(v);
danc3a20c12018-05-23 20:55:37 +00002003}
2004
dan13078ca2018-06-13 20:29:38 +00002005/*
2006** Allocate and return a duplicate of the Window object indicated by the
2007** third argument. Set the Window.pOwner field of the new object to
2008** pOwner.
2009*/
dan2a11bb22018-06-11 20:50:25 +00002010Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p){
dandacf1de2018-06-08 16:11:55 +00002011 Window *pNew = 0;
2012 if( p ){
2013 pNew = sqlite3DbMallocZero(db, sizeof(Window));
2014 if( pNew ){
danc95f38d2018-06-18 20:34:43 +00002015 pNew->zName = sqlite3DbStrDup(db, p->zName);
dandacf1de2018-06-08 16:11:55 +00002016 pNew->pFilter = sqlite3ExprDup(db, p->pFilter, 0);
2017 pNew->pPartition = sqlite3ExprListDup(db, p->pPartition, 0);
2018 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, 0);
2019 pNew->eType = p->eType;
2020 pNew->eEnd = p->eEnd;
2021 pNew->eStart = p->eStart;
dan303451a2018-06-14 20:52:08 +00002022 pNew->pStart = sqlite3ExprDup(db, p->pStart, 0);
2023 pNew->pEnd = sqlite3ExprDup(db, p->pEnd, 0);
dan2a11bb22018-06-11 20:50:25 +00002024 pNew->pOwner = pOwner;
dandacf1de2018-06-08 16:11:55 +00002025 }
2026 }
2027 return pNew;
2028}
danc3a20c12018-05-23 20:55:37 +00002029
danf9eae182018-05-21 19:45:11 +00002030/*
danc95f38d2018-06-18 20:34:43 +00002031** Return a copy of the linked list of Window objects passed as the
2032** second argument.
2033*/
2034Window *sqlite3WindowListDup(sqlite3 *db, Window *p){
2035 Window *pWin;
2036 Window *pRet = 0;
2037 Window **pp = &pRet;
2038
2039 for(pWin=p; pWin; pWin=pWin->pNextWin){
2040 *pp = sqlite3WindowDup(db, 0, pWin);
2041 if( *pp==0 ) break;
2042 pp = &((*pp)->pNextWin);
2043 }
2044
2045 return pRet;
2046}
2047
2048/*
dan2a11bb22018-06-11 20:50:25 +00002049** sqlite3WhereBegin() has already been called for the SELECT statement
2050** passed as the second argument when this function is invoked. It generates
2051** code to populate the Window.regResult register for each window function and
2052** invoke the sub-routine at instruction addrGosub once for each row.
2053** This function calls sqlite3WhereEnd() before returning.
danf9eae182018-05-21 19:45:11 +00002054*/
2055void sqlite3WindowCodeStep(
dan2a11bb22018-06-11 20:50:25 +00002056 Parse *pParse, /* Parse context */
2057 Select *p, /* Rewritten SELECT statement */
2058 WhereInfo *pWInfo, /* Context returned by sqlite3WhereBegin() */
2059 int regGosub, /* Register for OP_Gosub */
2060 int addrGosub /* OP_Gosub here to return each row */
danf9eae182018-05-21 19:45:11 +00002061){
danf9eae182018-05-21 19:45:11 +00002062 Window *pMWin = p->pWin;
danf9eae182018-05-21 19:45:11 +00002063
dan54a9ab32018-06-14 14:27:05 +00002064 /* There are three different functions that may be used to do the work
2065 ** of this one, depending on the window frame and the specific built-in
2066 ** window functions used (if any).
2067 **
2068 ** windowCodeRowExprStep() handles all "ROWS" window frames, except for:
dan26522d12018-06-11 18:16:51 +00002069 **
dan13078ca2018-06-13 20:29:38 +00002070 ** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
dan54a9ab32018-06-14 14:27:05 +00002071 **
2072 ** The exception is because windowCodeRowExprStep() implements all window
2073 ** frame types by caching the entire partition in a temp table, and
2074 ** "ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW" is easy enough to
2075 ** implement without such a cache.
2076 **
2077 ** windowCodeCacheStep() is used for:
2078 **
2079 ** RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
2080 **
2081 ** It is also used for anything not handled by windowCodeRowExprStep()
2082 ** that invokes a built-in window function that requires the entire
2083 ** partition to be cached in a temp table before any rows are returned
2084 ** (e.g. nth_value() or percent_rank()).
2085 **
2086 ** Finally, assuming there is no built-in window function that requires
2087 ** the partition to be cached, windowCodeDefaultStep() is used for:
2088 **
2089 ** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
2090 ** RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
2091 ** RANGE BETWEEN CURRENT ROW AND CURRENT ROW
2092 ** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
2093 **
2094 ** windowCodeDefaultStep() is the only one of the three functions that
2095 ** does not cache each partition in a temp table before beginning to
2096 ** return rows.
dan26522d12018-06-11 18:16:51 +00002097 */
dan54a9ab32018-06-14 14:27:05 +00002098 if( pMWin->eType==TK_ROWS
2099 && (pMWin->eStart!=TK_UNBOUNDED||pMWin->eEnd!=TK_CURRENT||!pMWin->pOrderBy)
dan09590aa2018-05-25 20:30:17 +00002100 ){
danc3a20c12018-05-23 20:55:37 +00002101 windowCodeRowExprStep(pParse, p, pWInfo, regGosub, addrGosub);
dan13078ca2018-06-13 20:29:38 +00002102 }else{
2103 Window *pWin;
dan54a9ab32018-06-14 14:27:05 +00002104 int bCache = 0; /* True to use CacheStep() */
danf9eae182018-05-21 19:45:11 +00002105
dan54a9ab32018-06-14 14:27:05 +00002106 if( pMWin->eStart==TK_CURRENT && pMWin->eEnd==TK_UNBOUNDED ){
dan13078ca2018-06-13 20:29:38 +00002107 bCache = 1;
2108 }else{
dan13078ca2018-06-13 20:29:38 +00002109 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
2110 FuncDef *pFunc = pWin->pFunc;
2111 if( (pFunc->funcFlags & SQLITE_FUNC_WINDOW_SIZE)
dan54a9ab32018-06-14 14:27:05 +00002112 || (pFunc->xSFunc==nth_valueStepFunc)
2113 || (pFunc->xSFunc==first_valueStepFunc)
2114 || (pFunc->xSFunc==leadStepFunc)
2115 || (pFunc->xSFunc==lagStepFunc)
2116 ){
dan13078ca2018-06-13 20:29:38 +00002117 bCache = 1;
2118 break;
2119 }
2120 }
2121 }
2122
2123 /* Otherwise, call windowCodeDefaultStep(). */
2124 if( bCache ){
dandfa552f2018-06-02 21:04:28 +00002125 windowCodeCacheStep(pParse, p, pWInfo, regGosub, addrGosub);
dan13078ca2018-06-13 20:29:38 +00002126 }else{
2127 windowCodeDefaultStep(pParse, p, pWInfo, regGosub, addrGosub);
dandfa552f2018-06-02 21:04:28 +00002128 }
danf690b572018-06-01 21:00:08 +00002129 }
danf9eae182018-05-21 19:45:11 +00002130}
2131
dan67a9b8e2018-06-22 20:51:35 +00002132#endif /* SQLITE_OMIT_WINDOWFUNC */