blob: 094f6eaa37bf9f4210f2a50c0837c30aa5869e6a [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));
drh5d6374f2018-07-10 23:31:17 +0000153 if( p ) (*p)++;
drhc7bf5712018-07-09 22:49:01 +0000154 UNUSED_PARAMETER(nArg);
155 UNUSED_PARAMETER(apArg);
dandfa552f2018-06-02 21:04:28 +0000156}
dandfa552f2018-06-02 21:04:28 +0000157static void row_numberValueFunc(sqlite3_context *pCtx){
158 i64 *p = (i64*)sqlite3_aggregate_context(pCtx, sizeof(*p));
159 sqlite3_result_int64(pCtx, (p ? *p : 0));
160}
161
162/*
dan2a11bb22018-06-11 20:50:25 +0000163** Context object type used by rank(), dense_rank(), percent_rank() and
164** cume_dist().
dandfa552f2018-06-02 21:04:28 +0000165*/
166struct CallCount {
167 i64 nValue;
168 i64 nStep;
169 i64 nTotal;
170};
171
172/*
dan9c277582018-06-20 09:23:49 +0000173** Implementation of built-in window function dense_rank(). Assumes that
174** the window frame has been set to:
175**
176** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
dandfa552f2018-06-02 21:04:28 +0000177*/
178static void dense_rankStepFunc(
179 sqlite3_context *pCtx,
180 int nArg,
181 sqlite3_value **apArg
182){
183 struct CallCount *p;
184 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
drh5d6374f2018-07-10 23:31:17 +0000185 if( p ) p->nStep = 1;
drhc7bf5712018-07-09 22:49:01 +0000186 UNUSED_PARAMETER(nArg);
187 UNUSED_PARAMETER(apArg);
dandfa552f2018-06-02 21:04:28 +0000188}
dandfa552f2018-06-02 21:04:28 +0000189static void dense_rankValueFunc(sqlite3_context *pCtx){
190 struct CallCount *p;
191 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
192 if( p ){
193 if( p->nStep ){
194 p->nValue++;
195 p->nStep = 0;
196 }
197 sqlite3_result_int64(pCtx, p->nValue);
198 }
199}
200
201/*
dan9c277582018-06-20 09:23:49 +0000202** Implementation of built-in window function rank(). Assumes that
203** the window frame has been set to:
204**
205** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
dandfa552f2018-06-02 21:04:28 +0000206*/
207static void rankStepFunc(
208 sqlite3_context *pCtx,
209 int nArg,
210 sqlite3_value **apArg
211){
212 struct CallCount *p;
213 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
drh5d6374f2018-07-10 23:31:17 +0000214 if( p ){
dandfa552f2018-06-02 21:04:28 +0000215 p->nStep++;
216 if( p->nValue==0 ){
217 p->nValue = p->nStep;
218 }
219 }
drhc7bf5712018-07-09 22:49:01 +0000220 UNUSED_PARAMETER(nArg);
221 UNUSED_PARAMETER(apArg);
dandfa552f2018-06-02 21:04:28 +0000222}
dandfa552f2018-06-02 21:04:28 +0000223static void rankValueFunc(sqlite3_context *pCtx){
224 struct CallCount *p;
225 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
226 if( p ){
227 sqlite3_result_int64(pCtx, p->nValue);
228 p->nValue = 0;
229 }
230}
231
232/*
dan9c277582018-06-20 09:23:49 +0000233** Implementation of built-in window function percent_rank(). Assumes that
234** the window frame has been set to:
235**
dancc7a8502019-03-11 19:50:54 +0000236** GROUPS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
dandfa552f2018-06-02 21:04:28 +0000237*/
238static void percent_rankStepFunc(
239 sqlite3_context *pCtx,
240 int nArg,
241 sqlite3_value **apArg
242){
243 struct CallCount *p;
dancc7a8502019-03-11 19:50:54 +0000244 UNUSED_PARAMETER(nArg); assert( nArg==0 );
dandfa552f2018-06-02 21:04:28 +0000245 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
drh5d6374f2018-07-10 23:31:17 +0000246 if( p ){
dancc7a8502019-03-11 19:50:54 +0000247 p->nTotal++;
dandfa552f2018-06-02 21:04:28 +0000248 }
249}
dancc7a8502019-03-11 19:50:54 +0000250static void percent_rankInvFunc(
251 sqlite3_context *pCtx,
252 int nArg,
253 sqlite3_value **apArg
254){
255 struct CallCount *p;
256 UNUSED_PARAMETER(nArg); assert( nArg==0 );
257 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
258 p->nStep++;
259}
dandfa552f2018-06-02 21:04:28 +0000260static void percent_rankValueFunc(sqlite3_context *pCtx){
261 struct CallCount *p;
262 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
263 if( p ){
dancc7a8502019-03-11 19:50:54 +0000264 p->nValue = p->nStep;
dandfa552f2018-06-02 21:04:28 +0000265 if( p->nTotal>1 ){
dancc7a8502019-03-11 19:50:54 +0000266 double r = (double)p->nValue / (double)(p->nTotal-1);
dandfa552f2018-06-02 21:04:28 +0000267 sqlite3_result_double(pCtx, r);
268 }else{
danb7306f62018-06-21 19:20:39 +0000269 sqlite3_result_double(pCtx, 0.0);
dandfa552f2018-06-02 21:04:28 +0000270 }
dandfa552f2018-06-02 21:04:28 +0000271 }
272}
dancc7a8502019-03-11 19:50:54 +0000273#define percent_rankFinalizeFunc percent_rankValueFunc
dandfa552f2018-06-02 21:04:28 +0000274
dan9c277582018-06-20 09:23:49 +0000275/*
276** Implementation of built-in window function cume_dist(). Assumes that
277** the window frame has been set to:
278**
dancc7a8502019-03-11 19:50:54 +0000279** GROUPS BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING
dan9c277582018-06-20 09:23:49 +0000280*/
danf1abe362018-06-04 08:22:09 +0000281static void cume_distStepFunc(
282 sqlite3_context *pCtx,
283 int nArg,
284 sqlite3_value **apArg
285){
286 struct CallCount *p;
dancc7a8502019-03-11 19:50:54 +0000287 UNUSED_PARAMETER(nArg); assert( nArg==0 );
danf1abe362018-06-04 08:22:09 +0000288 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
drh5d6374f2018-07-10 23:31:17 +0000289 if( p ){
dancc7a8502019-03-11 19:50:54 +0000290 p->nTotal++;
danf1abe362018-06-04 08:22:09 +0000291 }
292}
dancc7a8502019-03-11 19:50:54 +0000293static void cume_distInvFunc(
294 sqlite3_context *pCtx,
295 int nArg,
296 sqlite3_value **apArg
297){
298 struct CallCount *p;
299 UNUSED_PARAMETER(nArg); assert( nArg==0 );
300 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
301 p->nStep++;
302}
danf1abe362018-06-04 08:22:09 +0000303static void cume_distValueFunc(sqlite3_context *pCtx){
304 struct CallCount *p;
305 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
dan660af932018-06-18 16:55:22 +0000306 if( p && p->nTotal ){
danf1abe362018-06-04 08:22:09 +0000307 double r = (double)(p->nStep) / (double)(p->nTotal);
308 sqlite3_result_double(pCtx, r);
309 }
310}
dancc7a8502019-03-11 19:50:54 +0000311#define cume_distFinalizeFunc cume_distValueFunc
danf1abe362018-06-04 08:22:09 +0000312
dan2a11bb22018-06-11 20:50:25 +0000313/*
314** Context object for ntile() window function.
315*/
dan6bc5c9e2018-06-04 18:55:11 +0000316struct NtileCtx {
317 i64 nTotal; /* Total rows in partition */
318 i64 nParam; /* Parameter passed to ntile(N) */
319 i64 iRow; /* Current row */
320};
321
322/*
323** Implementation of ntile(). This assumes that the window frame has
324** been coerced to:
325**
dancc7a8502019-03-11 19:50:54 +0000326** ROWS CURRENT ROW AND UNBOUNDED FOLLOWING
dan6bc5c9e2018-06-04 18:55:11 +0000327*/
328static void ntileStepFunc(
329 sqlite3_context *pCtx,
330 int nArg,
331 sqlite3_value **apArg
332){
333 struct NtileCtx *p;
dancc7a8502019-03-11 19:50:54 +0000334 assert( nArg==1 ); UNUSED_PARAMETER(nArg);
dan6bc5c9e2018-06-04 18:55:11 +0000335 p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
drh5d6374f2018-07-10 23:31:17 +0000336 if( p ){
dan6bc5c9e2018-06-04 18:55:11 +0000337 if( p->nTotal==0 ){
338 p->nParam = sqlite3_value_int64(apArg[0]);
dan6bc5c9e2018-06-04 18:55:11 +0000339 if( p->nParam<=0 ){
340 sqlite3_result_error(
341 pCtx, "argument of ntile must be a positive integer", -1
342 );
343 }
344 }
dancc7a8502019-03-11 19:50:54 +0000345 p->nTotal++;
dan6bc5c9e2018-06-04 18:55:11 +0000346 }
347}
dancc7a8502019-03-11 19:50:54 +0000348static void ntileInvFunc(
349 sqlite3_context *pCtx,
350 int nArg,
351 sqlite3_value **apArg
352){
353 struct NtileCtx *p;
354 assert( nArg==1 ); UNUSED_PARAMETER(nArg);
355 p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
356 p->iRow++;
357}
dan6bc5c9e2018-06-04 18:55:11 +0000358static void ntileValueFunc(sqlite3_context *pCtx){
359 struct NtileCtx *p;
360 p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
361 if( p && p->nParam>0 ){
362 int nSize = (p->nTotal / p->nParam);
363 if( nSize==0 ){
dancc7a8502019-03-11 19:50:54 +0000364 sqlite3_result_int64(pCtx, p->iRow+1);
dan6bc5c9e2018-06-04 18:55:11 +0000365 }else{
366 i64 nLarge = p->nTotal - p->nParam*nSize;
367 i64 iSmall = nLarge*(nSize+1);
dancc7a8502019-03-11 19:50:54 +0000368 i64 iRow = p->iRow;
dan6bc5c9e2018-06-04 18:55:11 +0000369
370 assert( (nLarge*(nSize+1) + (p->nParam-nLarge)*nSize)==p->nTotal );
371
372 if( iRow<iSmall ){
373 sqlite3_result_int64(pCtx, 1 + iRow/(nSize+1));
374 }else{
375 sqlite3_result_int64(pCtx, 1 + nLarge + (iRow-iSmall)/nSize);
376 }
377 }
378 }
379}
dancc7a8502019-03-11 19:50:54 +0000380#define ntileFinalizeFunc ntileValueFunc
dan6bc5c9e2018-06-04 18:55:11 +0000381
dan2a11bb22018-06-11 20:50:25 +0000382/*
383** Context object for last_value() window function.
384*/
dan1c5ed622018-06-05 16:16:17 +0000385struct LastValueCtx {
386 sqlite3_value *pVal;
387 int nVal;
388};
389
390/*
391** Implementation of last_value().
392*/
393static void last_valueStepFunc(
394 sqlite3_context *pCtx,
395 int nArg,
396 sqlite3_value **apArg
397){
398 struct LastValueCtx *p;
drhc7bf5712018-07-09 22:49:01 +0000399 UNUSED_PARAMETER(nArg);
dan9c277582018-06-20 09:23:49 +0000400 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
dan1c5ed622018-06-05 16:16:17 +0000401 if( p ){
402 sqlite3_value_free(p->pVal);
403 p->pVal = sqlite3_value_dup(apArg[0]);
dan6fde1792018-06-15 19:01:35 +0000404 if( p->pVal==0 ){
405 sqlite3_result_error_nomem(pCtx);
406 }else{
407 p->nVal++;
408 }
dan1c5ed622018-06-05 16:16:17 +0000409 }
410}
dan2a11bb22018-06-11 20:50:25 +0000411static void last_valueInvFunc(
dan1c5ed622018-06-05 16:16:17 +0000412 sqlite3_context *pCtx,
413 int nArg,
414 sqlite3_value **apArg
415){
416 struct LastValueCtx *p;
drhc7bf5712018-07-09 22:49:01 +0000417 UNUSED_PARAMETER(nArg);
418 UNUSED_PARAMETER(apArg);
dan9c277582018-06-20 09:23:49 +0000419 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
420 if( ALWAYS(p) ){
dan1c5ed622018-06-05 16:16:17 +0000421 p->nVal--;
422 if( p->nVal==0 ){
423 sqlite3_value_free(p->pVal);
424 p->pVal = 0;
425 }
426 }
427}
428static void last_valueValueFunc(sqlite3_context *pCtx){
429 struct LastValueCtx *p;
dan9c277582018-06-20 09:23:49 +0000430 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
dan1c5ed622018-06-05 16:16:17 +0000431 if( p && p->pVal ){
432 sqlite3_result_value(pCtx, p->pVal);
433 }
434}
435static void last_valueFinalizeFunc(sqlite3_context *pCtx){
436 struct LastValueCtx *p;
dan9c277582018-06-20 09:23:49 +0000437 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
dan1c5ed622018-06-05 16:16:17 +0000438 if( p && p->pVal ){
439 sqlite3_result_value(pCtx, p->pVal);
440 sqlite3_value_free(p->pVal);
441 p->pVal = 0;
442 }
443}
444
dan2a11bb22018-06-11 20:50:25 +0000445/*
drh19dc4d42018-07-08 01:02:26 +0000446** Static names for the built-in window function names. These static
447** names are used, rather than string literals, so that FuncDef objects
448** can be associated with a particular window function by direct
449** comparison of the zName pointer. Example:
450**
451** if( pFuncDef->zName==row_valueName ){ ... }
dan2a11bb22018-06-11 20:50:25 +0000452*/
drh19dc4d42018-07-08 01:02:26 +0000453static const char row_numberName[] = "row_number";
454static const char dense_rankName[] = "dense_rank";
455static const char rankName[] = "rank";
456static const char percent_rankName[] = "percent_rank";
457static const char cume_distName[] = "cume_dist";
458static const char ntileName[] = "ntile";
459static const char last_valueName[] = "last_value";
460static const char nth_valueName[] = "nth_value";
461static const char first_valueName[] = "first_value";
462static const char leadName[] = "lead";
463static const char lagName[] = "lag";
danfe4e25a2018-06-07 20:08:59 +0000464
drh19dc4d42018-07-08 01:02:26 +0000465/*
466** No-op implementations of xStep() and xFinalize(). Used as place-holders
467** for built-in window functions that never call those interfaces.
468**
469** The noopValueFunc() is called but is expected to do nothing. The
470** noopStepFunc() is never called, and so it is marked with NO_TEST to
471** let the test coverage routine know not to expect this function to be
472** invoked.
473*/
474static void noopStepFunc( /*NO_TEST*/
475 sqlite3_context *p, /*NO_TEST*/
476 int n, /*NO_TEST*/
477 sqlite3_value **a /*NO_TEST*/
478){ /*NO_TEST*/
drhc7bf5712018-07-09 22:49:01 +0000479 UNUSED_PARAMETER(p); /*NO_TEST*/
480 UNUSED_PARAMETER(n); /*NO_TEST*/
481 UNUSED_PARAMETER(a); /*NO_TEST*/
drh19dc4d42018-07-08 01:02:26 +0000482 assert(0); /*NO_TEST*/
483} /*NO_TEST*/
drhc7bf5712018-07-09 22:49:01 +0000484static void noopValueFunc(sqlite3_context *p){ UNUSED_PARAMETER(p); /*no-op*/ }
dandfa552f2018-06-02 21:04:28 +0000485
drh19dc4d42018-07-08 01:02:26 +0000486/* Window functions that use all window interfaces: xStep, xFinal,
487** xValue, and xInverse */
488#define WINDOWFUNCALL(name,nArg,extra) { \
dan1c5ed622018-06-05 16:16:17 +0000489 nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
490 name ## StepFunc, name ## FinalizeFunc, name ## ValueFunc, \
drhc7bf5712018-07-09 22:49:01 +0000491 name ## InvFunc, name ## Name, {0} \
dan1c5ed622018-06-05 16:16:17 +0000492}
493
drh19dc4d42018-07-08 01:02:26 +0000494/* Window functions that are implemented using bytecode and thus have
495** no-op routines for their methods */
496#define WINDOWFUNCNOOP(name,nArg,extra) { \
497 nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
498 noopStepFunc, noopValueFunc, noopValueFunc, \
drhc7bf5712018-07-09 22:49:01 +0000499 noopStepFunc, name ## Name, {0} \
drh19dc4d42018-07-08 01:02:26 +0000500}
501
502/* Window functions that use all window interfaces: xStep, the
503** same routine for xFinalize and xValue and which never call
504** xInverse. */
505#define WINDOWFUNCX(name,nArg,extra) { \
506 nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
507 name ## StepFunc, name ## ValueFunc, name ## ValueFunc, \
drhc7bf5712018-07-09 22:49:01 +0000508 noopStepFunc, name ## Name, {0} \
drh19dc4d42018-07-08 01:02:26 +0000509}
510
511
dandfa552f2018-06-02 21:04:28 +0000512/*
513** Register those built-in window functions that are not also aggregates.
514*/
515void sqlite3WindowFunctions(void){
516 static FuncDef aWindowFuncs[] = {
drh19dc4d42018-07-08 01:02:26 +0000517 WINDOWFUNCX(row_number, 0, 0),
518 WINDOWFUNCX(dense_rank, 0, 0),
519 WINDOWFUNCX(rank, 0, 0),
dancc7a8502019-03-11 19:50:54 +0000520 // WINDOWFUNCX(percent_rank, 0, SQLITE_FUNC_WINDOW_SIZE),
521 WINDOWFUNCALL(percent_rank, 0, 0),
522 WINDOWFUNCALL(cume_dist, 0, 0),
523 WINDOWFUNCALL(ntile, 1, 0),
524 // WINDOWFUNCX(cume_dist, 0, SQLITE_FUNC_WINDOW_SIZE),
525 // WINDOWFUNCX(ntile, 1, SQLITE_FUNC_WINDOW_SIZE),
drh19dc4d42018-07-08 01:02:26 +0000526 WINDOWFUNCALL(last_value, 1, 0),
527 WINDOWFUNCNOOP(nth_value, 2, 0),
528 WINDOWFUNCNOOP(first_value, 1, 0),
529 WINDOWFUNCNOOP(lead, 1, 0),
530 WINDOWFUNCNOOP(lead, 2, 0),
531 WINDOWFUNCNOOP(lead, 3, 0),
532 WINDOWFUNCNOOP(lag, 1, 0),
533 WINDOWFUNCNOOP(lag, 2, 0),
534 WINDOWFUNCNOOP(lag, 3, 0),
dandfa552f2018-06-02 21:04:28 +0000535 };
536 sqlite3InsertBuiltinFuncs(aWindowFuncs, ArraySize(aWindowFuncs));
537}
538
dane7c9ca42019-02-16 17:27:51 +0000539static Window *windowFind(Parse *pParse, Window *pList, const char *zName){
540 Window *p;
541 for(p=pList; p; p=p->pNextWin){
542 if( sqlite3StrICmp(p->zName, zName)==0 ) break;
543 }
544 if( p==0 ){
545 sqlite3ErrorMsg(pParse, "no such window: %s", zName);
546 }
547 return p;
548}
549
danc0bb4452018-06-12 20:53:38 +0000550/*
551** This function is called immediately after resolving the function name
552** for a window function within a SELECT statement. Argument pList is a
553** linked list of WINDOW definitions for the current SELECT statement.
554** Argument pFunc is the function definition just resolved and pWin
555** is the Window object representing the associated OVER clause. This
556** function updates the contents of pWin as follows:
557**
558** * If the OVER clause refered to a named window (as in "max(x) OVER win"),
559** search list pList for a matching WINDOW definition, and update pWin
560** accordingly. If no such WINDOW clause can be found, leave an error
561** in pParse.
562**
563** * If the function is a built-in window function that requires the
564** window to be coerced (see "BUILT-IN WINDOW FUNCTIONS" at the top
565** of this file), pWin is updated here.
566*/
dane3bf6322018-06-08 20:58:27 +0000567void sqlite3WindowUpdate(
568 Parse *pParse,
danc0bb4452018-06-12 20:53:38 +0000569 Window *pList, /* List of named windows for this SELECT */
570 Window *pWin, /* Window frame to update */
571 FuncDef *pFunc /* Window function definition */
dane3bf6322018-06-08 20:58:27 +0000572){
danc95f38d2018-06-18 20:34:43 +0000573 if( pWin->zName && pWin->eType==0 ){
dane7c9ca42019-02-16 17:27:51 +0000574 Window *p = windowFind(pParse, pList, pWin->zName);
575 if( p==0 ) return;
dane3bf6322018-06-08 20:58:27 +0000576 pWin->pPartition = sqlite3ExprListDup(pParse->db, p->pPartition, 0);
577 pWin->pOrderBy = sqlite3ExprListDup(pParse->db, p->pOrderBy, 0);
578 pWin->pStart = sqlite3ExprDup(pParse->db, p->pStart, 0);
579 pWin->pEnd = sqlite3ExprDup(pParse->db, p->pEnd, 0);
580 pWin->eStart = p->eStart;
581 pWin->eEnd = p->eEnd;
danc95f38d2018-06-18 20:34:43 +0000582 pWin->eType = p->eType;
dane7c9ca42019-02-16 17:27:51 +0000583 }else{
584 sqlite3WindowChain(pParse, pWin, pList);
dane3bf6322018-06-08 20:58:27 +0000585 }
dan72b9fdc2019-03-09 20:49:17 +0000586 if( (pWin->eType==TK_RANGE)
587 && (pWin->pStart || pWin->pEnd)
588 && (pWin->pOrderBy==0 || pWin->pOrderBy->nExpr!=1)
589 ){
590 sqlite3ErrorMsg(pParse,
591 "RANGE with offset PRECEDING/FOLLOWING requires one ORDER BY expression"
592 );
593 }else
dandfa552f2018-06-02 21:04:28 +0000594 if( pFunc->funcFlags & SQLITE_FUNC_WINDOW ){
595 sqlite3 *db = pParse->db;
dan8b985602018-06-09 17:43:45 +0000596 if( pWin->pFilter ){
597 sqlite3ErrorMsg(pParse,
598 "FILTER clause may only be used with aggregate window functions"
599 );
dancc7a8502019-03-11 19:50:54 +0000600 }else{
601 struct WindowUpdate {
602 const char *zFunc;
603 int eType;
604 int eStart;
605 int eEnd;
606 } aUp[] = {
607 { row_numberName, TK_ROWS, TK_UNBOUNDED, TK_CURRENT },
608 { dense_rankName, TK_RANGE, TK_UNBOUNDED, TK_CURRENT },
609 { rankName, TK_RANGE, TK_UNBOUNDED, TK_CURRENT },
610 { percent_rankName, TK_GROUPS, TK_CURRENT, TK_UNBOUNDED },
611 { cume_distName, TK_GROUPS, TK_FOLLOWING, TK_UNBOUNDED },
612 { ntileName, TK_ROWS, TK_CURRENT, TK_UNBOUNDED },
613 { leadName, TK_ROWS, TK_UNBOUNDED, TK_UNBOUNDED },
614 };
615 int i;
616 for(i=0; i<ArraySize(aUp); i++){
617 if( pFunc->zName==aUp[i].zFunc ){
618 sqlite3ExprDelete(db, pWin->pStart);
619 sqlite3ExprDelete(db, pWin->pEnd);
620 pWin->pEnd = pWin->pStart = 0;
621 pWin->eType = aUp[i].eType;
622 pWin->eStart = aUp[i].eStart;
623 pWin->eEnd = aUp[i].eEnd;
624 if( pWin->eStart==TK_FOLLOWING ){
625 pWin->pStart = sqlite3Expr(db, TK_INTEGER, "1");
626 }
627 break;
628 }
629 }
dandfa552f2018-06-02 21:04:28 +0000630 }
631 }
dan2a11bb22018-06-11 20:50:25 +0000632 pWin->pFunc = pFunc;
dandfa552f2018-06-02 21:04:28 +0000633}
634
danc0bb4452018-06-12 20:53:38 +0000635/*
636** Context object passed through sqlite3WalkExprList() to
637** selectWindowRewriteExprCb() by selectWindowRewriteEList().
638*/
dandfa552f2018-06-02 21:04:28 +0000639typedef struct WindowRewrite WindowRewrite;
640struct WindowRewrite {
641 Window *pWin;
danb556f262018-07-10 17:26:12 +0000642 SrcList *pSrc;
dandfa552f2018-06-02 21:04:28 +0000643 ExprList *pSub;
danb556f262018-07-10 17:26:12 +0000644 Select *pSubSelect; /* Current sub-select, if any */
dandfa552f2018-06-02 21:04:28 +0000645};
646
danc0bb4452018-06-12 20:53:38 +0000647/*
648** Callback function used by selectWindowRewriteEList(). If necessary,
649** this function appends to the output expression-list and updates
650** expression (*ppExpr) in place.
651*/
dandfa552f2018-06-02 21:04:28 +0000652static int selectWindowRewriteExprCb(Walker *pWalker, Expr *pExpr){
653 struct WindowRewrite *p = pWalker->u.pRewrite;
654 Parse *pParse = pWalker->pParse;
655
danb556f262018-07-10 17:26:12 +0000656 /* If this function is being called from within a scalar sub-select
657 ** that used by the SELECT statement being processed, only process
658 ** TK_COLUMN expressions that refer to it (the outer SELECT). Do
659 ** not process aggregates or window functions at all, as they belong
660 ** to the scalar sub-select. */
661 if( p->pSubSelect ){
662 if( pExpr->op!=TK_COLUMN ){
663 return WRC_Continue;
664 }else{
665 int nSrc = p->pSrc->nSrc;
666 int i;
667 for(i=0; i<nSrc; i++){
668 if( pExpr->iTable==p->pSrc->a[i].iCursor ) break;
669 }
670 if( i==nSrc ) return WRC_Continue;
671 }
672 }
673
dandfa552f2018-06-02 21:04:28 +0000674 switch( pExpr->op ){
675
676 case TK_FUNCTION:
drheda079c2018-09-20 19:02:15 +0000677 if( !ExprHasProperty(pExpr, EP_WinFunc) ){
dandfa552f2018-06-02 21:04:28 +0000678 break;
679 }else{
680 Window *pWin;
681 for(pWin=p->pWin; pWin; pWin=pWin->pNextWin){
drheda079c2018-09-20 19:02:15 +0000682 if( pExpr->y.pWin==pWin ){
dan2a11bb22018-06-11 20:50:25 +0000683 assert( pWin->pOwner==pExpr );
dandfa552f2018-06-02 21:04:28 +0000684 return WRC_Prune;
685 }
686 }
687 }
688 /* Fall through. */
689
dan73925692018-06-12 18:40:17 +0000690 case TK_AGG_FUNCTION:
dandfa552f2018-06-02 21:04:28 +0000691 case TK_COLUMN: {
692 Expr *pDup = sqlite3ExprDup(pParse->db, pExpr, 0);
693 p->pSub = sqlite3ExprListAppend(pParse, p->pSub, pDup);
694 if( p->pSub ){
695 assert( ExprHasProperty(pExpr, EP_Static)==0 );
696 ExprSetProperty(pExpr, EP_Static);
697 sqlite3ExprDelete(pParse->db, pExpr);
698 ExprClearProperty(pExpr, EP_Static);
699 memset(pExpr, 0, sizeof(Expr));
700
701 pExpr->op = TK_COLUMN;
702 pExpr->iColumn = p->pSub->nExpr-1;
703 pExpr->iTable = p->pWin->iEphCsr;
704 }
705
706 break;
707 }
708
709 default: /* no-op */
710 break;
711 }
712
713 return WRC_Continue;
714}
danc0bb4452018-06-12 20:53:38 +0000715static int selectWindowRewriteSelectCb(Walker *pWalker, Select *pSelect){
danb556f262018-07-10 17:26:12 +0000716 struct WindowRewrite *p = pWalker->u.pRewrite;
717 Select *pSave = p->pSubSelect;
718 if( pSave==pSelect ){
719 return WRC_Continue;
720 }else{
721 p->pSubSelect = pSelect;
722 sqlite3WalkSelect(pWalker, pSelect);
723 p->pSubSelect = pSave;
724 }
danc0bb4452018-06-12 20:53:38 +0000725 return WRC_Prune;
726}
dandfa552f2018-06-02 21:04:28 +0000727
danc0bb4452018-06-12 20:53:38 +0000728
729/*
730** Iterate through each expression in expression-list pEList. For each:
731**
732** * TK_COLUMN,
733** * aggregate function, or
734** * window function with a Window object that is not a member of the
danb556f262018-07-10 17:26:12 +0000735** Window list passed as the second argument (pWin).
danc0bb4452018-06-12 20:53:38 +0000736**
737** Append the node to output expression-list (*ppSub). And replace it
738** with a TK_COLUMN that reads the (N-1)th element of table
739** pWin->iEphCsr, where N is the number of elements in (*ppSub) after
740** appending the new one.
741*/
dan13b08bb2018-06-15 20:46:12 +0000742static void selectWindowRewriteEList(
dandfa552f2018-06-02 21:04:28 +0000743 Parse *pParse,
744 Window *pWin,
danb556f262018-07-10 17:26:12 +0000745 SrcList *pSrc,
dandfa552f2018-06-02 21:04:28 +0000746 ExprList *pEList, /* Rewrite expressions in this list */
747 ExprList **ppSub /* IN/OUT: Sub-select expression-list */
748){
749 Walker sWalker;
750 WindowRewrite sRewrite;
dandfa552f2018-06-02 21:04:28 +0000751
752 memset(&sWalker, 0, sizeof(Walker));
753 memset(&sRewrite, 0, sizeof(WindowRewrite));
754
755 sRewrite.pSub = *ppSub;
756 sRewrite.pWin = pWin;
danb556f262018-07-10 17:26:12 +0000757 sRewrite.pSrc = pSrc;
dandfa552f2018-06-02 21:04:28 +0000758
759 sWalker.pParse = pParse;
760 sWalker.xExprCallback = selectWindowRewriteExprCb;
761 sWalker.xSelectCallback = selectWindowRewriteSelectCb;
762 sWalker.u.pRewrite = &sRewrite;
763
dan13b08bb2018-06-15 20:46:12 +0000764 (void)sqlite3WalkExprList(&sWalker, pEList);
dandfa552f2018-06-02 21:04:28 +0000765
766 *ppSub = sRewrite.pSub;
dandfa552f2018-06-02 21:04:28 +0000767}
768
danc0bb4452018-06-12 20:53:38 +0000769/*
770** Append a copy of each expression in expression-list pAppend to
771** expression list pList. Return a pointer to the result list.
772*/
dandfa552f2018-06-02 21:04:28 +0000773static ExprList *exprListAppendList(
774 Parse *pParse, /* Parsing context */
775 ExprList *pList, /* List to which to append. Might be NULL */
776 ExprList *pAppend /* List of values to append. Might be NULL */
777){
778 if( pAppend ){
779 int i;
780 int nInit = pList ? pList->nExpr : 0;
781 for(i=0; i<pAppend->nExpr; i++){
782 Expr *pDup = sqlite3ExprDup(pParse->db, pAppend->a[i].pExpr, 0);
783 pList = sqlite3ExprListAppend(pParse, pList, pDup);
784 if( pList ) pList->a[nInit+i].sortOrder = pAppend->a[i].sortOrder;
785 }
786 }
787 return pList;
788}
789
790/*
791** If the SELECT statement passed as the second argument does not invoke
792** any SQL window functions, this function is a no-op. Otherwise, it
793** rewrites the SELECT statement so that window function xStep functions
danc0bb4452018-06-12 20:53:38 +0000794** are invoked in the correct order as described under "SELECT REWRITING"
795** at the top of this file.
dandfa552f2018-06-02 21:04:28 +0000796*/
797int sqlite3WindowRewrite(Parse *pParse, Select *p){
798 int rc = SQLITE_OK;
dan0f5f5402018-10-23 13:48:19 +0000799 if( p->pWin && p->pPrior==0 ){
dandfa552f2018-06-02 21:04:28 +0000800 Vdbe *v = sqlite3GetVdbe(pParse);
dandfa552f2018-06-02 21:04:28 +0000801 sqlite3 *db = pParse->db;
802 Select *pSub = 0; /* The subquery */
803 SrcList *pSrc = p->pSrc;
804 Expr *pWhere = p->pWhere;
805 ExprList *pGroupBy = p->pGroupBy;
806 Expr *pHaving = p->pHaving;
807 ExprList *pSort = 0;
808
809 ExprList *pSublist = 0; /* Expression list for sub-query */
810 Window *pMWin = p->pWin; /* Master window object */
811 Window *pWin; /* Window object iterator */
812
813 p->pSrc = 0;
814 p->pWhere = 0;
815 p->pGroupBy = 0;
816 p->pHaving = 0;
817
danf02cdd32018-06-27 19:48:50 +0000818 /* Create the ORDER BY clause for the sub-select. This is the concatenation
819 ** of the window PARTITION and ORDER BY clauses. Then, if this makes it
820 ** redundant, remove the ORDER BY from the parent SELECT. */
821 pSort = sqlite3ExprListDup(db, pMWin->pPartition, 0);
822 pSort = exprListAppendList(pParse, pSort, pMWin->pOrderBy);
823 if( pSort && p->pOrderBy ){
824 if( sqlite3ExprListCompare(pSort, p->pOrderBy, -1)==0 ){
825 sqlite3ExprListDelete(db, p->pOrderBy);
826 p->pOrderBy = 0;
827 }
828 }
829
dandfa552f2018-06-02 21:04:28 +0000830 /* Assign a cursor number for the ephemeral table used to buffer rows.
831 ** The OpenEphemeral instruction is coded later, after it is known how
832 ** many columns the table will have. */
833 pMWin->iEphCsr = pParse->nTab++;
dan680f6e82019-03-04 21:07:11 +0000834 pParse->nTab += 3;
dandfa552f2018-06-02 21:04:28 +0000835
danb556f262018-07-10 17:26:12 +0000836 selectWindowRewriteEList(pParse, pMWin, pSrc, p->pEList, &pSublist);
837 selectWindowRewriteEList(pParse, pMWin, pSrc, p->pOrderBy, &pSublist);
dandfa552f2018-06-02 21:04:28 +0000838 pMWin->nBufferCol = (pSublist ? pSublist->nExpr : 0);
839
danf02cdd32018-06-27 19:48:50 +0000840 /* Append the PARTITION BY and ORDER BY expressions to the to the
841 ** sub-select expression list. They are required to figure out where
842 ** boundaries for partitions and sets of peer rows lie. */
843 pSublist = exprListAppendList(pParse, pSublist, pMWin->pPartition);
844 pSublist = exprListAppendList(pParse, pSublist, pMWin->pOrderBy);
dandfa552f2018-06-02 21:04:28 +0000845
846 /* Append the arguments passed to each window function to the
847 ** sub-select expression list. Also allocate two registers for each
848 ** window function - one for the accumulator, another for interim
849 ** results. */
850 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
851 pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);
852 pSublist = exprListAppendList(pParse, pSublist, pWin->pOwner->x.pList);
dan8b985602018-06-09 17:43:45 +0000853 if( pWin->pFilter ){
854 Expr *pFilter = sqlite3ExprDup(db, pWin->pFilter, 0);
855 pSublist = sqlite3ExprListAppend(pParse, pSublist, pFilter);
856 }
dandfa552f2018-06-02 21:04:28 +0000857 pWin->regAccum = ++pParse->nMem;
858 pWin->regResult = ++pParse->nMem;
859 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
860 }
861
dan9c277582018-06-20 09:23:49 +0000862 /* If there is no ORDER BY or PARTITION BY clause, and the window
863 ** function accepts zero arguments, and there are no other columns
864 ** selected (e.g. "SELECT row_number() OVER () FROM t1"), it is possible
865 ** that pSublist is still NULL here. Add a constant expression here to
866 ** keep everything legal in this case.
867 */
868 if( pSublist==0 ){
869 pSublist = sqlite3ExprListAppend(pParse, 0,
870 sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0)
871 );
872 }
873
dandfa552f2018-06-02 21:04:28 +0000874 pSub = sqlite3SelectNew(
875 pParse, pSublist, pSrc, pWhere, pGroupBy, pHaving, pSort, 0, 0
876 );
drh29c992c2019-01-17 15:40:41 +0000877 p->pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
dandfa552f2018-06-02 21:04:28 +0000878 if( p->pSrc ){
dandfa552f2018-06-02 21:04:28 +0000879 p->pSrc->a[0].pSelect = pSub;
880 sqlite3SrcListAssignCursors(pParse, p->pSrc);
881 if( sqlite3ExpandSubquery(pParse, &p->pSrc->a[0]) ){
882 rc = SQLITE_NOMEM;
883 }else{
884 pSub->selFlags |= SF_Expanded;
dan73925692018-06-12 18:40:17 +0000885 p->selFlags &= ~SF_Aggregate;
886 sqlite3SelectPrep(pParse, pSub, 0);
dandfa552f2018-06-02 21:04:28 +0000887 }
dandfa552f2018-06-02 21:04:28 +0000888
dan6fde1792018-06-15 19:01:35 +0000889 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pMWin->iEphCsr, pSublist->nExpr);
dan680f6e82019-03-04 21:07:11 +0000890 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+1, pMWin->iEphCsr);
891 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+2, pMWin->iEphCsr);
892 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+3, pMWin->iEphCsr);
dan6fde1792018-06-15 19:01:35 +0000893 }else{
894 sqlite3SelectDelete(db, pSub);
895 }
896 if( db->mallocFailed ) rc = SQLITE_NOMEM;
dandfa552f2018-06-02 21:04:28 +0000897 }
898
899 return rc;
900}
901
danc0bb4452018-06-12 20:53:38 +0000902/*
903** Free the Window object passed as the second argument.
904*/
dan86fb6e12018-05-16 20:58:07 +0000905void sqlite3WindowDelete(sqlite3 *db, Window *p){
906 if( p ){
907 sqlite3ExprDelete(db, p->pFilter);
908 sqlite3ExprListDelete(db, p->pPartition);
909 sqlite3ExprListDelete(db, p->pOrderBy);
910 sqlite3ExprDelete(db, p->pEnd);
911 sqlite3ExprDelete(db, p->pStart);
dane3bf6322018-06-08 20:58:27 +0000912 sqlite3DbFree(db, p->zName);
dane7c9ca42019-02-16 17:27:51 +0000913 sqlite3DbFree(db, p->zBase);
dan86fb6e12018-05-16 20:58:07 +0000914 sqlite3DbFree(db, p);
915 }
916}
917
danc0bb4452018-06-12 20:53:38 +0000918/*
919** Free the linked list of Window objects starting at the second argument.
920*/
dane3bf6322018-06-08 20:58:27 +0000921void sqlite3WindowListDelete(sqlite3 *db, Window *p){
922 while( p ){
923 Window *pNext = p->pNextWin;
924 sqlite3WindowDelete(db, p);
925 p = pNext;
926 }
927}
928
danc0bb4452018-06-12 20:53:38 +0000929/*
drhe4984a22018-07-06 17:19:20 +0000930** The argument expression is an PRECEDING or FOLLOWING offset. The
931** value should be a non-negative integer. If the value is not a
932** constant, change it to NULL. The fact that it is then a non-negative
933** integer will be caught later. But it is important not to leave
934** variable values in the expression tree.
935*/
936static Expr *sqlite3WindowOffsetExpr(Parse *pParse, Expr *pExpr){
937 if( 0==sqlite3ExprIsConstant(pExpr) ){
danfb8ac322019-01-16 12:05:22 +0000938 if( IN_RENAME_OBJECT ) sqlite3RenameExprUnmap(pParse, pExpr);
drhe4984a22018-07-06 17:19:20 +0000939 sqlite3ExprDelete(pParse->db, pExpr);
940 pExpr = sqlite3ExprAlloc(pParse->db, TK_NULL, 0, 0);
941 }
942 return pExpr;
943}
944
945/*
946** Allocate and return a new Window object describing a Window Definition.
danc0bb4452018-06-12 20:53:38 +0000947*/
dan86fb6e12018-05-16 20:58:07 +0000948Window *sqlite3WindowAlloc(
drhe4984a22018-07-06 17:19:20 +0000949 Parse *pParse, /* Parsing context */
950 int eType, /* Frame type. TK_RANGE or TK_ROWS */
951 int eStart, /* Start type: CURRENT, PRECEDING, FOLLOWING, UNBOUNDED */
952 Expr *pStart, /* Start window size if TK_PRECEDING or FOLLOWING */
953 int eEnd, /* End type: CURRENT, FOLLOWING, TK_UNBOUNDED, PRECEDING */
954 Expr *pEnd /* End window size if TK_FOLLOWING or PRECEDING */
dan86fb6e12018-05-16 20:58:07 +0000955){
dan7a606e12018-07-05 18:34:53 +0000956 Window *pWin = 0;
dane7c9ca42019-02-16 17:27:51 +0000957 int bImplicitFrame = 0;
dan7a606e12018-07-05 18:34:53 +0000958
drhe4984a22018-07-06 17:19:20 +0000959 /* Parser assures the following: */
dan6c75b392019-03-08 20:02:52 +0000960 assert( eType==0 || eType==TK_RANGE || eType==TK_ROWS || eType==TK_GROUPS );
drhe4984a22018-07-06 17:19:20 +0000961 assert( eStart==TK_CURRENT || eStart==TK_PRECEDING
962 || eStart==TK_UNBOUNDED || eStart==TK_FOLLOWING );
963 assert( eEnd==TK_CURRENT || eEnd==TK_FOLLOWING
964 || eEnd==TK_UNBOUNDED || eEnd==TK_PRECEDING );
965 assert( (eStart==TK_PRECEDING || eStart==TK_FOLLOWING)==(pStart!=0) );
966 assert( (eEnd==TK_FOLLOWING || eEnd==TK_PRECEDING)==(pEnd!=0) );
967
dane7c9ca42019-02-16 17:27:51 +0000968 if( eType==0 ){
969 bImplicitFrame = 1;
970 eType = TK_RANGE;
971 }
drhe4984a22018-07-06 17:19:20 +0000972
drhe4984a22018-07-06 17:19:20 +0000973 /* Additionally, the
dan5d764ac2018-07-06 14:15:49 +0000974 ** starting boundary type may not occur earlier in the following list than
975 ** the ending boundary type:
976 **
977 ** UNBOUNDED PRECEDING
978 ** <expr> PRECEDING
979 ** CURRENT ROW
980 ** <expr> FOLLOWING
981 ** UNBOUNDED FOLLOWING
982 **
983 ** The parser ensures that "UNBOUNDED PRECEDING" cannot be used as an ending
984 ** boundary, and than "UNBOUNDED FOLLOWING" cannot be used as a starting
985 ** frame boundary.
986 */
drhe4984a22018-07-06 17:19:20 +0000987 if( (eStart==TK_CURRENT && eEnd==TK_PRECEDING)
dan5d764ac2018-07-06 14:15:49 +0000988 || (eStart==TK_FOLLOWING && (eEnd==TK_PRECEDING || eEnd==TK_CURRENT))
989 ){
dan72b9fdc2019-03-09 20:49:17 +0000990 sqlite3ErrorMsg(pParse, "unsupported frame specification");
drhe4984a22018-07-06 17:19:20 +0000991 goto windowAllocErr;
dan7a606e12018-07-05 18:34:53 +0000992 }
dan86fb6e12018-05-16 20:58:07 +0000993
drhe4984a22018-07-06 17:19:20 +0000994 pWin = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
995 if( pWin==0 ) goto windowAllocErr;
996 pWin->eType = eType;
997 pWin->eStart = eStart;
998 pWin->eEnd = eEnd;
dane7c9ca42019-02-16 17:27:51 +0000999 pWin->bImplicitFrame = bImplicitFrame;
drhe4984a22018-07-06 17:19:20 +00001000 pWin->pEnd = sqlite3WindowOffsetExpr(pParse, pEnd);
1001 pWin->pStart = sqlite3WindowOffsetExpr(pParse, pStart);
dan86fb6e12018-05-16 20:58:07 +00001002 return pWin;
drhe4984a22018-07-06 17:19:20 +00001003
1004windowAllocErr:
1005 sqlite3ExprDelete(pParse->db, pEnd);
1006 sqlite3ExprDelete(pParse->db, pStart);
1007 return 0;
dan86fb6e12018-05-16 20:58:07 +00001008}
1009
danc0bb4452018-06-12 20:53:38 +00001010/*
dane7c9ca42019-02-16 17:27:51 +00001011** Attach PARTITION and ORDER BY clauses pPartition and pOrderBy to window
1012** pWin. Also, if parameter pBase is not NULL, set pWin->zBase to the
1013** equivalent nul-terminated string.
1014*/
1015Window *sqlite3WindowAssemble(
1016 Parse *pParse,
1017 Window *pWin,
1018 ExprList *pPartition,
1019 ExprList *pOrderBy,
1020 Token *pBase
1021){
1022 if( pWin ){
1023 pWin->pPartition = pPartition;
1024 pWin->pOrderBy = pOrderBy;
1025 if( pBase ){
1026 pWin->zBase = sqlite3DbStrNDup(pParse->db, pBase->z, pBase->n);
1027 }
1028 }else{
1029 sqlite3ExprListDelete(pParse->db, pPartition);
1030 sqlite3ExprListDelete(pParse->db, pOrderBy);
1031 }
1032 return pWin;
1033}
1034
1035/*
1036** Window *pWin has just been created from a WINDOW clause. Tokne pBase
1037** is the base window. Earlier windows from the same WINDOW clause are
1038** stored in the linked list starting at pWin->pNextWin. This function
1039** either updates *pWin according to the base specification, or else
1040** leaves an error in pParse.
1041*/
1042void sqlite3WindowChain(Parse *pParse, Window *pWin, Window *pList){
1043 if( pWin->zBase ){
1044 sqlite3 *db = pParse->db;
1045 Window *pExist = windowFind(pParse, pList, pWin->zBase);
1046 if( pExist ){
1047 const char *zErr = 0;
1048 /* Check for errors */
1049 if( pWin->pPartition ){
1050 zErr = "PARTITION clause";
1051 }else if( pExist->pOrderBy && pWin->pOrderBy ){
1052 zErr = "ORDER BY clause";
1053 }else if( pExist->bImplicitFrame==0 ){
1054 zErr = "frame specification";
1055 }
1056 if( zErr ){
1057 sqlite3ErrorMsg(pParse,
1058 "cannot override %s of window: %s", zErr, pWin->zBase
1059 );
1060 }else{
1061 pWin->pPartition = sqlite3ExprListDup(db, pExist->pPartition, 0);
1062 if( pExist->pOrderBy ){
1063 assert( pWin->pOrderBy==0 );
1064 pWin->pOrderBy = sqlite3ExprListDup(db, pExist->pOrderBy, 0);
1065 }
1066 sqlite3DbFree(db, pWin->zBase);
1067 pWin->zBase = 0;
1068 }
1069 }
1070 }
1071}
1072
1073/*
danc0bb4452018-06-12 20:53:38 +00001074** Attach window object pWin to expression p.
1075*/
dan86fb6e12018-05-16 20:58:07 +00001076void sqlite3WindowAttach(Parse *pParse, Expr *p, Window *pWin){
1077 if( p ){
drheda079c2018-09-20 19:02:15 +00001078 assert( p->op==TK_FUNCTION );
drh954733b2018-07-27 23:33:16 +00001079 /* This routine is only called for the parser. If pWin was not
1080 ** allocated due to an OOM, then the parser would fail before ever
1081 ** invoking this routine */
1082 if( ALWAYS(pWin) ){
drheda079c2018-09-20 19:02:15 +00001083 p->y.pWin = pWin;
1084 ExprSetProperty(p, EP_WinFunc);
dane33f6e72018-07-06 07:42:42 +00001085 pWin->pOwner = p;
1086 if( p->flags & EP_Distinct ){
drhe4984a22018-07-06 17:19:20 +00001087 sqlite3ErrorMsg(pParse,
1088 "DISTINCT is not supported for window functions");
dane33f6e72018-07-06 07:42:42 +00001089 }
1090 }
dan86fb6e12018-05-16 20:58:07 +00001091 }else{
1092 sqlite3WindowDelete(pParse->db, pWin);
1093 }
1094}
dane2f781b2018-05-17 19:24:08 +00001095
1096/*
1097** Return 0 if the two window objects are identical, or non-zero otherwise.
dan13078ca2018-06-13 20:29:38 +00001098** Identical window objects can be processed in a single scan.
dane2f781b2018-05-17 19:24:08 +00001099*/
1100int sqlite3WindowCompare(Parse *pParse, Window *p1, Window *p2){
1101 if( p1->eType!=p2->eType ) return 1;
1102 if( p1->eStart!=p2->eStart ) return 1;
1103 if( p1->eEnd!=p2->eEnd ) return 1;
1104 if( sqlite3ExprCompare(pParse, p1->pStart, p2->pStart, -1) ) return 1;
1105 if( sqlite3ExprCompare(pParse, p1->pEnd, p2->pEnd, -1) ) return 1;
1106 if( sqlite3ExprListCompare(p1->pPartition, p2->pPartition, -1) ) return 1;
1107 if( sqlite3ExprListCompare(p1->pOrderBy, p2->pOrderBy, -1) ) return 1;
1108 return 0;
1109}
1110
dan13078ca2018-06-13 20:29:38 +00001111
1112/*
1113** This is called by code in select.c before it calls sqlite3WhereBegin()
1114** to begin iterating through the sub-query results. It is used to allocate
1115** and initialize registers and cursors used by sqlite3WindowCodeStep().
1116*/
1117void sqlite3WindowCodeInit(Parse *pParse, Window *pMWin){
danc9a86682018-05-30 20:44:58 +00001118 Window *pWin;
dan13078ca2018-06-13 20:29:38 +00001119 Vdbe *v = sqlite3GetVdbe(pParse);
1120 int nPart = (pMWin->pPartition ? pMWin->pPartition->nExpr : 0);
1121 nPart += (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);
1122 if( nPart ){
1123 pMWin->regPart = pParse->nMem+1;
1124 pParse->nMem += nPart;
1125 sqlite3VdbeAddOp3(v, OP_Null, 0, pMWin->regPart, pMWin->regPart+nPart-1);
1126 }
1127
dan680f6e82019-03-04 21:07:11 +00001128 pMWin->regFirst = ++pParse->nMem;
1129 sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regFirst);
1130
danc9a86682018-05-30 20:44:58 +00001131 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
danec891fd2018-06-06 20:51:02 +00001132 FuncDef *p = pWin->pFunc;
1133 if( (p->funcFlags & SQLITE_FUNC_MINMAX) && pWin->eStart!=TK_UNBOUNDED ){
dan9a947222018-06-14 19:06:36 +00001134 /* The inline versions of min() and max() require a single ephemeral
1135 ** table and 3 registers. The registers are used as follows:
1136 **
1137 ** regApp+0: slot to copy min()/max() argument to for MakeRecord
1138 ** regApp+1: integer value used to ensure keys are unique
1139 ** regApp+2: output of MakeRecord
1140 */
danc9a86682018-05-30 20:44:58 +00001141 ExprList *pList = pWin->pOwner->x.pList;
1142 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pList, 0, 0);
danc9a86682018-05-30 20:44:58 +00001143 pWin->csrApp = pParse->nTab++;
1144 pWin->regApp = pParse->nMem+1;
1145 pParse->nMem += 3;
1146 if( pKeyInfo && pWin->pFunc->zName[1]=='i' ){
1147 assert( pKeyInfo->aSortOrder[0]==0 );
1148 pKeyInfo->aSortOrder[0] = 1;
1149 }
1150 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pWin->csrApp, 2);
1151 sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
1152 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
1153 }
drh19dc4d42018-07-08 01:02:26 +00001154 else if( p->zName==nth_valueName || p->zName==first_valueName ){
danec891fd2018-06-06 20:51:02 +00001155 /* Allocate two registers at pWin->regApp. These will be used to
1156 ** store the start and end index of the current frame. */
1157 assert( pMWin->iEphCsr );
1158 pWin->regApp = pParse->nMem+1;
1159 pWin->csrApp = pParse->nTab++;
1160 pParse->nMem += 2;
danec891fd2018-06-06 20:51:02 +00001161 sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
1162 }
drh19dc4d42018-07-08 01:02:26 +00001163 else if( p->zName==leadName || p->zName==lagName ){
danfe4e25a2018-06-07 20:08:59 +00001164 assert( pMWin->iEphCsr );
1165 pWin->csrApp = pParse->nTab++;
1166 sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
1167 }
danc9a86682018-05-30 20:44:58 +00001168 }
1169}
1170
dan13078ca2018-06-13 20:29:38 +00001171/*
dana1a7e112018-07-09 13:31:18 +00001172** A "PRECEDING <expr>" (eCond==0) or "FOLLOWING <expr>" (eCond==1) or the
1173** value of the second argument to nth_value() (eCond==2) has just been
1174** evaluated and the result left in register reg. This function generates VM
1175** code to check that the value is a non-negative integer and throws an
1176** exception if it is not.
dan13078ca2018-06-13 20:29:38 +00001177*/
dana1a7e112018-07-09 13:31:18 +00001178static void windowCheckIntValue(Parse *pParse, int reg, int eCond){
danc3a20c12018-05-23 20:55:37 +00001179 static const char *azErr[] = {
1180 "frame starting offset must be a non-negative integer",
dana1a7e112018-07-09 13:31:18 +00001181 "frame ending offset must be a non-negative integer",
1182 "second argument to nth_value must be a positive integer"
danc3a20c12018-05-23 20:55:37 +00001183 };
dana1a7e112018-07-09 13:31:18 +00001184 static int aOp[] = { OP_Ge, OP_Ge, OP_Gt };
danc3a20c12018-05-23 20:55:37 +00001185 Vdbe *v = sqlite3GetVdbe(pParse);
dan13078ca2018-06-13 20:29:38 +00001186 int regZero = sqlite3GetTempReg(pParse);
dana1a7e112018-07-09 13:31:18 +00001187 assert( eCond==0 || eCond==1 || eCond==2 );
danc3a20c12018-05-23 20:55:37 +00001188 sqlite3VdbeAddOp2(v, OP_Integer, 0, regZero);
1189 sqlite3VdbeAddOp2(v, OP_MustBeInt, reg, sqlite3VdbeCurrentAddr(v)+2);
drh0b3b0dd2018-07-10 05:11:03 +00001190 VdbeCoverageIf(v, eCond==0);
1191 VdbeCoverageIf(v, eCond==1);
1192 VdbeCoverageIf(v, eCond==2);
dana1a7e112018-07-09 13:31:18 +00001193 sqlite3VdbeAddOp3(v, aOp[eCond], regZero, sqlite3VdbeCurrentAddr(v)+2, reg);
drh6ccbd272018-07-10 17:10:44 +00001194 VdbeCoverageNeverNullIf(v, eCond==0);
1195 VdbeCoverageNeverNullIf(v, eCond==1);
1196 VdbeCoverageNeverNullIf(v, eCond==2);
drh211a0852019-01-27 02:41:34 +00001197 sqlite3MayAbort(pParse);
danc3a20c12018-05-23 20:55:37 +00001198 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_ERROR, OE_Abort);
dana1a7e112018-07-09 13:31:18 +00001199 sqlite3VdbeAppendP4(v, (void*)azErr[eCond], P4_STATIC);
dan13078ca2018-06-13 20:29:38 +00001200 sqlite3ReleaseTempReg(pParse, regZero);
danc3a20c12018-05-23 20:55:37 +00001201}
1202
dan13078ca2018-06-13 20:29:38 +00001203/*
1204** Return the number of arguments passed to the window-function associated
1205** with the object passed as the only argument to this function.
1206*/
dan2a11bb22018-06-11 20:50:25 +00001207static int windowArgCount(Window *pWin){
1208 ExprList *pList = pWin->pOwner->x.pList;
1209 return (pList ? pList->nExpr : 0);
1210}
1211
danc9a86682018-05-30 20:44:58 +00001212/*
1213** Generate VM code to invoke either xStep() (if bInverse is 0) or
1214** xInverse (if bInverse is non-zero) for each window function in the
dan13078ca2018-06-13 20:29:38 +00001215** linked list starting at pMWin. Or, for built-in window functions
1216** that do not use the standard function API, generate the required
1217** inline VM code.
1218**
1219** If argument csr is greater than or equal to 0, then argument reg is
1220** the first register in an array of registers guaranteed to be large
1221** enough to hold the array of arguments for each function. In this case
1222** the arguments are extracted from the current row of csr into the
drh8f26da62018-07-05 21:22:57 +00001223** array of registers before invoking OP_AggStep or OP_AggInverse
dan13078ca2018-06-13 20:29:38 +00001224**
1225** Or, if csr is less than zero, then the array of registers at reg is
1226** already populated with all columns from the current row of the sub-query.
1227**
1228** If argument regPartSize is non-zero, then it is a register containing the
1229** number of rows in the current partition.
danc9a86682018-05-30 20:44:58 +00001230*/
dan31f56392018-05-24 21:10:57 +00001231static void windowAggStep(
1232 Parse *pParse,
dan13078ca2018-06-13 20:29:38 +00001233 Window *pMWin, /* Linked list of window functions */
1234 int csr, /* Read arguments from this cursor */
1235 int bInverse, /* True to invoke xInverse instead of xStep */
1236 int reg, /* Array of registers */
dandfa552f2018-06-02 21:04:28 +00001237 int regPartSize /* Register containing size of partition */
dan31f56392018-05-24 21:10:57 +00001238){
1239 Vdbe *v = sqlite3GetVdbe(pParse);
1240 Window *pWin;
1241 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
danc9a86682018-05-30 20:44:58 +00001242 int regArg;
dan2a11bb22018-06-11 20:50:25 +00001243 int nArg = windowArgCount(pWin);
dandfa552f2018-06-02 21:04:28 +00001244
dan6bc5c9e2018-06-04 18:55:11 +00001245 if( csr>=0 ){
danc9a86682018-05-30 20:44:58 +00001246 int i;
dan2a11bb22018-06-11 20:50:25 +00001247 for(i=0; i<nArg; i++){
danc9a86682018-05-30 20:44:58 +00001248 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+i, reg+i);
1249 }
1250 regArg = reg;
1251 }else{
1252 regArg = reg + pWin->iArgCol;
dan31f56392018-05-24 21:10:57 +00001253 }
danc9a86682018-05-30 20:44:58 +00001254
danec891fd2018-06-06 20:51:02 +00001255 if( (pWin->pFunc->funcFlags & SQLITE_FUNC_MINMAX)
1256 && pWin->eStart!=TK_UNBOUNDED
1257 ){
dand4fc49f2018-07-07 17:30:44 +00001258 int addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regArg);
1259 VdbeCoverage(v);
danc9a86682018-05-30 20:44:58 +00001260 if( bInverse==0 ){
1261 sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1, 1);
1262 sqlite3VdbeAddOp2(v, OP_SCopy, regArg, pWin->regApp);
1263 sqlite3VdbeAddOp3(v, OP_MakeRecord, pWin->regApp, 2, pWin->regApp+2);
1264 sqlite3VdbeAddOp2(v, OP_IdxInsert, pWin->csrApp, pWin->regApp+2);
1265 }else{
1266 sqlite3VdbeAddOp4Int(v, OP_SeekGE, pWin->csrApp, 0, regArg, 1);
drh93419162018-07-11 03:27:52 +00001267 VdbeCoverageNeverTaken(v);
danc9a86682018-05-30 20:44:58 +00001268 sqlite3VdbeAddOp1(v, OP_Delete, pWin->csrApp);
1269 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
1270 }
dand4fc49f2018-07-07 17:30:44 +00001271 sqlite3VdbeJumpHere(v, addrIsNull);
danec891fd2018-06-06 20:51:02 +00001272 }else if( pWin->regApp ){
drh19dc4d42018-07-08 01:02:26 +00001273 assert( pWin->pFunc->zName==nth_valueName
1274 || pWin->pFunc->zName==first_valueName
dan7095c002018-06-07 17:45:22 +00001275 );
danec891fd2018-06-06 20:51:02 +00001276 assert( bInverse==0 || bInverse==1 );
1277 sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1-bInverse, 1);
drh19dc4d42018-07-08 01:02:26 +00001278 }else if( pWin->pFunc->zName==leadName
1279 || pWin->pFunc->zName==lagName
danfe4e25a2018-06-07 20:08:59 +00001280 ){
1281 /* no-op */
danc9a86682018-05-30 20:44:58 +00001282 }else{
dan8b985602018-06-09 17:43:45 +00001283 int addrIf = 0;
1284 if( pWin->pFilter ){
1285 int regTmp;
danf5e8e312018-07-09 06:51:36 +00001286 assert( nArg==0 || nArg==pWin->pOwner->x.pList->nExpr );
1287 assert( nArg || pWin->pOwner->x.pList==0 );
dan8b985602018-06-09 17:43:45 +00001288 if( csr>0 ){
1289 regTmp = sqlite3GetTempReg(pParse);
dan2a11bb22018-06-11 20:50:25 +00001290 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+nArg,regTmp);
dan8b985602018-06-09 17:43:45 +00001291 }else{
dan2a11bb22018-06-11 20:50:25 +00001292 regTmp = regArg + nArg;
dan8b985602018-06-09 17:43:45 +00001293 }
1294 addrIf = sqlite3VdbeAddOp3(v, OP_IfNot, regTmp, 0, 1);
dan01e12292018-06-27 20:24:59 +00001295 VdbeCoverage(v);
dan8b985602018-06-09 17:43:45 +00001296 if( csr>0 ){
1297 sqlite3ReleaseTempReg(pParse, regTmp);
1298 }
1299 }
danc9a86682018-05-30 20:44:58 +00001300 if( pWin->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
1301 CollSeq *pColl;
danf5e8e312018-07-09 06:51:36 +00001302 assert( nArg>0 );
dan8b985602018-06-09 17:43:45 +00001303 pColl = sqlite3ExprNNCollSeq(pParse, pWin->pOwner->x.pList->a[0].pExpr);
danc9a86682018-05-30 20:44:58 +00001304 sqlite3VdbeAddOp4(v, OP_CollSeq, 0,0,0, (const char*)pColl, P4_COLLSEQ);
1305 }
drh8f26da62018-07-05 21:22:57 +00001306 sqlite3VdbeAddOp3(v, bInverse? OP_AggInverse : OP_AggStep,
1307 bInverse, regArg, pWin->regAccum);
danc9a86682018-05-30 20:44:58 +00001308 sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
dandfa552f2018-06-02 21:04:28 +00001309 sqlite3VdbeChangeP5(v, (u8)nArg);
dan8b985602018-06-09 17:43:45 +00001310 if( addrIf ) sqlite3VdbeJumpHere(v, addrIf);
danc9a86682018-05-30 20:44:58 +00001311 }
dan31f56392018-05-24 21:10:57 +00001312 }
1313}
1314
dan13078ca2018-06-13 20:29:38 +00001315/*
1316** Generate VM code to invoke either xValue() (bFinal==0) or xFinalize()
1317** (bFinal==1) for each window function in the linked list starting at
1318** pMWin. Or, for built-in window-functions that do not use the standard
1319** API, generate the equivalent VM code.
1320*/
dand6f784e2018-05-28 18:30:45 +00001321static void windowAggFinal(Parse *pParse, Window *pMWin, int bFinal){
1322 Vdbe *v = sqlite3GetVdbe(pParse);
1323 Window *pWin;
1324
1325 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
danec891fd2018-06-06 20:51:02 +00001326 if( (pWin->pFunc->funcFlags & SQLITE_FUNC_MINMAX)
1327 && pWin->eStart!=TK_UNBOUNDED
1328 ){
dand6f784e2018-05-28 18:30:45 +00001329 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
danc9a86682018-05-30 20:44:58 +00001330 sqlite3VdbeAddOp1(v, OP_Last, pWin->csrApp);
dan01e12292018-06-27 20:24:59 +00001331 VdbeCoverage(v);
danc9a86682018-05-30 20:44:58 +00001332 sqlite3VdbeAddOp3(v, OP_Column, pWin->csrApp, 0, pWin->regResult);
1333 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
1334 if( bFinal ){
1335 sqlite3VdbeAddOp1(v, OP_ResetSorter, pWin->csrApp);
1336 }
danec891fd2018-06-06 20:51:02 +00001337 }else if( pWin->regApp ){
dand6f784e2018-05-28 18:30:45 +00001338 }else{
danc9a86682018-05-30 20:44:58 +00001339 if( bFinal ){
drh8f26da62018-07-05 21:22:57 +00001340 sqlite3VdbeAddOp2(v, OP_AggFinal, pWin->regAccum, windowArgCount(pWin));
1341 sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
danc9a86682018-05-30 20:44:58 +00001342 sqlite3VdbeAddOp2(v, OP_Copy, pWin->regAccum, pWin->regResult);
dan8b985602018-06-09 17:43:45 +00001343 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
danc9a86682018-05-30 20:44:58 +00001344 }else{
drh8f26da62018-07-05 21:22:57 +00001345 sqlite3VdbeAddOp3(v, OP_AggValue, pWin->regAccum, windowArgCount(pWin),
1346 pWin->regResult);
1347 sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
danc9a86682018-05-30 20:44:58 +00001348 }
dand6f784e2018-05-28 18:30:45 +00001349 }
1350 }
1351}
1352
dan13078ca2018-06-13 20:29:38 +00001353/*
dan13078ca2018-06-13 20:29:38 +00001354** Invoke the sub-routine at regGosub (generated by code in select.c) to
1355** return the current row of Window.iEphCsr. If all window functions are
1356** aggregate window functions that use the standard API, a single
1357** OP_Gosub instruction is all that this routine generates. Extra VM code
1358** for per-row processing is only generated for the following built-in window
1359** functions:
1360**
1361** nth_value()
1362** first_value()
1363** lag()
1364** lead()
1365*/
danec891fd2018-06-06 20:51:02 +00001366static void windowReturnOneRow(
1367 Parse *pParse,
1368 Window *pMWin,
1369 int regGosub,
1370 int addrGosub
1371){
1372 Vdbe *v = sqlite3GetVdbe(pParse);
1373 Window *pWin;
1374 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1375 FuncDef *pFunc = pWin->pFunc;
drh19dc4d42018-07-08 01:02:26 +00001376 if( pFunc->zName==nth_valueName
1377 || pFunc->zName==first_valueName
dan7095c002018-06-07 17:45:22 +00001378 ){
danec891fd2018-06-06 20:51:02 +00001379 int csr = pWin->csrApp;
drhec4ccdb2018-12-29 02:26:59 +00001380 int lbl = sqlite3VdbeMakeLabel(pParse);
danec891fd2018-06-06 20:51:02 +00001381 int tmpReg = sqlite3GetTempReg(pParse);
1382 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
dan7095c002018-06-07 17:45:22 +00001383
drh19dc4d42018-07-08 01:02:26 +00001384 if( pFunc->zName==nth_valueName ){
dan6fde1792018-06-15 19:01:35 +00001385 sqlite3VdbeAddOp3(v, OP_Column, pMWin->iEphCsr, pWin->iArgCol+1,tmpReg);
dana1a7e112018-07-09 13:31:18 +00001386 windowCheckIntValue(pParse, tmpReg, 2);
dan7095c002018-06-07 17:45:22 +00001387 }else{
1388 sqlite3VdbeAddOp2(v, OP_Integer, 1, tmpReg);
1389 }
danec891fd2018-06-06 20:51:02 +00001390 sqlite3VdbeAddOp3(v, OP_Add, tmpReg, pWin->regApp, tmpReg);
1391 sqlite3VdbeAddOp3(v, OP_Gt, pWin->regApp+1, lbl, tmpReg);
drh6ccbd272018-07-10 17:10:44 +00001392 VdbeCoverageNeverNull(v);
drh93419162018-07-11 03:27:52 +00001393 sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, 0, tmpReg);
1394 VdbeCoverageNeverTaken(v);
danec891fd2018-06-06 20:51:02 +00001395 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
1396 sqlite3VdbeResolveLabel(v, lbl);
1397 sqlite3ReleaseTempReg(pParse, tmpReg);
1398 }
drh19dc4d42018-07-08 01:02:26 +00001399 else if( pFunc->zName==leadName || pFunc->zName==lagName ){
dan2a11bb22018-06-11 20:50:25 +00001400 int nArg = pWin->pOwner->x.pList->nExpr;
danfe4e25a2018-06-07 20:08:59 +00001401 int csr = pWin->csrApp;
drhec4ccdb2018-12-29 02:26:59 +00001402 int lbl = sqlite3VdbeMakeLabel(pParse);
danfe4e25a2018-06-07 20:08:59 +00001403 int tmpReg = sqlite3GetTempReg(pParse);
dan680f6e82019-03-04 21:07:11 +00001404 int iEph = pMWin->iEphCsr;
danfe4e25a2018-06-07 20:08:59 +00001405
dan2a11bb22018-06-11 20:50:25 +00001406 if( nArg<3 ){
danfe4e25a2018-06-07 20:08:59 +00001407 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
1408 }else{
1409 sqlite3VdbeAddOp3(v, OP_Column, iEph, pWin->iArgCol+2, pWin->regResult);
1410 }
1411 sqlite3VdbeAddOp2(v, OP_Rowid, iEph, tmpReg);
dan2a11bb22018-06-11 20:50:25 +00001412 if( nArg<2 ){
drh19dc4d42018-07-08 01:02:26 +00001413 int val = (pFunc->zName==leadName ? 1 : -1);
danfe4e25a2018-06-07 20:08:59 +00001414 sqlite3VdbeAddOp2(v, OP_AddImm, tmpReg, val);
1415 }else{
drh19dc4d42018-07-08 01:02:26 +00001416 int op = (pFunc->zName==leadName ? OP_Add : OP_Subtract);
danfe4e25a2018-06-07 20:08:59 +00001417 int tmpReg2 = sqlite3GetTempReg(pParse);
1418 sqlite3VdbeAddOp3(v, OP_Column, iEph, pWin->iArgCol+1, tmpReg2);
1419 sqlite3VdbeAddOp3(v, op, tmpReg2, tmpReg, tmpReg);
1420 sqlite3ReleaseTempReg(pParse, tmpReg2);
1421 }
1422
1423 sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, lbl, tmpReg);
dan01e12292018-06-27 20:24:59 +00001424 VdbeCoverage(v);
danfe4e25a2018-06-07 20:08:59 +00001425 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
1426 sqlite3VdbeResolveLabel(v, lbl);
1427 sqlite3ReleaseTempReg(pParse, tmpReg);
1428 }
danec891fd2018-06-06 20:51:02 +00001429 }
1430 sqlite3VdbeAddOp2(v, OP_Gosub, regGosub, addrGosub);
1431}
1432
dan13078ca2018-06-13 20:29:38 +00001433/*
dan54a9ab32018-06-14 14:27:05 +00001434** Generate code to set the accumulator register for each window function
1435** in the linked list passed as the second argument to NULL. And perform
1436** any equivalent initialization required by any built-in window functions
1437** in the list.
1438*/
dan2e605682018-06-07 15:54:26 +00001439static int windowInitAccum(Parse *pParse, Window *pMWin){
1440 Vdbe *v = sqlite3GetVdbe(pParse);
1441 int regArg;
1442 int nArg = 0;
1443 Window *pWin;
1444 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
dan9a947222018-06-14 19:06:36 +00001445 FuncDef *pFunc = pWin->pFunc;
dan2e605682018-06-07 15:54:26 +00001446 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
dan2a11bb22018-06-11 20:50:25 +00001447 nArg = MAX(nArg, windowArgCount(pWin));
drh19dc4d42018-07-08 01:02:26 +00001448 if( pFunc->zName==nth_valueName
1449 || pFunc->zName==first_valueName
dan7095c002018-06-07 17:45:22 +00001450 ){
dan2e605682018-06-07 15:54:26 +00001451 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp);
1452 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
1453 }
dan9a947222018-06-14 19:06:36 +00001454
1455 if( (pFunc->funcFlags & SQLITE_FUNC_MINMAX) && pWin->csrApp ){
1456 assert( pWin->eStart!=TK_UNBOUNDED );
1457 sqlite3VdbeAddOp1(v, OP_ResetSorter, pWin->csrApp);
1458 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
1459 }
dan2e605682018-06-07 15:54:26 +00001460 }
1461 regArg = pParse->nMem+1;
1462 pParse->nMem += nArg;
1463 return regArg;
1464}
1465
dancc7a8502019-03-11 19:50:54 +00001466#if 0
danb33487b2019-03-06 17:12:32 +00001467/*
dancc7a8502019-03-11 19:50:54 +00001468** Return true if the current frame should be cached in the ephemeral table,
1469** even if there are no xInverse() calls required.
danb33487b2019-03-06 17:12:32 +00001470*/
dancc7a8502019-03-11 19:50:54 +00001471static int windowCacheFrame(Window *pMWin){
danb33487b2019-03-06 17:12:32 +00001472 Window *pWin;
1473 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1474 FuncDef *pFunc = pWin->pFunc;
dancc7a8502019-03-11 19:50:54 +00001475 if( (pFunc->zName==nth_valueName)
danb33487b2019-03-06 17:12:32 +00001476 || (pFunc->zName==first_valueName)
dancc7a8502019-03-11 19:50:54 +00001477 || (pFunc->zName==leadName) */
danb33487b2019-03-06 17:12:32 +00001478 || (pFunc->zName==lagName)
1479 ){
1480 return 1;
1481 }
1482 }
1483 return 0;
1484}
dancc7a8502019-03-11 19:50:54 +00001485#endif
danb33487b2019-03-06 17:12:32 +00001486
dan6c75b392019-03-08 20:02:52 +00001487/*
1488** regOld and regNew are each the first register in an array of size
1489** pOrderBy->nExpr. This function generates code to compare the two
1490** arrays of registers using the collation sequences and other comparison
1491** parameters specified by pOrderBy.
1492**
1493** If the two arrays are not equal, the contents of regNew is copied to
1494** regOld and control falls through. Otherwise, if the contents of the arrays
1495** are equal, an OP_Goto is executed. The address of the OP_Goto is returned.
1496*/
1497static int windowIfNewPeer(
1498 Parse *pParse,
1499 ExprList *pOrderBy,
1500 int regNew, /* First in array of new values */
1501 int regOld /* First in array of old values */
1502){
1503 Vdbe *v = sqlite3GetVdbe(pParse);
1504 int addr;
1505 if( pOrderBy ){
1506 int nVal = pOrderBy->nExpr;
1507 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pOrderBy, 0, 0);
1508 sqlite3VdbeAddOp3(v, OP_Compare, regOld, regNew, nVal);
1509 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
1510 addr = sqlite3VdbeAddOp3(
1511 v, OP_Jump, sqlite3VdbeCurrentAddr(v)+1, 0, sqlite3VdbeCurrentAddr(v)+1
dan72b9fdc2019-03-09 20:49:17 +00001512 );
dan6c75b392019-03-08 20:02:52 +00001513 VdbeCoverageEqNe(v);
1514 sqlite3VdbeAddOp3(v, OP_Copy, regNew, regOld, nVal-1);
1515 }else{
1516 addr = sqlite3VdbeAddOp0(v, OP_Goto);
1517 }
1518 return addr;
1519}
1520
dan00267b82019-03-06 21:04:11 +00001521typedef struct WindowCodeArg WindowCodeArg;
dan6c75b392019-03-08 20:02:52 +00001522typedef struct WindowCsrAndReg WindowCsrAndReg;
1523struct WindowCsrAndReg {
1524 int csr;
1525 int reg;
1526};
dan00267b82019-03-06 21:04:11 +00001527struct WindowCodeArg {
1528 Parse *pParse;
1529 Window *pMWin;
1530 Vdbe *pVdbe;
1531 int regGosub;
1532 int addrGosub;
1533 int regArg;
dan6c75b392019-03-08 20:02:52 +00001534
1535 WindowCsrAndReg start;
1536 WindowCsrAndReg current;
1537 WindowCsrAndReg end;
dan00267b82019-03-06 21:04:11 +00001538};
1539
1540#define WINDOW_RETURN_ROW 1
1541#define WINDOW_AGGINVERSE 2
1542#define WINDOW_AGGSTEP 3
1543
dan6c75b392019-03-08 20:02:52 +00001544/*
1545** Generate VM code to read the window frames peer values from cursor csr into
1546** an array of registers starting at reg.
1547*/
1548static void windowReadPeerValues(
1549 WindowCodeArg *p,
1550 int csr,
1551 int reg
1552){
1553 Window *pMWin = p->pMWin;
1554 ExprList *pOrderBy = pMWin->pOrderBy;
1555 if( pOrderBy ){
1556 Vdbe *v = sqlite3GetVdbe(p->pParse);
1557 ExprList *pPart = pMWin->pPartition;
1558 int iColOff = pMWin->nBufferCol + (pPart ? pPart->nExpr : 0);
1559 int i;
1560 for(i=0; i<pOrderBy->nExpr; i++){
1561 sqlite3VdbeAddOp3(v, OP_Column, csr, iColOff+i, reg+i);
1562 }
1563 }
1564}
1565
dan72b9fdc2019-03-09 20:49:17 +00001566/*
1567** This function is called as part of generating VM programs for RANGE
1568** offset PRECEDING/FOLLOWING frame boundaries. It generates code equivalent
1569** to:
1570**
1571** if( csr1.peerVal + regVal >= csr2.peerVal ) goto lbl;
1572** if( csr1.rowid >= csr2.rowid ) goto lbl;
1573*/
1574static void windowCodeRangeTest(
1575 WindowCodeArg *p,
1576 int op, /* OP_Ge or OP_Gt */
1577 int csr1,
1578 int regVal,
1579 int csr2,
1580 int lbl
1581){
1582 Parse *pParse = p->pParse;
1583 Vdbe *v = sqlite3GetVdbe(pParse);
1584 int reg1 = sqlite3GetTempReg(pParse);
1585 int reg2 = sqlite3GetTempReg(pParse);
dan71fddaf2019-03-11 11:12:34 +00001586 int arith = OP_Add;
1587
1588 assert( op==OP_Ge || op==OP_Gt || op==OP_Le );
1589 assert( p->pMWin->pOrderBy && p->pMWin->pOrderBy->nExpr==1 );
1590 if( p->pMWin->pOrderBy->a[0].sortOrder ){
1591 switch( op ){
1592 case OP_Ge: op = OP_Le; break;
1593 case OP_Gt: op = OP_Lt; break;
1594 default: assert( op==OP_Le ); op = OP_Ge; break;
1595 }
1596 arith = OP_Subtract;
1597 }
1598
dan72b9fdc2019-03-09 20:49:17 +00001599 windowReadPeerValues(p, csr1, reg1);
1600 windowReadPeerValues(p, csr2, reg2);
dan71fddaf2019-03-11 11:12:34 +00001601 sqlite3VdbeAddOp3(v, arith, regVal, reg1, reg1);
dan72b9fdc2019-03-09 20:49:17 +00001602 sqlite3VdbeAddOp3(v, op, reg2, lbl, reg1);
1603 sqlite3VdbeAddOp2(v, OP_Rowid, csr1, reg1);
1604 sqlite3VdbeAddOp2(v, OP_Rowid, csr2, reg2);
1605 sqlite3VdbeAddOp3(v, OP_Gt, reg2, lbl, reg1);
1606 sqlite3ReleaseTempReg(pParse, reg1);
1607 sqlite3ReleaseTempReg(pParse, reg2);
dan72b9fdc2019-03-09 20:49:17 +00001608}
1609
dan00267b82019-03-06 21:04:11 +00001610static int windowCodeOp(
1611 WindowCodeArg *p,
1612 int op,
dan00267b82019-03-06 21:04:11 +00001613 int regCountdown,
1614 int jumpOnEof
1615){
dan6c75b392019-03-08 20:02:52 +00001616 int csr, reg;
1617 Parse *pParse = p->pParse;
dan54975cd2019-03-07 20:47:46 +00001618 Window *pMWin = p->pMWin;
dan00267b82019-03-06 21:04:11 +00001619 int ret = 0;
1620 Vdbe *v = p->pVdbe;
1621 int addrIf = 0;
dan6c75b392019-03-08 20:02:52 +00001622 int addrContinue = 0;
1623 int addrGoto = 0;
1624 int bPeer = (pMWin->eType!=TK_ROWS);
dan00267b82019-03-06 21:04:11 +00001625
dan72b9fdc2019-03-09 20:49:17 +00001626 int lblDone = sqlite3VdbeMakeLabel(pParse);
1627 int addrNextRange = 0;
1628
dan54975cd2019-03-07 20:47:46 +00001629 /* Special case - WINDOW_AGGINVERSE is always a no-op if the frame
1630 ** starts with UNBOUNDED PRECEDING. */
1631 if( op==WINDOW_AGGINVERSE && pMWin->eStart==TK_UNBOUNDED ){
1632 assert( regCountdown==0 && jumpOnEof==0 );
1633 return 0;
1634 }
1635
dan00267b82019-03-06 21:04:11 +00001636 if( regCountdown>0 ){
dan72b9fdc2019-03-09 20:49:17 +00001637 if( pMWin->eType==TK_RANGE ){
1638 addrNextRange = sqlite3VdbeCurrentAddr(v);
1639
1640 switch( op ){
1641 case WINDOW_RETURN_ROW: {
1642 assert( 0 );
1643 break;
1644 }
1645
1646 case WINDOW_AGGINVERSE: {
1647 if( pMWin->eStart==TK_FOLLOWING ){
1648 windowCodeRangeTest(
1649 p, OP_Le, p->current.csr, regCountdown, p->start.csr, lblDone
1650 );
1651 }else{
1652 windowCodeRangeTest(
1653 p, OP_Ge, p->start.csr, regCountdown, p->current.csr, lblDone
1654 );
1655 }
1656 break;
1657 }
1658
1659 case WINDOW_AGGSTEP: {
1660 windowCodeRangeTest(
1661 p, OP_Gt, p->end.csr, regCountdown, p->current.csr, lblDone
1662 );
1663 break;
1664 }
1665 }
1666
1667 }else{
1668 addrIf = sqlite3VdbeAddOp3(v, OP_IfPos, regCountdown, 0, 1);
1669 }
dan00267b82019-03-06 21:04:11 +00001670 }
1671
dan6c75b392019-03-08 20:02:52 +00001672 if( op==WINDOW_RETURN_ROW ){
1673 windowAggFinal(pParse, pMWin, 0);
1674 }
1675 addrContinue = sqlite3VdbeCurrentAddr(v);
dan00267b82019-03-06 21:04:11 +00001676 switch( op ){
1677 case WINDOW_RETURN_ROW:
dan6c75b392019-03-08 20:02:52 +00001678 csr = p->current.csr;
1679 reg = p->current.reg;
1680 windowReturnOneRow(pParse, pMWin, p->regGosub, p->addrGosub);
dan00267b82019-03-06 21:04:11 +00001681 break;
1682
1683 case WINDOW_AGGINVERSE:
dan6c75b392019-03-08 20:02:52 +00001684 csr = p->start.csr;
1685 reg = p->start.reg;
dancc7a8502019-03-11 19:50:54 +00001686 windowAggStep(pParse, pMWin, csr, 1, p->regArg, 0);
dan00267b82019-03-06 21:04:11 +00001687 break;
1688
1689 case WINDOW_AGGSTEP:
dan6c75b392019-03-08 20:02:52 +00001690 csr = p->end.csr;
1691 reg = p->end.reg;
dancc7a8502019-03-11 19:50:54 +00001692 windowAggStep(pParse, pMWin, csr, 0, p->regArg, 0);
dan00267b82019-03-06 21:04:11 +00001693 break;
1694 }
1695
danc8137502019-03-07 19:26:17 +00001696 if( jumpOnEof ){
1697 sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+2);
1698 ret = sqlite3VdbeAddOp0(v, OP_Goto);
1699 }else{
dan6c75b392019-03-08 20:02:52 +00001700 sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+1+bPeer);
1701 if( bPeer ){
1702 addrGoto = sqlite3VdbeAddOp0(v, OP_Goto);
1703 }
dan00267b82019-03-06 21:04:11 +00001704 }
danc8137502019-03-07 19:26:17 +00001705
dan6c75b392019-03-08 20:02:52 +00001706 if( bPeer ){
1707 int addr;
1708 int nReg = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);
1709 int regTmp = (nReg ? sqlite3GetTempRange(pParse, nReg) : 0);
1710 windowReadPeerValues(p, csr, regTmp);
1711 addr = windowIfNewPeer(pParse, pMWin->pOrderBy, regTmp, reg);
1712 sqlite3VdbeChangeP2(v, addr, addrContinue);
1713 sqlite3ReleaseTempRange(pParse, regTmp, nReg);
dan00267b82019-03-06 21:04:11 +00001714 }
dan6c75b392019-03-08 20:02:52 +00001715
dan72b9fdc2019-03-09 20:49:17 +00001716 if( addrNextRange ){
1717 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNextRange);
1718 }
1719 sqlite3VdbeResolveLabel(v, lblDone);
dan6c75b392019-03-08 20:02:52 +00001720 if( addrGoto ) sqlite3VdbeJumpHere(v, addrGoto);
1721 if( addrIf ) sqlite3VdbeJumpHere(v, addrIf);
dan00267b82019-03-06 21:04:11 +00001722 return ret;
1723}
1724
dana786e452019-03-11 18:17:04 +00001725
dan00267b82019-03-06 21:04:11 +00001726/*
dana786e452019-03-11 18:17:04 +00001727** Allocate and return a duplicate of the Window object indicated by the
1728** third argument. Set the Window.pOwner field of the new object to
1729** pOwner.
1730*/
1731Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p){
1732 Window *pNew = 0;
1733 if( ALWAYS(p) ){
1734 pNew = sqlite3DbMallocZero(db, sizeof(Window));
1735 if( pNew ){
1736 pNew->zName = sqlite3DbStrDup(db, p->zName);
1737 pNew->pFilter = sqlite3ExprDup(db, p->pFilter, 0);
1738 pNew->pFunc = p->pFunc;
1739 pNew->pPartition = sqlite3ExprListDup(db, p->pPartition, 0);
1740 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, 0);
1741 pNew->eType = p->eType;
1742 pNew->eEnd = p->eEnd;
1743 pNew->eStart = p->eStart;
1744 pNew->pStart = sqlite3ExprDup(db, p->pStart, 0);
1745 pNew->pEnd = sqlite3ExprDup(db, p->pEnd, 0);
1746 pNew->pOwner = pOwner;
1747 }
1748 }
1749 return pNew;
1750}
1751
1752/*
1753** Return a copy of the linked list of Window objects passed as the
1754** second argument.
1755*/
1756Window *sqlite3WindowListDup(sqlite3 *db, Window *p){
1757 Window *pWin;
1758 Window *pRet = 0;
1759 Window **pp = &pRet;
1760
1761 for(pWin=p; pWin; pWin=pWin->pNextWin){
1762 *pp = sqlite3WindowDup(db, 0, pWin);
1763 if( *pp==0 ) break;
1764 pp = &((*pp)->pNextWin);
1765 }
1766
1767 return pRet;
1768}
1769
1770/*
1771** sqlite3WhereBegin() has already been called for the SELECT statement
1772** passed as the second argument when this function is invoked. It generates
1773** code to populate the Window.regResult register for each window function
1774** and invoke the sub-routine at instruction addrGosub once for each row.
1775** sqlite3WhereEnd() is always called before returning.
dan00267b82019-03-06 21:04:11 +00001776**
dana786e452019-03-11 18:17:04 +00001777** This function handles several different types of window frames, which
1778** require slightly different processing. The following pseudo code is
1779** used to implement window frames of the form:
dan00267b82019-03-06 21:04:11 +00001780**
dana786e452019-03-11 18:17:04 +00001781** ROWS BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
dan00267b82019-03-06 21:04:11 +00001782**
dana786e452019-03-11 18:17:04 +00001783** Other window frame types use variants of the following:
1784**
1785** ... loop started by sqlite3WhereBegin() ...
dan00267b82019-03-06 21:04:11 +00001786** if( new partition ){
1787** Gosub flush
dana786e452019-03-11 18:17:04 +00001788** }
dan00267b82019-03-06 21:04:11 +00001789** Insert new row into eph table.
dana786e452019-03-11 18:17:04 +00001790**
dan00267b82019-03-06 21:04:11 +00001791** if( first row of partition ){
dana786e452019-03-11 18:17:04 +00001792** // Rewind three cursors, all open on the eph table.
1793** Rewind(csrEnd);
1794** Rewind(csrStart);
1795** Rewind(csrCurrent);
1796**
dan00267b82019-03-06 21:04:11 +00001797** regEnd = <expr2> // FOLLOWING expression
1798** regStart = <expr1> // PRECEDING expression
1799** }else{
dana786e452019-03-11 18:17:04 +00001800** // First time this branch is taken, the eph table contains two
1801** // rows. The first row in the partition, which all three cursors
1802** // currently point to, and the following row.
1803** AGGSTEP
dan00267b82019-03-06 21:04:11 +00001804** if( (regEnd--)<=0 ){
dana786e452019-03-11 18:17:04 +00001805** RETURN_ROW
1806** if( (regStart--)<=0 ){
1807** AGGINVERSE
dan00267b82019-03-06 21:04:11 +00001808** }
1809** }
dana786e452019-03-11 18:17:04 +00001810** }
1811** }
dan00267b82019-03-06 21:04:11 +00001812** flush:
dana786e452019-03-11 18:17:04 +00001813** AGGSTEP
1814** while( 1 ){
1815** RETURN ROW
1816** if( csrCurrent is EOF ) break;
1817** if( (regStart--)<=0 ){
1818** AggInverse(csrStart)
1819** Next(csrStart)
dan00267b82019-03-06 21:04:11 +00001820** }
dana786e452019-03-11 18:17:04 +00001821** }
dan00267b82019-03-06 21:04:11 +00001822**
dana786e452019-03-11 18:17:04 +00001823** The pseudo-code above uses the following shorthand:
dan00267b82019-03-06 21:04:11 +00001824**
dana786e452019-03-11 18:17:04 +00001825** AGGSTEP: invoke the aggregate xStep() function for each window function
1826** with arguments read from the current row of cursor csrEnd, then
1827** step cursor csrEnd forward one row (i.e. sqlite3BtreeNext()).
1828**
1829** RETURN_ROW: return a row to the caller based on the contents of the
1830** current row of csrCurrent and the current state of all
1831** aggregates. Then step cursor csrCurrent forward one row.
1832**
1833** AGGINVERSE: invoke the aggregate xInverse() function for each window
1834** functions with arguments read from the current row of cursor
1835** csrStart. Then step csrStart forward one row.
1836**
1837** There are two other ROWS window frames that are handled significantly
1838** differently from the above - "BETWEEN <expr> PRECEDING AND <expr> PRECEDING"
1839** and "BETWEEN <expr> FOLLOWING AND <expr> FOLLOWING". These are special
1840** cases because they change the order in which the three cursors (csrStart,
1841** csrCurrent and csrEnd) iterate through the ephemeral table. Cases that
1842** use UNBOUNDED or CURRENT ROW are much simpler variations on one of these
1843** three.
1844**
1845** ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
1846**
1847** ... loop started by sqlite3WhereBegin() ...
dan00267b82019-03-06 21:04:11 +00001848** if( new partition ){
1849** Gosub flush
dana786e452019-03-11 18:17:04 +00001850** }
dan00267b82019-03-06 21:04:11 +00001851** Insert new row into eph table.
1852** if( first row of partition ){
dana786e452019-03-11 18:17:04 +00001853** Rewind(csrEnd)
1854** Rewind(csrStart)
1855** Rewind(csrCurrent)
1856** regEnd = <expr2>
1857** regStart = <expr1>
dan00267b82019-03-06 21:04:11 +00001858** }else{
dana786e452019-03-11 18:17:04 +00001859** if( (regEnd--)<=0 ){
1860** AGGSTEP
1861** }
1862** RETURN_ROW
1863** if( (regStart--)<=0 ){
1864** AGGINVERSE
1865** }
1866** }
1867** }
dan00267b82019-03-06 21:04:11 +00001868** flush:
dana786e452019-03-11 18:17:04 +00001869** if( (regEnd--)<=0 ){
1870** AGGSTEP
1871** }
1872** RETURN_ROW
1873**
1874**
1875** ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
1876**
1877** ... loop started by sqlite3WhereBegin() ...
1878** if( new partition ){
1879** Gosub flush
1880** }
1881** Insert new row into eph table.
1882** if( first row of partition ){
1883** Rewind(csrEnd)
1884** Rewind(csrStart)
1885** Rewind(csrCurrent)
1886** regEnd = <expr2>
1887** regStart = regEnd - <expr1>
1888** }else{
1889** AGGSTEP
1890** if( (regEnd--)<=0 ){
1891** RETURN_ROW
1892** }
1893** if( (regStart--)<=0 ){
1894** AGGINVERSE
1895** }
1896** }
1897** }
1898** flush:
1899** AGGSTEP
1900** while( 1 ){
1901** if( (regEnd--)<=0 ){
1902** RETURN_ROW
1903** if( eof ) break;
1904** }
1905** if( (regStart--)<=0 ){
1906** AGGINVERSE
1907** if( eof ) break
1908** }
1909** }
1910** while( !eof csrCurrent ){
1911** RETURN_ROW
1912** }
1913**
1914** For the most part, the patterns above are adapted to support UNBOUNDED by
1915** assuming that it is equivalent to "infinity PRECEDING/FOLLOWING" and
1916** CURRENT ROW by assuming that it is equivilent to "0 PRECEDING/FOLLOWING".
1917** This is optimized of course - branches that will never be taken and
1918** conditions that are always true are omitted from the VM code. The only
1919** exceptional case is:
1920**
1921** ROWS BETWEEN <expr1> FOLLOWING AND UNBOUNDED FOLLOWING
1922**
1923** ... loop started by sqlite3WhereBegin() ...
1924** if( new partition ){
1925** Gosub flush
1926** }
1927** Insert new row into eph table.
1928** if( first row of partition ){
1929** Rewind(csrEnd)
1930** Rewind(csrStart)
1931** Rewind(csrCurrent)
1932** regStart = <expr1>
1933** }else{
1934** AGGSTEP
1935** }
1936** }
1937** flush:
1938** AGGSTEP
1939** while( 1 ){
1940** if( (regStart--)<=0 ){
1941** AGGINVERSE
1942** if( eof ) break
1943** }
1944** RETURN_ROW
1945** }
1946** while( !eof csrCurrent ){
1947** RETURN_ROW
1948** }
dan00267b82019-03-06 21:04:11 +00001949*/
dana786e452019-03-11 18:17:04 +00001950void sqlite3WindowCodeStep(
dancc7a8502019-03-11 19:50:54 +00001951 Parse *pParse, /* Parse context */
dana786e452019-03-11 18:17:04 +00001952 Select *p, /* Rewritten SELECT statement */
1953 WhereInfo *pWInfo, /* Context returned by sqlite3WhereBegin() */
1954 int regGosub, /* Register for OP_Gosub */
1955 int addrGosub /* OP_Gosub here to return each row */
dan680f6e82019-03-04 21:07:11 +00001956){
1957 Window *pMWin = p->pWin;
dan6c75b392019-03-08 20:02:52 +00001958 ExprList *pOrderBy = pMWin->pOrderBy;
dan680f6e82019-03-04 21:07:11 +00001959 Vdbe *v = sqlite3GetVdbe(pParse);
1960 int regFlushPart; /* Register for "Gosub flush_partition" */
dana786e452019-03-11 18:17:04 +00001961 int csrWrite; /* Cursor used to write to eph. table */
1962 int csrInput = p->pSrc->a[0].iCursor; /* Cursor of sub-select */
1963 int nInput = p->pSrc->a[0].pTab->nCol; /* Number of cols returned by sub */
1964 int iInput; /* To iterate through sub cols */
1965 int addrGoto; /* Address of OP_Goto */
1966 int addrIfNot; /* Address of OP_IfNot */
1967 int addrGosubFlush; /* Address of OP_Gosub to flush: */
1968 int addrInteger; /* Address of OP_Integer */
danb25a2142019-03-05 19:29:36 +00001969 int addrShortcut = 0;
dana786e452019-03-11 18:17:04 +00001970 int addrEmpty = 0; /* Address of OP_Rewind in flush: */
1971 int addrPeerJump = 0; /* Address of jump taken if not new peer */
dan54975cd2019-03-07 20:47:46 +00001972 int regStart = 0; /* Value of <expr> PRECEDING */
1973 int regEnd = 0; /* Value of <expr> FOLLOWING */
dana786e452019-03-11 18:17:04 +00001974 int regNew; /* Array of registers holding new input row */
1975 int regRecord; /* regNew array in record form */
1976 int regRowid; /* Rowid for regRecord in eph table */
1977 int regNewPeer = 0; /* Peer values for new row (part of regNew) */
1978 int regPeer = 0; /* Peer values for current row */
1979 WindowCodeArg s; /* Context object for sub-routines */
dan680f6e82019-03-04 21:07:11 +00001980
dan72b9fdc2019-03-09 20:49:17 +00001981 assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_CURRENT
1982 || pMWin->eStart==TK_FOLLOWING || pMWin->eStart==TK_UNBOUNDED
1983 );
1984 assert( pMWin->eEnd==TK_FOLLOWING || pMWin->eEnd==TK_CURRENT
1985 || pMWin->eEnd==TK_UNBOUNDED || pMWin->eEnd==TK_PRECEDING
1986 );
1987
dana786e452019-03-11 18:17:04 +00001988 /* Determine whether or not each partition will be cached before beginning
1989 ** to process rows within it. */
dana786e452019-03-11 18:17:04 +00001990
1991 /* Fill in the context object */
dan00267b82019-03-06 21:04:11 +00001992 memset(&s, 0, sizeof(WindowCodeArg));
1993 s.pParse = pParse;
1994 s.pMWin = pMWin;
1995 s.pVdbe = v;
1996 s.regGosub = regGosub;
1997 s.addrGosub = addrGosub;
dan6c75b392019-03-08 20:02:52 +00001998 s.current.csr = pMWin->iEphCsr;
dana786e452019-03-11 18:17:04 +00001999 csrWrite = s.current.csr+1;
dan6c75b392019-03-08 20:02:52 +00002000 s.start.csr = s.current.csr+2;
2001 s.end.csr = s.current.csr+3;
danb33487b2019-03-06 17:12:32 +00002002
dana786e452019-03-11 18:17:04 +00002003 regNew = pParse->nMem+1;
2004 pParse->nMem += nInput;
2005 regRecord = ++pParse->nMem;
2006 regRowid = ++pParse->nMem;
dan680f6e82019-03-04 21:07:11 +00002007 regFlushPart = ++pParse->nMem;
dan54975cd2019-03-07 20:47:46 +00002008
dana786e452019-03-11 18:17:04 +00002009 /* If the window frame contains an "<expr> PRECEDING" or "<expr> FOLLOWING"
2010 ** clause, allocate registers to store the results of evaluating each
2011 ** <expr>. */
dan54975cd2019-03-07 20:47:46 +00002012 if( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_FOLLOWING ){
2013 regStart = ++pParse->nMem;
2014 }
2015 if( pMWin->eEnd==TK_PRECEDING || pMWin->eEnd==TK_FOLLOWING ){
2016 regEnd = ++pParse->nMem;
2017 }
dan680f6e82019-03-04 21:07:11 +00002018
dan72b9fdc2019-03-09 20:49:17 +00002019 /* If this is not a "ROWS BETWEEN ..." frame, then allocate arrays of
dana786e452019-03-11 18:17:04 +00002020 ** registers to store copies of the ORDER BY expressions (peer values)
2021 ** for the main loop, and for each cursor (start, current and end). */
dan6c75b392019-03-08 20:02:52 +00002022 if( pMWin->eType!=TK_ROWS ){
2023 int nPeer = (pOrderBy ? pOrderBy->nExpr : 0);
dana786e452019-03-11 18:17:04 +00002024 regNewPeer = regNew + pMWin->nBufferCol;
dan6c75b392019-03-08 20:02:52 +00002025 if( pMWin->pPartition ) regNewPeer += pMWin->pPartition->nExpr;
dan6c75b392019-03-08 20:02:52 +00002026 regPeer = pParse->nMem+1; pParse->nMem += nPeer;
2027 s.start.reg = pParse->nMem+1; pParse->nMem += nPeer;
2028 s.current.reg = pParse->nMem+1; pParse->nMem += nPeer;
2029 s.end.reg = pParse->nMem+1; pParse->nMem += nPeer;
2030 }
2031
dan680f6e82019-03-04 21:07:11 +00002032 /* Load the column values for the row returned by the sub-select
dana786e452019-03-11 18:17:04 +00002033 ** into an array of registers starting at regNew. Assemble them into
2034 ** a record in register regRecord. */
2035 for(iInput=0; iInput<nInput; iInput++){
2036 sqlite3VdbeAddOp3(v, OP_Column, csrInput, iInput, regNew+iInput);
dan680f6e82019-03-04 21:07:11 +00002037 }
dana786e452019-03-11 18:17:04 +00002038 sqlite3VdbeAddOp3(v, OP_MakeRecord, regNew, nInput, regRecord);
dan680f6e82019-03-04 21:07:11 +00002039
danb33487b2019-03-06 17:12:32 +00002040 /* An input row has just been read into an array of registers starting
dana786e452019-03-11 18:17:04 +00002041 ** at regNew. If the window has a PARTITION clause, this block generates
danb33487b2019-03-06 17:12:32 +00002042 ** VM code to check if the input row is the start of a new partition.
2043 ** If so, it does an OP_Gosub to an address to be filled in later. The
dana786e452019-03-11 18:17:04 +00002044 ** address of the OP_Gosub is stored in local variable addrGosubFlush. */
dan680f6e82019-03-04 21:07:11 +00002045 if( pMWin->pPartition ){
2046 int addr;
2047 ExprList *pPart = pMWin->pPartition;
2048 int nPart = pPart->nExpr;
dana786e452019-03-11 18:17:04 +00002049 int regNewPart = regNew + pMWin->nBufferCol;
dan680f6e82019-03-04 21:07:11 +00002050 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pPart, 0, 0);
2051
dan680f6e82019-03-04 21:07:11 +00002052 addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPart, pMWin->regPart, nPart);
2053 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
danb33487b2019-03-06 17:12:32 +00002054 sqlite3VdbeAddOp3(v, OP_Jump, addr+2, addr+4, addr+2);
dan680f6e82019-03-04 21:07:11 +00002055 VdbeCoverageEqNe(v);
2056 addrGosubFlush = sqlite3VdbeAddOp1(v, OP_Gosub, regFlushPart);
2057 VdbeComment((v, "call flush_partition"));
danb33487b2019-03-06 17:12:32 +00002058 sqlite3VdbeAddOp3(v, OP_Copy, regNewPart, pMWin->regPart, nPart-1);
dan680f6e82019-03-04 21:07:11 +00002059 }
2060
2061 /* Insert the new row into the ephemeral table */
2062 sqlite3VdbeAddOp2(v, OP_NewRowid, csrWrite, regRowid);
2063 sqlite3VdbeAddOp3(v, OP_Insert, csrWrite, regRecord, regRowid);
2064
dancc7a8502019-03-11 19:50:54 +00002065 addrIfNot = sqlite3VdbeAddOp1(v, OP_IfNot, pMWin->regFirst);
danb25a2142019-03-05 19:29:36 +00002066
danb33487b2019-03-06 17:12:32 +00002067 /* This block is run for the first row of each partition */
dana786e452019-03-11 18:17:04 +00002068 s.regArg = windowInitAccum(pParse, pMWin);
dan680f6e82019-03-04 21:07:11 +00002069
dan54975cd2019-03-07 20:47:46 +00002070 if( regStart ){
2071 sqlite3ExprCode(pParse, pMWin->pStart, regStart);
2072 windowCheckIntValue(pParse, regStart, 0);
2073 }
2074 if( regEnd ){
2075 sqlite3ExprCode(pParse, pMWin->pEnd, regEnd);
2076 windowCheckIntValue(pParse, regEnd, 1);
2077 }
danb25a2142019-03-05 19:29:36 +00002078
dan54975cd2019-03-07 20:47:46 +00002079 if( pMWin->eStart==pMWin->eEnd && regStart && regEnd ){
danb25a2142019-03-05 19:29:36 +00002080 int op = ((pMWin->eStart==TK_FOLLOWING) ? OP_Ge : OP_Le);
2081 int addrGe = sqlite3VdbeAddOp3(v, op, regStart, 0, regEnd);
2082 windowAggFinal(pParse, pMWin, 0);
dancc7a8502019-03-11 19:50:54 +00002083 sqlite3VdbeAddOp2(v, OP_Rewind, s.current.csr, 1);
2084 windowReturnOneRow(pParse, pMWin, regGosub, addrGosub);
2085 sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr);
danb25a2142019-03-05 19:29:36 +00002086 addrShortcut = sqlite3VdbeAddOp0(v, OP_Goto);
2087 sqlite3VdbeJumpHere(v, addrGe);
2088 }
dan72b9fdc2019-03-09 20:49:17 +00002089 if( pMWin->eStart==TK_FOLLOWING && pMWin->eType!=TK_RANGE && regEnd ){
dan54975cd2019-03-07 20:47:46 +00002090 assert( pMWin->eEnd==TK_FOLLOWING );
danb25a2142019-03-05 19:29:36 +00002091 sqlite3VdbeAddOp3(v, OP_Subtract, regStart, regEnd, regStart);
2092 }
2093
dan54975cd2019-03-07 20:47:46 +00002094 if( pMWin->eStart!=TK_UNBOUNDED ){
dan6c75b392019-03-08 20:02:52 +00002095 sqlite3VdbeAddOp2(v, OP_Rewind, s.start.csr, 1);
dan54975cd2019-03-07 20:47:46 +00002096 }
dan6c75b392019-03-08 20:02:52 +00002097 sqlite3VdbeAddOp2(v, OP_Rewind, s.current.csr, 1);
2098 sqlite3VdbeAddOp2(v, OP_Rewind, s.end.csr, 1);
2099 if( regPeer && pOrderBy ){
dancc7a8502019-03-11 19:50:54 +00002100 sqlite3VdbeAddOp3(v, OP_Copy, regNewPeer, regPeer, pOrderBy->nExpr-1);
dan6c75b392019-03-08 20:02:52 +00002101 sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.start.reg, pOrderBy->nExpr-1);
2102 sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.current.reg, pOrderBy->nExpr-1);
2103 sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.end.reg, pOrderBy->nExpr-1);
2104 }
danb25a2142019-03-05 19:29:36 +00002105
2106 sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regFirst);
dan680f6e82019-03-04 21:07:11 +00002107 addrGoto = sqlite3VdbeAddOp0(v, OP_Goto);
2108
dan00267b82019-03-06 21:04:11 +00002109 /* Begin generating SECOND_ROW_CODE */
dana786e452019-03-11 18:17:04 +00002110 VdbeModuleComment((pParse->pVdbe, "Begin WindowCodeStep.SECOND_ROW"));
dancc7a8502019-03-11 19:50:54 +00002111 sqlite3VdbeJumpHere(v, addrIfNot);
dan6c75b392019-03-08 20:02:52 +00002112 if( regPeer ){
2113 addrPeerJump = windowIfNewPeer(pParse, pOrderBy, regNewPeer, regPeer);
2114 }
danb25a2142019-03-05 19:29:36 +00002115 if( pMWin->eStart==TK_FOLLOWING ){
dan6c75b392019-03-08 20:02:52 +00002116 windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
dan54975cd2019-03-07 20:47:46 +00002117 if( pMWin->eEnd!=TK_UNBOUNDED ){
dan72b9fdc2019-03-09 20:49:17 +00002118 if( pMWin->eType==TK_RANGE ){
2119 int lbl = sqlite3VdbeMakeLabel(pParse);
2120 int addrNext = sqlite3VdbeCurrentAddr(v);
2121 windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl);
2122 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2123 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
2124 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNext);
2125 sqlite3VdbeResolveLabel(v, lbl);
2126 }else{
2127 windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 0);
2128 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2129 }
dan54975cd2019-03-07 20:47:46 +00002130 }
danb25a2142019-03-05 19:29:36 +00002131 }else
2132 if( pMWin->eEnd==TK_PRECEDING ){
dan6c75b392019-03-08 20:02:52 +00002133 windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0);
2134 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
2135 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
danb25a2142019-03-05 19:29:36 +00002136 }else{
danc8137502019-03-07 19:26:17 +00002137 int addr;
dan6c75b392019-03-08 20:02:52 +00002138 windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
dan54975cd2019-03-07 20:47:46 +00002139 if( pMWin->eEnd!=TK_UNBOUNDED ){
dan72b9fdc2019-03-09 20:49:17 +00002140 if( pMWin->eType==TK_RANGE ){
2141 int lbl;
2142 addr = sqlite3VdbeCurrentAddr(v);
2143 if( regEnd ){
2144 lbl = sqlite3VdbeMakeLabel(pParse);
2145 windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl);
2146 }
2147 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
2148 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2149 if( regEnd ){
2150 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
2151 sqlite3VdbeResolveLabel(v, lbl);
2152 }
2153 }else{
2154 if( regEnd ) addr = sqlite3VdbeAddOp3(v, OP_IfPos, regEnd, 0, 1);
2155 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
2156 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2157 if( regEnd ) sqlite3VdbeJumpHere(v, addr);
2158 }
dan54975cd2019-03-07 20:47:46 +00002159 }
danb25a2142019-03-05 19:29:36 +00002160 }
dan6c75b392019-03-08 20:02:52 +00002161 if( addrPeerJump ){
2162 sqlite3VdbeJumpHere(v, addrPeerJump);
2163 }
dana786e452019-03-11 18:17:04 +00002164 VdbeModuleComment((pParse->pVdbe, "End WindowCodeStep.SECOND_ROW"));
dan680f6e82019-03-04 21:07:11 +00002165
dan680f6e82019-03-04 21:07:11 +00002166 /* End of the main input loop */
danc8137502019-03-07 19:26:17 +00002167 sqlite3VdbeJumpHere(v, addrGoto);
dancc7a8502019-03-11 19:50:54 +00002168 if( addrShortcut>0 ) sqlite3VdbeJumpHere(v, addrShortcut);
2169 sqlite3WhereEnd(pWInfo);
dan680f6e82019-03-04 21:07:11 +00002170
2171 /* Fall through */
dancc7a8502019-03-11 19:50:54 +00002172 if( pMWin->pPartition ){
dan680f6e82019-03-04 21:07:11 +00002173 addrInteger = sqlite3VdbeAddOp2(v, OP_Integer, 0, regFlushPart);
2174 sqlite3VdbeJumpHere(v, addrGosubFlush);
2175 }
2176
dana786e452019-03-11 18:17:04 +00002177 VdbeModuleComment((pParse->pVdbe, "Begin WindowCodeStep.FLUSH"));
danc8137502019-03-07 19:26:17 +00002178 addrEmpty = sqlite3VdbeAddOp1(v, OP_Rewind, csrWrite);
dan00267b82019-03-06 21:04:11 +00002179 if( pMWin->eEnd==TK_PRECEDING ){
dan6c75b392019-03-08 20:02:52 +00002180 windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0);
2181 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
danc8137502019-03-07 19:26:17 +00002182 }else if( pMWin->eStart==TK_FOLLOWING ){
2183 int addrStart;
2184 int addrBreak1;
2185 int addrBreak2;
2186 int addrBreak3;
dan6c75b392019-03-08 20:02:52 +00002187 windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
dan72b9fdc2019-03-09 20:49:17 +00002188 if( pMWin->eType==TK_RANGE ){
2189 addrStart = sqlite3VdbeCurrentAddr(v);
2190 addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1);
2191 addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
2192 }else
dan54975cd2019-03-07 20:47:46 +00002193 if( pMWin->eEnd==TK_UNBOUNDED ){
2194 addrStart = sqlite3VdbeCurrentAddr(v);
dan6c75b392019-03-08 20:02:52 +00002195 addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regStart, 1);
2196 addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, 0, 1);
dan54975cd2019-03-07 20:47:46 +00002197 }else{
2198 assert( pMWin->eEnd==TK_FOLLOWING );
2199 addrStart = sqlite3VdbeCurrentAddr(v);
dan6c75b392019-03-08 20:02:52 +00002200 addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 1);
2201 addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1);
dan54975cd2019-03-07 20:47:46 +00002202 }
danc8137502019-03-07 19:26:17 +00002203 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
2204 sqlite3VdbeJumpHere(v, addrBreak2);
2205 addrStart = sqlite3VdbeCurrentAddr(v);
dan6c75b392019-03-08 20:02:52 +00002206 addrBreak3 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
danc8137502019-03-07 19:26:17 +00002207 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
2208 sqlite3VdbeJumpHere(v, addrBreak1);
2209 sqlite3VdbeJumpHere(v, addrBreak3);
danb25a2142019-03-05 19:29:36 +00002210 }else{
dan00267b82019-03-06 21:04:11 +00002211 int addrBreak;
danc8137502019-03-07 19:26:17 +00002212 int addrStart;
dan6c75b392019-03-08 20:02:52 +00002213 windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
danc8137502019-03-07 19:26:17 +00002214 addrStart = sqlite3VdbeCurrentAddr(v);
dan6c75b392019-03-08 20:02:52 +00002215 addrBreak = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
2216 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
dan00267b82019-03-06 21:04:11 +00002217 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
2218 sqlite3VdbeJumpHere(v, addrBreak);
danb25a2142019-03-05 19:29:36 +00002219 }
2220
danc8137502019-03-07 19:26:17 +00002221 sqlite3VdbeJumpHere(v, addrEmpty);
2222
dan6c75b392019-03-08 20:02:52 +00002223 sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr);
dancc7a8502019-03-11 19:50:54 +00002224 sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regFirst);
dana786e452019-03-11 18:17:04 +00002225 VdbeModuleComment((pParse->pVdbe, "End WindowCodeStep.FLUSH"));
dan680f6e82019-03-04 21:07:11 +00002226 if( pMWin->pPartition ){
2227 sqlite3VdbeChangeP1(v, addrInteger, sqlite3VdbeCurrentAddr(v));
2228 sqlite3VdbeAddOp1(v, OP_Return, regFlushPart);
2229 }
2230}
2231
dan67a9b8e2018-06-22 20:51:35 +00002232#endif /* SQLITE_OMIT_WINDOWFUNC */