blob: 86b849e72387b09b84e3375c1bcd758017f66cfb [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/*
dana0f6b832019-03-14 16:36:20 +0000202** Implementation of built-in window function nth_value(). This
203** implementation is used in "slow mode" only - when the EXCLUDE clause
204** is not set to the default value "NO OTHERS".
205*/
206struct NthValueCtx {
207 i64 nStep;
208 sqlite3_value *pValue;
209};
210static void nth_valueStepFunc(
211 sqlite3_context *pCtx,
212 int nArg,
213 sqlite3_value **apArg
214){
215 struct NthValueCtx *p;
216 p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
217 if( p ){
dan108e6b22019-03-18 18:55:35 +0000218 i64 iVal;
219 switch( sqlite3_value_numeric_type(apArg[1]) ){
220 case SQLITE_INTEGER:
221 iVal = sqlite3_value_int64(apArg[1]);
222 break;
223 case SQLITE_FLOAT: {
224 double fVal = sqlite3_value_double(apArg[1]);
225 if( ((i64)fVal)!=fVal ) goto error_out;
226 iVal = (i64)fVal;
227 break;
228 }
229 default:
230 goto error_out;
231 }
232 if( iVal<=0 ) goto error_out;
233
dana0f6b832019-03-14 16:36:20 +0000234 p->nStep++;
235 if( iVal==p->nStep ){
236 p->pValue = sqlite3_value_dup(apArg[0]);
dan108e6b22019-03-18 18:55:35 +0000237 if( !p->pValue ){
238 sqlite3_result_error_nomem(pCtx);
239 }
dana0f6b832019-03-14 16:36:20 +0000240 }
241 }
242 UNUSED_PARAMETER(nArg);
243 UNUSED_PARAMETER(apArg);
dan108e6b22019-03-18 18:55:35 +0000244 return;
245
246 error_out:
247 sqlite3_result_error(
248 pCtx, "second argument to nth_value must be a positive integer", -1
249 );
dana0f6b832019-03-14 16:36:20 +0000250}
dana0f6b832019-03-14 16:36:20 +0000251static void nth_valueFinalizeFunc(sqlite3_context *pCtx){
252 struct NthValueCtx *p;
dan0525b6f2019-03-18 21:19:40 +0000253 p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, 0);
dana0f6b832019-03-14 16:36:20 +0000254 if( p && p->pValue ){
255 sqlite3_result_value(pCtx, p->pValue);
256 sqlite3_value_free(p->pValue);
257 p->pValue = 0;
258 }
259}
260#define nth_valueInvFunc noopStepFunc
dan0525b6f2019-03-18 21:19:40 +0000261#define nth_valueValueFunc noopValueFunc
dana0f6b832019-03-14 16:36:20 +0000262
danc782a812019-03-15 20:46:19 +0000263static void first_valueStepFunc(
264 sqlite3_context *pCtx,
265 int nArg,
266 sqlite3_value **apArg
267){
268 struct NthValueCtx *p;
269 p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
270 if( p && p->pValue==0 ){
271 p->pValue = sqlite3_value_dup(apArg[0]);
dan108e6b22019-03-18 18:55:35 +0000272 if( !p->pValue ){
273 sqlite3_result_error_nomem(pCtx);
274 }
danc782a812019-03-15 20:46:19 +0000275 }
276 UNUSED_PARAMETER(nArg);
277 UNUSED_PARAMETER(apArg);
278}
danc782a812019-03-15 20:46:19 +0000279static void first_valueFinalizeFunc(sqlite3_context *pCtx){
280 struct NthValueCtx *p;
281 p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
282 if( p && p->pValue ){
283 sqlite3_result_value(pCtx, p->pValue);
284 sqlite3_value_free(p->pValue);
285 p->pValue = 0;
286 }
287}
288#define first_valueInvFunc noopStepFunc
dan0525b6f2019-03-18 21:19:40 +0000289#define first_valueValueFunc noopValueFunc
danc782a812019-03-15 20:46:19 +0000290
dana0f6b832019-03-14 16:36:20 +0000291/*
dan9c277582018-06-20 09:23:49 +0000292** Implementation of built-in window function rank(). Assumes that
293** the window frame has been set to:
294**
295** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
dandfa552f2018-06-02 21:04:28 +0000296*/
297static void rankStepFunc(
298 sqlite3_context *pCtx,
299 int nArg,
300 sqlite3_value **apArg
301){
302 struct CallCount *p;
303 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
drh5d6374f2018-07-10 23:31:17 +0000304 if( p ){
dandfa552f2018-06-02 21:04:28 +0000305 p->nStep++;
306 if( p->nValue==0 ){
307 p->nValue = p->nStep;
308 }
309 }
drhc7bf5712018-07-09 22:49:01 +0000310 UNUSED_PARAMETER(nArg);
311 UNUSED_PARAMETER(apArg);
dandfa552f2018-06-02 21:04:28 +0000312}
dandfa552f2018-06-02 21:04:28 +0000313static void rankValueFunc(sqlite3_context *pCtx){
314 struct CallCount *p;
315 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
316 if( p ){
317 sqlite3_result_int64(pCtx, p->nValue);
318 p->nValue = 0;
319 }
320}
321
322/*
dan9c277582018-06-20 09:23:49 +0000323** Implementation of built-in window function percent_rank(). Assumes that
324** the window frame has been set to:
325**
dancc7a8502019-03-11 19:50:54 +0000326** GROUPS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
dandfa552f2018-06-02 21:04:28 +0000327*/
328static void percent_rankStepFunc(
329 sqlite3_context *pCtx,
330 int nArg,
331 sqlite3_value **apArg
332){
333 struct CallCount *p;
dancc7a8502019-03-11 19:50:54 +0000334 UNUSED_PARAMETER(nArg); assert( nArg==0 );
dandfa552f2018-06-02 21:04:28 +0000335 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
drh5d6374f2018-07-10 23:31:17 +0000336 if( p ){
dancc7a8502019-03-11 19:50:54 +0000337 p->nTotal++;
dandfa552f2018-06-02 21:04:28 +0000338 }
339}
dancc7a8502019-03-11 19:50:54 +0000340static void percent_rankInvFunc(
341 sqlite3_context *pCtx,
342 int nArg,
343 sqlite3_value **apArg
344){
345 struct CallCount *p;
346 UNUSED_PARAMETER(nArg); assert( nArg==0 );
347 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
348 p->nStep++;
349}
dandfa552f2018-06-02 21:04:28 +0000350static void percent_rankValueFunc(sqlite3_context *pCtx){
351 struct CallCount *p;
352 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
353 if( p ){
dancc7a8502019-03-11 19:50:54 +0000354 p->nValue = p->nStep;
dandfa552f2018-06-02 21:04:28 +0000355 if( p->nTotal>1 ){
dancc7a8502019-03-11 19:50:54 +0000356 double r = (double)p->nValue / (double)(p->nTotal-1);
dandfa552f2018-06-02 21:04:28 +0000357 sqlite3_result_double(pCtx, r);
358 }else{
danb7306f62018-06-21 19:20:39 +0000359 sqlite3_result_double(pCtx, 0.0);
dandfa552f2018-06-02 21:04:28 +0000360 }
dandfa552f2018-06-02 21:04:28 +0000361 }
362}
dancc7a8502019-03-11 19:50:54 +0000363#define percent_rankFinalizeFunc percent_rankValueFunc
dandfa552f2018-06-02 21:04:28 +0000364
dan9c277582018-06-20 09:23:49 +0000365/*
366** Implementation of built-in window function cume_dist(). Assumes that
367** the window frame has been set to:
368**
dancc7a8502019-03-11 19:50:54 +0000369** GROUPS BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING
dan9c277582018-06-20 09:23:49 +0000370*/
danf1abe362018-06-04 08:22:09 +0000371static void cume_distStepFunc(
372 sqlite3_context *pCtx,
373 int nArg,
374 sqlite3_value **apArg
375){
376 struct CallCount *p;
dancc7a8502019-03-11 19:50:54 +0000377 UNUSED_PARAMETER(nArg); assert( nArg==0 );
danf1abe362018-06-04 08:22:09 +0000378 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
drh5d6374f2018-07-10 23:31:17 +0000379 if( p ){
dancc7a8502019-03-11 19:50:54 +0000380 p->nTotal++;
danf1abe362018-06-04 08:22:09 +0000381 }
382}
dancc7a8502019-03-11 19:50:54 +0000383static void cume_distInvFunc(
384 sqlite3_context *pCtx,
385 int nArg,
386 sqlite3_value **apArg
387){
388 struct CallCount *p;
389 UNUSED_PARAMETER(nArg); assert( nArg==0 );
390 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
391 p->nStep++;
392}
danf1abe362018-06-04 08:22:09 +0000393static void cume_distValueFunc(sqlite3_context *pCtx){
394 struct CallCount *p;
dan0525b6f2019-03-18 21:19:40 +0000395 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, 0);
396 if( p ){
danf1abe362018-06-04 08:22:09 +0000397 double r = (double)(p->nStep) / (double)(p->nTotal);
398 sqlite3_result_double(pCtx, r);
399 }
400}
dancc7a8502019-03-11 19:50:54 +0000401#define cume_distFinalizeFunc cume_distValueFunc
danf1abe362018-06-04 08:22:09 +0000402
dan2a11bb22018-06-11 20:50:25 +0000403/*
404** Context object for ntile() window function.
405*/
dan6bc5c9e2018-06-04 18:55:11 +0000406struct NtileCtx {
407 i64 nTotal; /* Total rows in partition */
408 i64 nParam; /* Parameter passed to ntile(N) */
409 i64 iRow; /* Current row */
410};
411
412/*
413** Implementation of ntile(). This assumes that the window frame has
414** been coerced to:
415**
dancc7a8502019-03-11 19:50:54 +0000416** ROWS CURRENT ROW AND UNBOUNDED FOLLOWING
dan6bc5c9e2018-06-04 18:55:11 +0000417*/
418static void ntileStepFunc(
419 sqlite3_context *pCtx,
420 int nArg,
421 sqlite3_value **apArg
422){
423 struct NtileCtx *p;
dancc7a8502019-03-11 19:50:54 +0000424 assert( nArg==1 ); UNUSED_PARAMETER(nArg);
dan6bc5c9e2018-06-04 18:55:11 +0000425 p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
drh5d6374f2018-07-10 23:31:17 +0000426 if( p ){
dan6bc5c9e2018-06-04 18:55:11 +0000427 if( p->nTotal==0 ){
428 p->nParam = sqlite3_value_int64(apArg[0]);
dan6bc5c9e2018-06-04 18:55:11 +0000429 if( p->nParam<=0 ){
430 sqlite3_result_error(
431 pCtx, "argument of ntile must be a positive integer", -1
432 );
433 }
434 }
dancc7a8502019-03-11 19:50:54 +0000435 p->nTotal++;
dan6bc5c9e2018-06-04 18:55:11 +0000436 }
437}
dancc7a8502019-03-11 19:50:54 +0000438static void ntileInvFunc(
439 sqlite3_context *pCtx,
440 int nArg,
441 sqlite3_value **apArg
442){
443 struct NtileCtx *p;
444 assert( nArg==1 ); UNUSED_PARAMETER(nArg);
445 p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
446 p->iRow++;
447}
dan6bc5c9e2018-06-04 18:55:11 +0000448static void ntileValueFunc(sqlite3_context *pCtx){
449 struct NtileCtx *p;
450 p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
451 if( p && p->nParam>0 ){
452 int nSize = (p->nTotal / p->nParam);
453 if( nSize==0 ){
dancc7a8502019-03-11 19:50:54 +0000454 sqlite3_result_int64(pCtx, p->iRow+1);
dan6bc5c9e2018-06-04 18:55:11 +0000455 }else{
456 i64 nLarge = p->nTotal - p->nParam*nSize;
457 i64 iSmall = nLarge*(nSize+1);
dancc7a8502019-03-11 19:50:54 +0000458 i64 iRow = p->iRow;
dan6bc5c9e2018-06-04 18:55:11 +0000459
460 assert( (nLarge*(nSize+1) + (p->nParam-nLarge)*nSize)==p->nTotal );
461
462 if( iRow<iSmall ){
463 sqlite3_result_int64(pCtx, 1 + iRow/(nSize+1));
464 }else{
465 sqlite3_result_int64(pCtx, 1 + nLarge + (iRow-iSmall)/nSize);
466 }
467 }
468 }
469}
dancc7a8502019-03-11 19:50:54 +0000470#define ntileFinalizeFunc ntileValueFunc
dan6bc5c9e2018-06-04 18:55:11 +0000471
dan2a11bb22018-06-11 20:50:25 +0000472/*
473** Context object for last_value() window function.
474*/
dan1c5ed622018-06-05 16:16:17 +0000475struct LastValueCtx {
476 sqlite3_value *pVal;
477 int nVal;
478};
479
480/*
481** Implementation of last_value().
482*/
483static void last_valueStepFunc(
484 sqlite3_context *pCtx,
485 int nArg,
486 sqlite3_value **apArg
487){
488 struct LastValueCtx *p;
drhc7bf5712018-07-09 22:49:01 +0000489 UNUSED_PARAMETER(nArg);
dan9c277582018-06-20 09:23:49 +0000490 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
dan1c5ed622018-06-05 16:16:17 +0000491 if( p ){
492 sqlite3_value_free(p->pVal);
493 p->pVal = sqlite3_value_dup(apArg[0]);
dan6fde1792018-06-15 19:01:35 +0000494 if( p->pVal==0 ){
495 sqlite3_result_error_nomem(pCtx);
496 }else{
497 p->nVal++;
498 }
dan1c5ed622018-06-05 16:16:17 +0000499 }
500}
dan2a11bb22018-06-11 20:50:25 +0000501static void last_valueInvFunc(
dan1c5ed622018-06-05 16:16:17 +0000502 sqlite3_context *pCtx,
503 int nArg,
504 sqlite3_value **apArg
505){
506 struct LastValueCtx *p;
drhc7bf5712018-07-09 22:49:01 +0000507 UNUSED_PARAMETER(nArg);
508 UNUSED_PARAMETER(apArg);
dan9c277582018-06-20 09:23:49 +0000509 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
510 if( ALWAYS(p) ){
dan1c5ed622018-06-05 16:16:17 +0000511 p->nVal--;
512 if( p->nVal==0 ){
513 sqlite3_value_free(p->pVal);
514 p->pVal = 0;
515 }
516 }
517}
518static void last_valueValueFunc(sqlite3_context *pCtx){
519 struct LastValueCtx *p;
dan0525b6f2019-03-18 21:19:40 +0000520 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, 0);
dan1c5ed622018-06-05 16:16:17 +0000521 if( p && p->pVal ){
522 sqlite3_result_value(pCtx, p->pVal);
523 }
524}
525static void last_valueFinalizeFunc(sqlite3_context *pCtx){
526 struct LastValueCtx *p;
dan9c277582018-06-20 09:23:49 +0000527 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
dan1c5ed622018-06-05 16:16:17 +0000528 if( p && p->pVal ){
529 sqlite3_result_value(pCtx, p->pVal);
530 sqlite3_value_free(p->pVal);
531 p->pVal = 0;
532 }
533}
534
dan2a11bb22018-06-11 20:50:25 +0000535/*
drh19dc4d42018-07-08 01:02:26 +0000536** Static names for the built-in window function names. These static
537** names are used, rather than string literals, so that FuncDef objects
538** can be associated with a particular window function by direct
539** comparison of the zName pointer. Example:
540**
541** if( pFuncDef->zName==row_valueName ){ ... }
dan2a11bb22018-06-11 20:50:25 +0000542*/
drh19dc4d42018-07-08 01:02:26 +0000543static const char row_numberName[] = "row_number";
544static const char dense_rankName[] = "dense_rank";
545static const char rankName[] = "rank";
546static const char percent_rankName[] = "percent_rank";
547static const char cume_distName[] = "cume_dist";
548static const char ntileName[] = "ntile";
549static const char last_valueName[] = "last_value";
550static const char nth_valueName[] = "nth_value";
551static const char first_valueName[] = "first_value";
552static const char leadName[] = "lead";
553static const char lagName[] = "lag";
danfe4e25a2018-06-07 20:08:59 +0000554
drh19dc4d42018-07-08 01:02:26 +0000555/*
556** No-op implementations of xStep() and xFinalize(). Used as place-holders
557** for built-in window functions that never call those interfaces.
558**
559** The noopValueFunc() is called but is expected to do nothing. The
560** noopStepFunc() is never called, and so it is marked with NO_TEST to
561** let the test coverage routine know not to expect this function to be
562** invoked.
563*/
564static void noopStepFunc( /*NO_TEST*/
565 sqlite3_context *p, /*NO_TEST*/
566 int n, /*NO_TEST*/
567 sqlite3_value **a /*NO_TEST*/
568){ /*NO_TEST*/
drhc7bf5712018-07-09 22:49:01 +0000569 UNUSED_PARAMETER(p); /*NO_TEST*/
570 UNUSED_PARAMETER(n); /*NO_TEST*/
571 UNUSED_PARAMETER(a); /*NO_TEST*/
drh19dc4d42018-07-08 01:02:26 +0000572 assert(0); /*NO_TEST*/
573} /*NO_TEST*/
drhc7bf5712018-07-09 22:49:01 +0000574static void noopValueFunc(sqlite3_context *p){ UNUSED_PARAMETER(p); /*no-op*/ }
dandfa552f2018-06-02 21:04:28 +0000575
drh19dc4d42018-07-08 01:02:26 +0000576/* Window functions that use all window interfaces: xStep, xFinal,
577** xValue, and xInverse */
578#define WINDOWFUNCALL(name,nArg,extra) { \
dan1c5ed622018-06-05 16:16:17 +0000579 nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
580 name ## StepFunc, name ## FinalizeFunc, name ## ValueFunc, \
drhc7bf5712018-07-09 22:49:01 +0000581 name ## InvFunc, name ## Name, {0} \
dan1c5ed622018-06-05 16:16:17 +0000582}
583
drh19dc4d42018-07-08 01:02:26 +0000584/* Window functions that are implemented using bytecode and thus have
585** no-op routines for their methods */
586#define WINDOWFUNCNOOP(name,nArg,extra) { \
587 nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
588 noopStepFunc, noopValueFunc, noopValueFunc, \
drhc7bf5712018-07-09 22:49:01 +0000589 noopStepFunc, name ## Name, {0} \
drh19dc4d42018-07-08 01:02:26 +0000590}
591
592/* Window functions that use all window interfaces: xStep, the
593** same routine for xFinalize and xValue and which never call
594** xInverse. */
595#define WINDOWFUNCX(name,nArg,extra) { \
596 nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
597 name ## StepFunc, name ## ValueFunc, name ## ValueFunc, \
drhc7bf5712018-07-09 22:49:01 +0000598 noopStepFunc, name ## Name, {0} \
drh19dc4d42018-07-08 01:02:26 +0000599}
600
601
dandfa552f2018-06-02 21:04:28 +0000602/*
603** Register those built-in window functions that are not also aggregates.
604*/
605void sqlite3WindowFunctions(void){
606 static FuncDef aWindowFuncs[] = {
drh19dc4d42018-07-08 01:02:26 +0000607 WINDOWFUNCX(row_number, 0, 0),
608 WINDOWFUNCX(dense_rank, 0, 0),
609 WINDOWFUNCX(rank, 0, 0),
dancc7a8502019-03-11 19:50:54 +0000610 WINDOWFUNCALL(percent_rank, 0, 0),
611 WINDOWFUNCALL(cume_dist, 0, 0),
612 WINDOWFUNCALL(ntile, 1, 0),
drh19dc4d42018-07-08 01:02:26 +0000613 WINDOWFUNCALL(last_value, 1, 0),
dana0f6b832019-03-14 16:36:20 +0000614 WINDOWFUNCALL(nth_value, 2, 0),
danc782a812019-03-15 20:46:19 +0000615 WINDOWFUNCALL(first_value, 1, 0),
drh19dc4d42018-07-08 01:02:26 +0000616 WINDOWFUNCNOOP(lead, 1, 0),
617 WINDOWFUNCNOOP(lead, 2, 0),
618 WINDOWFUNCNOOP(lead, 3, 0),
619 WINDOWFUNCNOOP(lag, 1, 0),
620 WINDOWFUNCNOOP(lag, 2, 0),
621 WINDOWFUNCNOOP(lag, 3, 0),
dandfa552f2018-06-02 21:04:28 +0000622 };
623 sqlite3InsertBuiltinFuncs(aWindowFuncs, ArraySize(aWindowFuncs));
624}
625
dane7c9ca42019-02-16 17:27:51 +0000626static Window *windowFind(Parse *pParse, Window *pList, const char *zName){
627 Window *p;
628 for(p=pList; p; p=p->pNextWin){
629 if( sqlite3StrICmp(p->zName, zName)==0 ) break;
630 }
631 if( p==0 ){
632 sqlite3ErrorMsg(pParse, "no such window: %s", zName);
633 }
634 return p;
635}
636
danc0bb4452018-06-12 20:53:38 +0000637/*
638** This function is called immediately after resolving the function name
639** for a window function within a SELECT statement. Argument pList is a
640** linked list of WINDOW definitions for the current SELECT statement.
641** Argument pFunc is the function definition just resolved and pWin
642** is the Window object representing the associated OVER clause. This
643** function updates the contents of pWin as follows:
644**
645** * If the OVER clause refered to a named window (as in "max(x) OVER win"),
646** search list pList for a matching WINDOW definition, and update pWin
647** accordingly. If no such WINDOW clause can be found, leave an error
648** in pParse.
649**
650** * If the function is a built-in window function that requires the
651** window to be coerced (see "BUILT-IN WINDOW FUNCTIONS" at the top
652** of this file), pWin is updated here.
653*/
dane3bf6322018-06-08 20:58:27 +0000654void sqlite3WindowUpdate(
655 Parse *pParse,
danc0bb4452018-06-12 20:53:38 +0000656 Window *pList, /* List of named windows for this SELECT */
657 Window *pWin, /* Window frame to update */
658 FuncDef *pFunc /* Window function definition */
dane3bf6322018-06-08 20:58:27 +0000659){
danc95f38d2018-06-18 20:34:43 +0000660 if( pWin->zName && pWin->eType==0 ){
dane7c9ca42019-02-16 17:27:51 +0000661 Window *p = windowFind(pParse, pList, pWin->zName);
662 if( p==0 ) return;
dane3bf6322018-06-08 20:58:27 +0000663 pWin->pPartition = sqlite3ExprListDup(pParse->db, p->pPartition, 0);
664 pWin->pOrderBy = sqlite3ExprListDup(pParse->db, p->pOrderBy, 0);
665 pWin->pStart = sqlite3ExprDup(pParse->db, p->pStart, 0);
666 pWin->pEnd = sqlite3ExprDup(pParse->db, p->pEnd, 0);
667 pWin->eStart = p->eStart;
668 pWin->eEnd = p->eEnd;
danc95f38d2018-06-18 20:34:43 +0000669 pWin->eType = p->eType;
danc782a812019-03-15 20:46:19 +0000670 pWin->eExclude = p->eExclude;
dane7c9ca42019-02-16 17:27:51 +0000671 }else{
672 sqlite3WindowChain(pParse, pWin, pList);
dane3bf6322018-06-08 20:58:27 +0000673 }
dan72b9fdc2019-03-09 20:49:17 +0000674 if( (pWin->eType==TK_RANGE)
675 && (pWin->pStart || pWin->pEnd)
676 && (pWin->pOrderBy==0 || pWin->pOrderBy->nExpr!=1)
677 ){
678 sqlite3ErrorMsg(pParse,
679 "RANGE with offset PRECEDING/FOLLOWING requires one ORDER BY expression"
680 );
681 }else
dandfa552f2018-06-02 21:04:28 +0000682 if( pFunc->funcFlags & SQLITE_FUNC_WINDOW ){
683 sqlite3 *db = pParse->db;
dan8b985602018-06-09 17:43:45 +0000684 if( pWin->pFilter ){
685 sqlite3ErrorMsg(pParse,
686 "FILTER clause may only be used with aggregate window functions"
687 );
dancc7a8502019-03-11 19:50:54 +0000688 }else{
689 struct WindowUpdate {
690 const char *zFunc;
691 int eType;
692 int eStart;
693 int eEnd;
694 } aUp[] = {
695 { row_numberName, TK_ROWS, TK_UNBOUNDED, TK_CURRENT },
696 { dense_rankName, TK_RANGE, TK_UNBOUNDED, TK_CURRENT },
697 { rankName, TK_RANGE, TK_UNBOUNDED, TK_CURRENT },
698 { percent_rankName, TK_GROUPS, TK_CURRENT, TK_UNBOUNDED },
699 { cume_distName, TK_GROUPS, TK_FOLLOWING, TK_UNBOUNDED },
700 { ntileName, TK_ROWS, TK_CURRENT, TK_UNBOUNDED },
701 { leadName, TK_ROWS, TK_UNBOUNDED, TK_UNBOUNDED },
danb560a712019-03-13 15:29:14 +0000702 { lagName, TK_ROWS, TK_UNBOUNDED, TK_CURRENT },
dancc7a8502019-03-11 19:50:54 +0000703 };
704 int i;
705 for(i=0; i<ArraySize(aUp); i++){
706 if( pFunc->zName==aUp[i].zFunc ){
707 sqlite3ExprDelete(db, pWin->pStart);
708 sqlite3ExprDelete(db, pWin->pEnd);
709 pWin->pEnd = pWin->pStart = 0;
710 pWin->eType = aUp[i].eType;
711 pWin->eStart = aUp[i].eStart;
712 pWin->eEnd = aUp[i].eEnd;
dana0f6b832019-03-14 16:36:20 +0000713 pWin->eExclude = 0;
dancc7a8502019-03-11 19:50:54 +0000714 if( pWin->eStart==TK_FOLLOWING ){
715 pWin->pStart = sqlite3Expr(db, TK_INTEGER, "1");
716 }
717 break;
718 }
719 }
dandfa552f2018-06-02 21:04:28 +0000720 }
721 }
dan2a11bb22018-06-11 20:50:25 +0000722 pWin->pFunc = pFunc;
dandfa552f2018-06-02 21:04:28 +0000723}
724
danc0bb4452018-06-12 20:53:38 +0000725/*
726** Context object passed through sqlite3WalkExprList() to
727** selectWindowRewriteExprCb() by selectWindowRewriteEList().
728*/
dandfa552f2018-06-02 21:04:28 +0000729typedef struct WindowRewrite WindowRewrite;
730struct WindowRewrite {
731 Window *pWin;
danb556f262018-07-10 17:26:12 +0000732 SrcList *pSrc;
dandfa552f2018-06-02 21:04:28 +0000733 ExprList *pSub;
danb556f262018-07-10 17:26:12 +0000734 Select *pSubSelect; /* Current sub-select, if any */
dandfa552f2018-06-02 21:04:28 +0000735};
736
danc0bb4452018-06-12 20:53:38 +0000737/*
738** Callback function used by selectWindowRewriteEList(). If necessary,
739** this function appends to the output expression-list and updates
740** expression (*ppExpr) in place.
741*/
dandfa552f2018-06-02 21:04:28 +0000742static int selectWindowRewriteExprCb(Walker *pWalker, Expr *pExpr){
743 struct WindowRewrite *p = pWalker->u.pRewrite;
744 Parse *pParse = pWalker->pParse;
745
danb556f262018-07-10 17:26:12 +0000746 /* If this function is being called from within a scalar sub-select
747 ** that used by the SELECT statement being processed, only process
748 ** TK_COLUMN expressions that refer to it (the outer SELECT). Do
749 ** not process aggregates or window functions at all, as they belong
750 ** to the scalar sub-select. */
751 if( p->pSubSelect ){
752 if( pExpr->op!=TK_COLUMN ){
753 return WRC_Continue;
754 }else{
755 int nSrc = p->pSrc->nSrc;
756 int i;
757 for(i=0; i<nSrc; i++){
758 if( pExpr->iTable==p->pSrc->a[i].iCursor ) break;
759 }
760 if( i==nSrc ) return WRC_Continue;
761 }
762 }
763
dandfa552f2018-06-02 21:04:28 +0000764 switch( pExpr->op ){
765
766 case TK_FUNCTION:
drheda079c2018-09-20 19:02:15 +0000767 if( !ExprHasProperty(pExpr, EP_WinFunc) ){
dandfa552f2018-06-02 21:04:28 +0000768 break;
769 }else{
770 Window *pWin;
771 for(pWin=p->pWin; pWin; pWin=pWin->pNextWin){
drheda079c2018-09-20 19:02:15 +0000772 if( pExpr->y.pWin==pWin ){
dan2a11bb22018-06-11 20:50:25 +0000773 assert( pWin->pOwner==pExpr );
dandfa552f2018-06-02 21:04:28 +0000774 return WRC_Prune;
775 }
776 }
777 }
778 /* Fall through. */
779
dan73925692018-06-12 18:40:17 +0000780 case TK_AGG_FUNCTION:
dandfa552f2018-06-02 21:04:28 +0000781 case TK_COLUMN: {
782 Expr *pDup = sqlite3ExprDup(pParse->db, pExpr, 0);
783 p->pSub = sqlite3ExprListAppend(pParse, p->pSub, pDup);
784 if( p->pSub ){
785 assert( ExprHasProperty(pExpr, EP_Static)==0 );
786 ExprSetProperty(pExpr, EP_Static);
787 sqlite3ExprDelete(pParse->db, pExpr);
788 ExprClearProperty(pExpr, EP_Static);
789 memset(pExpr, 0, sizeof(Expr));
790
791 pExpr->op = TK_COLUMN;
792 pExpr->iColumn = p->pSub->nExpr-1;
793 pExpr->iTable = p->pWin->iEphCsr;
794 }
795
796 break;
797 }
798
799 default: /* no-op */
800 break;
801 }
802
803 return WRC_Continue;
804}
danc0bb4452018-06-12 20:53:38 +0000805static int selectWindowRewriteSelectCb(Walker *pWalker, Select *pSelect){
danb556f262018-07-10 17:26:12 +0000806 struct WindowRewrite *p = pWalker->u.pRewrite;
807 Select *pSave = p->pSubSelect;
808 if( pSave==pSelect ){
809 return WRC_Continue;
810 }else{
811 p->pSubSelect = pSelect;
812 sqlite3WalkSelect(pWalker, pSelect);
813 p->pSubSelect = pSave;
814 }
danc0bb4452018-06-12 20:53:38 +0000815 return WRC_Prune;
816}
dandfa552f2018-06-02 21:04:28 +0000817
danc0bb4452018-06-12 20:53:38 +0000818
819/*
820** Iterate through each expression in expression-list pEList. For each:
821**
822** * TK_COLUMN,
823** * aggregate function, or
824** * window function with a Window object that is not a member of the
danb556f262018-07-10 17:26:12 +0000825** Window list passed as the second argument (pWin).
danc0bb4452018-06-12 20:53:38 +0000826**
827** Append the node to output expression-list (*ppSub). And replace it
828** with a TK_COLUMN that reads the (N-1)th element of table
829** pWin->iEphCsr, where N is the number of elements in (*ppSub) after
830** appending the new one.
831*/
dan13b08bb2018-06-15 20:46:12 +0000832static void selectWindowRewriteEList(
dandfa552f2018-06-02 21:04:28 +0000833 Parse *pParse,
834 Window *pWin,
danb556f262018-07-10 17:26:12 +0000835 SrcList *pSrc,
dandfa552f2018-06-02 21:04:28 +0000836 ExprList *pEList, /* Rewrite expressions in this list */
837 ExprList **ppSub /* IN/OUT: Sub-select expression-list */
838){
839 Walker sWalker;
840 WindowRewrite sRewrite;
dandfa552f2018-06-02 21:04:28 +0000841
842 memset(&sWalker, 0, sizeof(Walker));
843 memset(&sRewrite, 0, sizeof(WindowRewrite));
844
845 sRewrite.pSub = *ppSub;
846 sRewrite.pWin = pWin;
danb556f262018-07-10 17:26:12 +0000847 sRewrite.pSrc = pSrc;
dandfa552f2018-06-02 21:04:28 +0000848
849 sWalker.pParse = pParse;
850 sWalker.xExprCallback = selectWindowRewriteExprCb;
851 sWalker.xSelectCallback = selectWindowRewriteSelectCb;
852 sWalker.u.pRewrite = &sRewrite;
853
dan13b08bb2018-06-15 20:46:12 +0000854 (void)sqlite3WalkExprList(&sWalker, pEList);
dandfa552f2018-06-02 21:04:28 +0000855
856 *ppSub = sRewrite.pSub;
dandfa552f2018-06-02 21:04:28 +0000857}
858
danc0bb4452018-06-12 20:53:38 +0000859/*
860** Append a copy of each expression in expression-list pAppend to
861** expression list pList. Return a pointer to the result list.
862*/
dandfa552f2018-06-02 21:04:28 +0000863static ExprList *exprListAppendList(
864 Parse *pParse, /* Parsing context */
865 ExprList *pList, /* List to which to append. Might be NULL */
866 ExprList *pAppend /* List of values to append. Might be NULL */
867){
868 if( pAppend ){
869 int i;
870 int nInit = pList ? pList->nExpr : 0;
871 for(i=0; i<pAppend->nExpr; i++){
872 Expr *pDup = sqlite3ExprDup(pParse->db, pAppend->a[i].pExpr, 0);
873 pList = sqlite3ExprListAppend(pParse, pList, pDup);
874 if( pList ) pList->a[nInit+i].sortOrder = pAppend->a[i].sortOrder;
875 }
876 }
877 return pList;
878}
879
880/*
881** If the SELECT statement passed as the second argument does not invoke
882** any SQL window functions, this function is a no-op. Otherwise, it
883** rewrites the SELECT statement so that window function xStep functions
danc0bb4452018-06-12 20:53:38 +0000884** are invoked in the correct order as described under "SELECT REWRITING"
885** at the top of this file.
dandfa552f2018-06-02 21:04:28 +0000886*/
887int sqlite3WindowRewrite(Parse *pParse, Select *p){
888 int rc = SQLITE_OK;
dan0f5f5402018-10-23 13:48:19 +0000889 if( p->pWin && p->pPrior==0 ){
dandfa552f2018-06-02 21:04:28 +0000890 Vdbe *v = sqlite3GetVdbe(pParse);
dandfa552f2018-06-02 21:04:28 +0000891 sqlite3 *db = pParse->db;
892 Select *pSub = 0; /* The subquery */
893 SrcList *pSrc = p->pSrc;
894 Expr *pWhere = p->pWhere;
895 ExprList *pGroupBy = p->pGroupBy;
896 Expr *pHaving = p->pHaving;
897 ExprList *pSort = 0;
898
899 ExprList *pSublist = 0; /* Expression list for sub-query */
900 Window *pMWin = p->pWin; /* Master window object */
901 Window *pWin; /* Window object iterator */
902
903 p->pSrc = 0;
904 p->pWhere = 0;
905 p->pGroupBy = 0;
906 p->pHaving = 0;
907
danf02cdd32018-06-27 19:48:50 +0000908 /* Create the ORDER BY clause for the sub-select. This is the concatenation
909 ** of the window PARTITION and ORDER BY clauses. Then, if this makes it
910 ** redundant, remove the ORDER BY from the parent SELECT. */
911 pSort = sqlite3ExprListDup(db, pMWin->pPartition, 0);
912 pSort = exprListAppendList(pParse, pSort, pMWin->pOrderBy);
913 if( pSort && p->pOrderBy ){
914 if( sqlite3ExprListCompare(pSort, p->pOrderBy, -1)==0 ){
915 sqlite3ExprListDelete(db, p->pOrderBy);
916 p->pOrderBy = 0;
917 }
918 }
919
dandfa552f2018-06-02 21:04:28 +0000920 /* Assign a cursor number for the ephemeral table used to buffer rows.
921 ** The OpenEphemeral instruction is coded later, after it is known how
922 ** many columns the table will have. */
923 pMWin->iEphCsr = pParse->nTab++;
dan680f6e82019-03-04 21:07:11 +0000924 pParse->nTab += 3;
dandfa552f2018-06-02 21:04:28 +0000925
danb556f262018-07-10 17:26:12 +0000926 selectWindowRewriteEList(pParse, pMWin, pSrc, p->pEList, &pSublist);
927 selectWindowRewriteEList(pParse, pMWin, pSrc, p->pOrderBy, &pSublist);
dandfa552f2018-06-02 21:04:28 +0000928 pMWin->nBufferCol = (pSublist ? pSublist->nExpr : 0);
929
danf02cdd32018-06-27 19:48:50 +0000930 /* Append the PARTITION BY and ORDER BY expressions to the to the
931 ** sub-select expression list. They are required to figure out where
932 ** boundaries for partitions and sets of peer rows lie. */
933 pSublist = exprListAppendList(pParse, pSublist, pMWin->pPartition);
934 pSublist = exprListAppendList(pParse, pSublist, pMWin->pOrderBy);
dandfa552f2018-06-02 21:04:28 +0000935
936 /* Append the arguments passed to each window function to the
937 ** sub-select expression list. Also allocate two registers for each
938 ** window function - one for the accumulator, another for interim
939 ** results. */
940 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
941 pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);
942 pSublist = exprListAppendList(pParse, pSublist, pWin->pOwner->x.pList);
dan8b985602018-06-09 17:43:45 +0000943 if( pWin->pFilter ){
944 Expr *pFilter = sqlite3ExprDup(db, pWin->pFilter, 0);
945 pSublist = sqlite3ExprListAppend(pParse, pSublist, pFilter);
946 }
dandfa552f2018-06-02 21:04:28 +0000947 pWin->regAccum = ++pParse->nMem;
948 pWin->regResult = ++pParse->nMem;
949 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
950 }
951
dan9c277582018-06-20 09:23:49 +0000952 /* If there is no ORDER BY or PARTITION BY clause, and the window
953 ** function accepts zero arguments, and there are no other columns
954 ** selected (e.g. "SELECT row_number() OVER () FROM t1"), it is possible
955 ** that pSublist is still NULL here. Add a constant expression here to
956 ** keep everything legal in this case.
957 */
958 if( pSublist==0 ){
959 pSublist = sqlite3ExprListAppend(pParse, 0,
960 sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0)
961 );
962 }
963
dandfa552f2018-06-02 21:04:28 +0000964 pSub = sqlite3SelectNew(
965 pParse, pSublist, pSrc, pWhere, pGroupBy, pHaving, pSort, 0, 0
966 );
drh29c992c2019-01-17 15:40:41 +0000967 p->pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
dandfa552f2018-06-02 21:04:28 +0000968 if( p->pSrc ){
dandfa552f2018-06-02 21:04:28 +0000969 p->pSrc->a[0].pSelect = pSub;
970 sqlite3SrcListAssignCursors(pParse, p->pSrc);
971 if( sqlite3ExpandSubquery(pParse, &p->pSrc->a[0]) ){
972 rc = SQLITE_NOMEM;
973 }else{
974 pSub->selFlags |= SF_Expanded;
dan73925692018-06-12 18:40:17 +0000975 p->selFlags &= ~SF_Aggregate;
976 sqlite3SelectPrep(pParse, pSub, 0);
dandfa552f2018-06-02 21:04:28 +0000977 }
dandfa552f2018-06-02 21:04:28 +0000978
dan6fde1792018-06-15 19:01:35 +0000979 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pMWin->iEphCsr, pSublist->nExpr);
dan680f6e82019-03-04 21:07:11 +0000980 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+1, pMWin->iEphCsr);
981 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+2, pMWin->iEphCsr);
982 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+3, pMWin->iEphCsr);
dan6fde1792018-06-15 19:01:35 +0000983 }else{
984 sqlite3SelectDelete(db, pSub);
985 }
986 if( db->mallocFailed ) rc = SQLITE_NOMEM;
dandfa552f2018-06-02 21:04:28 +0000987 }
988
989 return rc;
990}
991
danc0bb4452018-06-12 20:53:38 +0000992/*
993** Free the Window object passed as the second argument.
994*/
dan86fb6e12018-05-16 20:58:07 +0000995void sqlite3WindowDelete(sqlite3 *db, Window *p){
996 if( p ){
997 sqlite3ExprDelete(db, p->pFilter);
998 sqlite3ExprListDelete(db, p->pPartition);
999 sqlite3ExprListDelete(db, p->pOrderBy);
1000 sqlite3ExprDelete(db, p->pEnd);
1001 sqlite3ExprDelete(db, p->pStart);
dane3bf6322018-06-08 20:58:27 +00001002 sqlite3DbFree(db, p->zName);
dane7c9ca42019-02-16 17:27:51 +00001003 sqlite3DbFree(db, p->zBase);
dan86fb6e12018-05-16 20:58:07 +00001004 sqlite3DbFree(db, p);
1005 }
1006}
1007
danc0bb4452018-06-12 20:53:38 +00001008/*
1009** Free the linked list of Window objects starting at the second argument.
1010*/
dane3bf6322018-06-08 20:58:27 +00001011void sqlite3WindowListDelete(sqlite3 *db, Window *p){
1012 while( p ){
1013 Window *pNext = p->pNextWin;
1014 sqlite3WindowDelete(db, p);
1015 p = pNext;
1016 }
1017}
1018
danc0bb4452018-06-12 20:53:38 +00001019/*
drhe4984a22018-07-06 17:19:20 +00001020** The argument expression is an PRECEDING or FOLLOWING offset. The
1021** value should be a non-negative integer. If the value is not a
1022** constant, change it to NULL. The fact that it is then a non-negative
1023** integer will be caught later. But it is important not to leave
1024** variable values in the expression tree.
1025*/
1026static Expr *sqlite3WindowOffsetExpr(Parse *pParse, Expr *pExpr){
1027 if( 0==sqlite3ExprIsConstant(pExpr) ){
danfb8ac322019-01-16 12:05:22 +00001028 if( IN_RENAME_OBJECT ) sqlite3RenameExprUnmap(pParse, pExpr);
drhe4984a22018-07-06 17:19:20 +00001029 sqlite3ExprDelete(pParse->db, pExpr);
1030 pExpr = sqlite3ExprAlloc(pParse->db, TK_NULL, 0, 0);
1031 }
1032 return pExpr;
1033}
1034
1035/*
1036** Allocate and return a new Window object describing a Window Definition.
danc0bb4452018-06-12 20:53:38 +00001037*/
dan86fb6e12018-05-16 20:58:07 +00001038Window *sqlite3WindowAlloc(
drhe4984a22018-07-06 17:19:20 +00001039 Parse *pParse, /* Parsing context */
1040 int eType, /* Frame type. TK_RANGE or TK_ROWS */
1041 int eStart, /* Start type: CURRENT, PRECEDING, FOLLOWING, UNBOUNDED */
1042 Expr *pStart, /* Start window size if TK_PRECEDING or FOLLOWING */
1043 int eEnd, /* End type: CURRENT, FOLLOWING, TK_UNBOUNDED, PRECEDING */
dand35300f2019-03-14 20:53:21 +00001044 Expr *pEnd, /* End window size if TK_FOLLOWING or PRECEDING */
1045 u8 eExclude /* EXCLUDE clause */
dan86fb6e12018-05-16 20:58:07 +00001046){
dan7a606e12018-07-05 18:34:53 +00001047 Window *pWin = 0;
dane7c9ca42019-02-16 17:27:51 +00001048 int bImplicitFrame = 0;
dan7a606e12018-07-05 18:34:53 +00001049
drhe4984a22018-07-06 17:19:20 +00001050 /* Parser assures the following: */
dan6c75b392019-03-08 20:02:52 +00001051 assert( eType==0 || eType==TK_RANGE || eType==TK_ROWS || eType==TK_GROUPS );
drhe4984a22018-07-06 17:19:20 +00001052 assert( eStart==TK_CURRENT || eStart==TK_PRECEDING
1053 || eStart==TK_UNBOUNDED || eStart==TK_FOLLOWING );
1054 assert( eEnd==TK_CURRENT || eEnd==TK_FOLLOWING
1055 || eEnd==TK_UNBOUNDED || eEnd==TK_PRECEDING );
1056 assert( (eStart==TK_PRECEDING || eStart==TK_FOLLOWING)==(pStart!=0) );
1057 assert( (eEnd==TK_FOLLOWING || eEnd==TK_PRECEDING)==(pEnd!=0) );
1058
dane7c9ca42019-02-16 17:27:51 +00001059 if( eType==0 ){
1060 bImplicitFrame = 1;
1061 eType = TK_RANGE;
1062 }
drhe4984a22018-07-06 17:19:20 +00001063
drhe4984a22018-07-06 17:19:20 +00001064 /* Additionally, the
dan5d764ac2018-07-06 14:15:49 +00001065 ** starting boundary type may not occur earlier in the following list than
1066 ** the ending boundary type:
1067 **
1068 ** UNBOUNDED PRECEDING
1069 ** <expr> PRECEDING
1070 ** CURRENT ROW
1071 ** <expr> FOLLOWING
1072 ** UNBOUNDED FOLLOWING
1073 **
1074 ** The parser ensures that "UNBOUNDED PRECEDING" cannot be used as an ending
1075 ** boundary, and than "UNBOUNDED FOLLOWING" cannot be used as a starting
1076 ** frame boundary.
1077 */
drhe4984a22018-07-06 17:19:20 +00001078 if( (eStart==TK_CURRENT && eEnd==TK_PRECEDING)
dan5d764ac2018-07-06 14:15:49 +00001079 || (eStart==TK_FOLLOWING && (eEnd==TK_PRECEDING || eEnd==TK_CURRENT))
1080 ){
dan72b9fdc2019-03-09 20:49:17 +00001081 sqlite3ErrorMsg(pParse, "unsupported frame specification");
drhe4984a22018-07-06 17:19:20 +00001082 goto windowAllocErr;
dan7a606e12018-07-05 18:34:53 +00001083 }
dan86fb6e12018-05-16 20:58:07 +00001084
drhe4984a22018-07-06 17:19:20 +00001085 pWin = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
1086 if( pWin==0 ) goto windowAllocErr;
1087 pWin->eType = eType;
1088 pWin->eStart = eStart;
1089 pWin->eEnd = eEnd;
dan108e6b22019-03-18 18:55:35 +00001090 if( eExclude==0 && OptimizationDisabled(pParse->db, SQLITE_QueryFlattener) ){
1091 eExclude = TK_NO;
1092 }
dand35300f2019-03-14 20:53:21 +00001093 pWin->eExclude = eExclude;
dane7c9ca42019-02-16 17:27:51 +00001094 pWin->bImplicitFrame = bImplicitFrame;
drhe4984a22018-07-06 17:19:20 +00001095 pWin->pEnd = sqlite3WindowOffsetExpr(pParse, pEnd);
1096 pWin->pStart = sqlite3WindowOffsetExpr(pParse, pStart);
dan86fb6e12018-05-16 20:58:07 +00001097 return pWin;
drhe4984a22018-07-06 17:19:20 +00001098
1099windowAllocErr:
1100 sqlite3ExprDelete(pParse->db, pEnd);
1101 sqlite3ExprDelete(pParse->db, pStart);
1102 return 0;
dan86fb6e12018-05-16 20:58:07 +00001103}
1104
danc0bb4452018-06-12 20:53:38 +00001105/*
dane7c9ca42019-02-16 17:27:51 +00001106** Attach PARTITION and ORDER BY clauses pPartition and pOrderBy to window
1107** pWin. Also, if parameter pBase is not NULL, set pWin->zBase to the
1108** equivalent nul-terminated string.
1109*/
1110Window *sqlite3WindowAssemble(
1111 Parse *pParse,
1112 Window *pWin,
1113 ExprList *pPartition,
1114 ExprList *pOrderBy,
1115 Token *pBase
1116){
1117 if( pWin ){
1118 pWin->pPartition = pPartition;
1119 pWin->pOrderBy = pOrderBy;
1120 if( pBase ){
1121 pWin->zBase = sqlite3DbStrNDup(pParse->db, pBase->z, pBase->n);
1122 }
1123 }else{
1124 sqlite3ExprListDelete(pParse->db, pPartition);
1125 sqlite3ExprListDelete(pParse->db, pOrderBy);
1126 }
1127 return pWin;
1128}
1129
1130/*
1131** Window *pWin has just been created from a WINDOW clause. Tokne pBase
1132** is the base window. Earlier windows from the same WINDOW clause are
1133** stored in the linked list starting at pWin->pNextWin. This function
1134** either updates *pWin according to the base specification, or else
1135** leaves an error in pParse.
1136*/
1137void sqlite3WindowChain(Parse *pParse, Window *pWin, Window *pList){
1138 if( pWin->zBase ){
1139 sqlite3 *db = pParse->db;
1140 Window *pExist = windowFind(pParse, pList, pWin->zBase);
1141 if( pExist ){
1142 const char *zErr = 0;
1143 /* Check for errors */
1144 if( pWin->pPartition ){
1145 zErr = "PARTITION clause";
1146 }else if( pExist->pOrderBy && pWin->pOrderBy ){
1147 zErr = "ORDER BY clause";
1148 }else if( pExist->bImplicitFrame==0 ){
1149 zErr = "frame specification";
1150 }
1151 if( zErr ){
1152 sqlite3ErrorMsg(pParse,
1153 "cannot override %s of window: %s", zErr, pWin->zBase
1154 );
1155 }else{
1156 pWin->pPartition = sqlite3ExprListDup(db, pExist->pPartition, 0);
1157 if( pExist->pOrderBy ){
1158 assert( pWin->pOrderBy==0 );
1159 pWin->pOrderBy = sqlite3ExprListDup(db, pExist->pOrderBy, 0);
1160 }
1161 sqlite3DbFree(db, pWin->zBase);
1162 pWin->zBase = 0;
1163 }
1164 }
1165 }
1166}
1167
1168/*
danc0bb4452018-06-12 20:53:38 +00001169** Attach window object pWin to expression p.
1170*/
dan86fb6e12018-05-16 20:58:07 +00001171void sqlite3WindowAttach(Parse *pParse, Expr *p, Window *pWin){
1172 if( p ){
drheda079c2018-09-20 19:02:15 +00001173 assert( p->op==TK_FUNCTION );
drh954733b2018-07-27 23:33:16 +00001174 /* This routine is only called for the parser. If pWin was not
1175 ** allocated due to an OOM, then the parser would fail before ever
1176 ** invoking this routine */
1177 if( ALWAYS(pWin) ){
drheda079c2018-09-20 19:02:15 +00001178 p->y.pWin = pWin;
1179 ExprSetProperty(p, EP_WinFunc);
dane33f6e72018-07-06 07:42:42 +00001180 pWin->pOwner = p;
1181 if( p->flags & EP_Distinct ){
drhe4984a22018-07-06 17:19:20 +00001182 sqlite3ErrorMsg(pParse,
1183 "DISTINCT is not supported for window functions");
dane33f6e72018-07-06 07:42:42 +00001184 }
1185 }
dan86fb6e12018-05-16 20:58:07 +00001186 }else{
1187 sqlite3WindowDelete(pParse->db, pWin);
1188 }
1189}
dane2f781b2018-05-17 19:24:08 +00001190
1191/*
1192** Return 0 if the two window objects are identical, or non-zero otherwise.
dan13078ca2018-06-13 20:29:38 +00001193** Identical window objects can be processed in a single scan.
dane2f781b2018-05-17 19:24:08 +00001194*/
1195int sqlite3WindowCompare(Parse *pParse, Window *p1, Window *p2){
1196 if( p1->eType!=p2->eType ) return 1;
1197 if( p1->eStart!=p2->eStart ) return 1;
1198 if( p1->eEnd!=p2->eEnd ) return 1;
dana0f6b832019-03-14 16:36:20 +00001199 if( p1->eExclude!=p2->eExclude ) return 1;
dane2f781b2018-05-17 19:24:08 +00001200 if( sqlite3ExprCompare(pParse, p1->pStart, p2->pStart, -1) ) return 1;
1201 if( sqlite3ExprCompare(pParse, p1->pEnd, p2->pEnd, -1) ) return 1;
1202 if( sqlite3ExprListCompare(p1->pPartition, p2->pPartition, -1) ) return 1;
1203 if( sqlite3ExprListCompare(p1->pOrderBy, p2->pOrderBy, -1) ) return 1;
1204 return 0;
1205}
1206
dan13078ca2018-06-13 20:29:38 +00001207
1208/*
1209** This is called by code in select.c before it calls sqlite3WhereBegin()
1210** to begin iterating through the sub-query results. It is used to allocate
1211** and initialize registers and cursors used by sqlite3WindowCodeStep().
1212*/
1213void sqlite3WindowCodeInit(Parse *pParse, Window *pMWin){
danc9a86682018-05-30 20:44:58 +00001214 Window *pWin;
dan13078ca2018-06-13 20:29:38 +00001215 Vdbe *v = sqlite3GetVdbe(pParse);
danb6f2dea2019-03-13 17:20:27 +00001216
1217 /* Allocate registers to use for PARTITION BY values, if any. Initialize
1218 ** said registers to NULL. */
1219 if( pMWin->pPartition ){
1220 int nExpr = pMWin->pPartition->nExpr;
dan13078ca2018-06-13 20:29:38 +00001221 pMWin->regPart = pParse->nMem+1;
danb6f2dea2019-03-13 17:20:27 +00001222 pParse->nMem += nExpr;
1223 sqlite3VdbeAddOp3(v, OP_Null, 0, pMWin->regPart, pMWin->regPart+nExpr-1);
dan13078ca2018-06-13 20:29:38 +00001224 }
1225
danbf845152019-03-16 10:15:24 +00001226 pMWin->regOne = ++pParse->nMem;
1227 sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regOne);
dan680f6e82019-03-04 21:07:11 +00001228
dana0f6b832019-03-14 16:36:20 +00001229 if( pMWin->eExclude ){
1230 pMWin->regStartRowid = ++pParse->nMem;
1231 pMWin->regEndRowid = ++pParse->nMem;
1232 pMWin->csrApp = pParse->nTab++;
1233 sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid);
1234 sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid);
1235 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->csrApp, pMWin->iEphCsr);
1236 return;
1237 }
1238
danc9a86682018-05-30 20:44:58 +00001239 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
danec891fd2018-06-06 20:51:02 +00001240 FuncDef *p = pWin->pFunc;
1241 if( (p->funcFlags & SQLITE_FUNC_MINMAX) && pWin->eStart!=TK_UNBOUNDED ){
dan9a947222018-06-14 19:06:36 +00001242 /* The inline versions of min() and max() require a single ephemeral
1243 ** table and 3 registers. The registers are used as follows:
1244 **
1245 ** regApp+0: slot to copy min()/max() argument to for MakeRecord
1246 ** regApp+1: integer value used to ensure keys are unique
1247 ** regApp+2: output of MakeRecord
1248 */
danc9a86682018-05-30 20:44:58 +00001249 ExprList *pList = pWin->pOwner->x.pList;
1250 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pList, 0, 0);
danc9a86682018-05-30 20:44:58 +00001251 pWin->csrApp = pParse->nTab++;
1252 pWin->regApp = pParse->nMem+1;
1253 pParse->nMem += 3;
1254 if( pKeyInfo && pWin->pFunc->zName[1]=='i' ){
1255 assert( pKeyInfo->aSortOrder[0]==0 );
1256 pKeyInfo->aSortOrder[0] = 1;
1257 }
1258 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pWin->csrApp, 2);
1259 sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
1260 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
1261 }
drh19dc4d42018-07-08 01:02:26 +00001262 else if( p->zName==nth_valueName || p->zName==first_valueName ){
danec891fd2018-06-06 20:51:02 +00001263 /* Allocate two registers at pWin->regApp. These will be used to
1264 ** store the start and end index of the current frame. */
danec891fd2018-06-06 20:51:02 +00001265 pWin->regApp = pParse->nMem+1;
1266 pWin->csrApp = pParse->nTab++;
1267 pParse->nMem += 2;
danec891fd2018-06-06 20:51:02 +00001268 sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
1269 }
drh19dc4d42018-07-08 01:02:26 +00001270 else if( p->zName==leadName || p->zName==lagName ){
danfe4e25a2018-06-07 20:08:59 +00001271 pWin->csrApp = pParse->nTab++;
1272 sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
1273 }
danc9a86682018-05-30 20:44:58 +00001274 }
1275}
1276
danbb407272019-03-12 18:28:51 +00001277#define WINDOW_STARTING_INT 0
1278#define WINDOW_ENDING_INT 1
1279#define WINDOW_NTH_VALUE_INT 2
1280#define WINDOW_STARTING_NUM 3
1281#define WINDOW_ENDING_NUM 4
1282
dan13078ca2018-06-13 20:29:38 +00001283/*
dana1a7e112018-07-09 13:31:18 +00001284** A "PRECEDING <expr>" (eCond==0) or "FOLLOWING <expr>" (eCond==1) or the
1285** value of the second argument to nth_value() (eCond==2) has just been
1286** evaluated and the result left in register reg. This function generates VM
1287** code to check that the value is a non-negative integer and throws an
1288** exception if it is not.
dan13078ca2018-06-13 20:29:38 +00001289*/
danbb407272019-03-12 18:28:51 +00001290static void windowCheckValue(Parse *pParse, int reg, int eCond){
danc3a20c12018-05-23 20:55:37 +00001291 static const char *azErr[] = {
1292 "frame starting offset must be a non-negative integer",
dana1a7e112018-07-09 13:31:18 +00001293 "frame ending offset must be a non-negative integer",
danbb407272019-03-12 18:28:51 +00001294 "second argument to nth_value must be a positive integer",
1295 "frame starting offset must be a non-negative number",
1296 "frame ending offset must be a non-negative number",
danc3a20c12018-05-23 20:55:37 +00001297 };
danbb407272019-03-12 18:28:51 +00001298 static int aOp[] = { OP_Ge, OP_Ge, OP_Gt, OP_Ge, OP_Ge };
danc3a20c12018-05-23 20:55:37 +00001299 Vdbe *v = sqlite3GetVdbe(pParse);
dan13078ca2018-06-13 20:29:38 +00001300 int regZero = sqlite3GetTempReg(pParse);
danbb407272019-03-12 18:28:51 +00001301 assert( eCond>=0 && eCond<ArraySize(azErr) );
danc3a20c12018-05-23 20:55:37 +00001302 sqlite3VdbeAddOp2(v, OP_Integer, 0, regZero);
dane5166e02019-03-19 11:56:39 +00001303 if( eCond>=WINDOW_STARTING_NUM ){
1304 int regString = sqlite3GetTempReg(pParse);
1305 sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC);
1306 sqlite3VdbeAddOp3(v, OP_Ge, regString, sqlite3VdbeCurrentAddr(v)+2, reg);
1307 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC);
1308 }else{
1309 sqlite3VdbeAddOp2(v, OP_MustBeInt, reg, sqlite3VdbeCurrentAddr(v)+2);
1310 }
drh0b3b0dd2018-07-10 05:11:03 +00001311 VdbeCoverageIf(v, eCond==0);
1312 VdbeCoverageIf(v, eCond==1);
1313 VdbeCoverageIf(v, eCond==2);
dan1d4b25f2019-03-19 16:49:15 +00001314 VdbeCoverageIf(v, eCond==3);
1315 VdbeCoverageIf(v, eCond==4);
dana1a7e112018-07-09 13:31:18 +00001316 sqlite3VdbeAddOp3(v, aOp[eCond], regZero, sqlite3VdbeCurrentAddr(v)+2, reg);
drh6ccbd272018-07-10 17:10:44 +00001317 VdbeCoverageNeverNullIf(v, eCond==0);
1318 VdbeCoverageNeverNullIf(v, eCond==1);
1319 VdbeCoverageNeverNullIf(v, eCond==2);
dan1d4b25f2019-03-19 16:49:15 +00001320 VdbeCoverageNeverNullIf(v, eCond==3);
1321 VdbeCoverageNeverNullIf(v, eCond==4);
drh211a0852019-01-27 02:41:34 +00001322 sqlite3MayAbort(pParse);
danc3a20c12018-05-23 20:55:37 +00001323 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_ERROR, OE_Abort);
dana1a7e112018-07-09 13:31:18 +00001324 sqlite3VdbeAppendP4(v, (void*)azErr[eCond], P4_STATIC);
dan13078ca2018-06-13 20:29:38 +00001325 sqlite3ReleaseTempReg(pParse, regZero);
danc3a20c12018-05-23 20:55:37 +00001326}
1327
dan13078ca2018-06-13 20:29:38 +00001328/*
1329** Return the number of arguments passed to the window-function associated
1330** with the object passed as the only argument to this function.
1331*/
dan2a11bb22018-06-11 20:50:25 +00001332static int windowArgCount(Window *pWin){
1333 ExprList *pList = pWin->pOwner->x.pList;
1334 return (pList ? pList->nExpr : 0);
1335}
1336
danc9a86682018-05-30 20:44:58 +00001337/*
1338** Generate VM code to invoke either xStep() (if bInverse is 0) or
1339** xInverse (if bInverse is non-zero) for each window function in the
dan13078ca2018-06-13 20:29:38 +00001340** linked list starting at pMWin. Or, for built-in window functions
1341** that do not use the standard function API, generate the required
1342** inline VM code.
1343**
1344** If argument csr is greater than or equal to 0, then argument reg is
1345** the first register in an array of registers guaranteed to be large
1346** enough to hold the array of arguments for each function. In this case
1347** the arguments are extracted from the current row of csr into the
drh8f26da62018-07-05 21:22:57 +00001348** array of registers before invoking OP_AggStep or OP_AggInverse
dan13078ca2018-06-13 20:29:38 +00001349**
1350** Or, if csr is less than zero, then the array of registers at reg is
1351** already populated with all columns from the current row of the sub-query.
1352**
1353** If argument regPartSize is non-zero, then it is a register containing the
1354** number of rows in the current partition.
danc9a86682018-05-30 20:44:58 +00001355*/
dan31f56392018-05-24 21:10:57 +00001356static void windowAggStep(
1357 Parse *pParse,
dan13078ca2018-06-13 20:29:38 +00001358 Window *pMWin, /* Linked list of window functions */
1359 int csr, /* Read arguments from this cursor */
1360 int bInverse, /* True to invoke xInverse instead of xStep */
dana0f6b832019-03-14 16:36:20 +00001361 int reg /* Array of registers */
dan31f56392018-05-24 21:10:57 +00001362){
1363 Vdbe *v = sqlite3GetVdbe(pParse);
1364 Window *pWin;
1365 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
dana0f6b832019-03-14 16:36:20 +00001366 FuncDef *pFunc = pWin->pFunc;
danc9a86682018-05-30 20:44:58 +00001367 int regArg;
dan2a11bb22018-06-11 20:50:25 +00001368 int nArg = windowArgCount(pWin);
dana0f6b832019-03-14 16:36:20 +00001369 int i;
dandfa552f2018-06-02 21:04:28 +00001370
dana0f6b832019-03-14 16:36:20 +00001371 for(i=0; i<nArg; i++){
danc782a812019-03-15 20:46:19 +00001372 if( i!=1 || pFunc->zName!=nth_valueName ){
1373 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+i, reg+i);
1374 }else{
1375 sqlite3VdbeAddOp3(v, OP_Column, pMWin->iEphCsr, pWin->iArgCol+i, reg+i);
1376 }
dan31f56392018-05-24 21:10:57 +00001377 }
dana0f6b832019-03-14 16:36:20 +00001378 regArg = reg;
danc9a86682018-05-30 20:44:58 +00001379
dana0f6b832019-03-14 16:36:20 +00001380 if( pMWin->regStartRowid==0
1381 && (pFunc->funcFlags & SQLITE_FUNC_MINMAX)
1382 && (pWin->eStart!=TK_UNBOUNDED)
danec891fd2018-06-06 20:51:02 +00001383 ){
dand4fc49f2018-07-07 17:30:44 +00001384 int addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regArg);
1385 VdbeCoverage(v);
danc9a86682018-05-30 20:44:58 +00001386 if( bInverse==0 ){
1387 sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1, 1);
1388 sqlite3VdbeAddOp2(v, OP_SCopy, regArg, pWin->regApp);
1389 sqlite3VdbeAddOp3(v, OP_MakeRecord, pWin->regApp, 2, pWin->regApp+2);
1390 sqlite3VdbeAddOp2(v, OP_IdxInsert, pWin->csrApp, pWin->regApp+2);
1391 }else{
1392 sqlite3VdbeAddOp4Int(v, OP_SeekGE, pWin->csrApp, 0, regArg, 1);
drh93419162018-07-11 03:27:52 +00001393 VdbeCoverageNeverTaken(v);
danc9a86682018-05-30 20:44:58 +00001394 sqlite3VdbeAddOp1(v, OP_Delete, pWin->csrApp);
1395 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
1396 }
dand4fc49f2018-07-07 17:30:44 +00001397 sqlite3VdbeJumpHere(v, addrIsNull);
danec891fd2018-06-06 20:51:02 +00001398 }else if( pWin->regApp ){
dana0f6b832019-03-14 16:36:20 +00001399 assert( pFunc->zName==nth_valueName
1400 || pFunc->zName==first_valueName
dan7095c002018-06-07 17:45:22 +00001401 );
danec891fd2018-06-06 20:51:02 +00001402 assert( bInverse==0 || bInverse==1 );
1403 sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1-bInverse, 1);
dana0f6b832019-03-14 16:36:20 +00001404 }else if( pFunc->xSFunc!=noopStepFunc ){
dan8b985602018-06-09 17:43:45 +00001405 int addrIf = 0;
1406 if( pWin->pFilter ){
1407 int regTmp;
danf5e8e312018-07-09 06:51:36 +00001408 assert( nArg==0 || nArg==pWin->pOwner->x.pList->nExpr );
1409 assert( nArg || pWin->pOwner->x.pList==0 );
dana0f6b832019-03-14 16:36:20 +00001410 regTmp = sqlite3GetTempReg(pParse);
1411 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+nArg,regTmp);
dan8b985602018-06-09 17:43:45 +00001412 addrIf = sqlite3VdbeAddOp3(v, OP_IfNot, regTmp, 0, 1);
dan01e12292018-06-27 20:24:59 +00001413 VdbeCoverage(v);
dana0f6b832019-03-14 16:36:20 +00001414 sqlite3ReleaseTempReg(pParse, regTmp);
dan8b985602018-06-09 17:43:45 +00001415 }
dana0f6b832019-03-14 16:36:20 +00001416 if( pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
danc9a86682018-05-30 20:44:58 +00001417 CollSeq *pColl;
danf5e8e312018-07-09 06:51:36 +00001418 assert( nArg>0 );
dan8b985602018-06-09 17:43:45 +00001419 pColl = sqlite3ExprNNCollSeq(pParse, pWin->pOwner->x.pList->a[0].pExpr);
danc9a86682018-05-30 20:44:58 +00001420 sqlite3VdbeAddOp4(v, OP_CollSeq, 0,0,0, (const char*)pColl, P4_COLLSEQ);
1421 }
drh8f26da62018-07-05 21:22:57 +00001422 sqlite3VdbeAddOp3(v, bInverse? OP_AggInverse : OP_AggStep,
1423 bInverse, regArg, pWin->regAccum);
dana0f6b832019-03-14 16:36:20 +00001424 sqlite3VdbeAppendP4(v, pFunc, P4_FUNCDEF);
dandfa552f2018-06-02 21:04:28 +00001425 sqlite3VdbeChangeP5(v, (u8)nArg);
dan8b985602018-06-09 17:43:45 +00001426 if( addrIf ) sqlite3VdbeJumpHere(v, addrIf);
danc9a86682018-05-30 20:44:58 +00001427 }
dan31f56392018-05-24 21:10:57 +00001428 }
1429}
1430
danc782a812019-03-15 20:46:19 +00001431typedef struct WindowCodeArg WindowCodeArg;
1432typedef struct WindowCsrAndReg WindowCsrAndReg;
1433struct WindowCsrAndReg {
1434 int csr;
1435 int reg;
1436};
1437
1438struct WindowCodeArg {
1439 Parse *pParse;
1440 Window *pMWin;
1441 Vdbe *pVdbe;
1442 int regGosub;
1443 int addrGosub;
1444 int regArg;
1445 int eDelete;
1446
1447 WindowCsrAndReg start;
1448 WindowCsrAndReg current;
1449 WindowCsrAndReg end;
1450};
1451
1452/*
1453** Values that may be passed as the second argument to windowCodeOp().
1454*/
1455#define WINDOW_RETURN_ROW 1
1456#define WINDOW_AGGINVERSE 2
1457#define WINDOW_AGGSTEP 3
1458
1459/*
1460** Generate VM code to read the window frames peer values from cursor csr into
1461** an array of registers starting at reg.
1462*/
1463static void windowReadPeerValues(
1464 WindowCodeArg *p,
1465 int csr,
1466 int reg
1467){
1468 Window *pMWin = p->pMWin;
1469 ExprList *pOrderBy = pMWin->pOrderBy;
1470 if( pOrderBy ){
1471 Vdbe *v = sqlite3GetVdbe(p->pParse);
1472 ExprList *pPart = pMWin->pPartition;
1473 int iColOff = pMWin->nBufferCol + (pPart ? pPart->nExpr : 0);
1474 int i;
1475 for(i=0; i<pOrderBy->nExpr; i++){
1476 sqlite3VdbeAddOp3(v, OP_Column, csr, iColOff+i, reg+i);
1477 }
1478 }
1479}
1480
dan13078ca2018-06-13 20:29:38 +00001481/*
dana0f6b832019-03-14 16:36:20 +00001482** Generate VM code to invoke either xValue() (bFin==0) or xFinalize()
1483** (bFin==1) for each window function in the linked list starting at
dan13078ca2018-06-13 20:29:38 +00001484** pMWin. Or, for built-in window-functions that do not use the standard
1485** API, generate the equivalent VM code.
1486*/
danc782a812019-03-15 20:46:19 +00001487static void windowAggFinal(WindowCodeArg *p, int bFin){
1488 Parse *pParse = p->pParse;
1489 Window *pMWin = p->pMWin;
dand6f784e2018-05-28 18:30:45 +00001490 Vdbe *v = sqlite3GetVdbe(pParse);
1491 Window *pWin;
1492
1493 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
dana0f6b832019-03-14 16:36:20 +00001494 if( pMWin->regStartRowid==0
1495 && (pWin->pFunc->funcFlags & SQLITE_FUNC_MINMAX)
1496 && (pWin->eStart!=TK_UNBOUNDED)
danec891fd2018-06-06 20:51:02 +00001497 ){
dand6f784e2018-05-28 18:30:45 +00001498 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
danc9a86682018-05-30 20:44:58 +00001499 sqlite3VdbeAddOp1(v, OP_Last, pWin->csrApp);
dan01e12292018-06-27 20:24:59 +00001500 VdbeCoverage(v);
danc9a86682018-05-30 20:44:58 +00001501 sqlite3VdbeAddOp3(v, OP_Column, pWin->csrApp, 0, pWin->regResult);
1502 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
danec891fd2018-06-06 20:51:02 +00001503 }else if( pWin->regApp ){
dana0f6b832019-03-14 16:36:20 +00001504 assert( pMWin->regStartRowid==0 );
dand6f784e2018-05-28 18:30:45 +00001505 }else{
dana0f6b832019-03-14 16:36:20 +00001506 int nArg = windowArgCount(pWin);
1507 if( bFin ){
1508 sqlite3VdbeAddOp2(v, OP_AggFinal, pWin->regAccum, nArg);
drh8f26da62018-07-05 21:22:57 +00001509 sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
danc9a86682018-05-30 20:44:58 +00001510 sqlite3VdbeAddOp2(v, OP_Copy, pWin->regAccum, pWin->regResult);
dan8b985602018-06-09 17:43:45 +00001511 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
danc9a86682018-05-30 20:44:58 +00001512 }else{
dana0f6b832019-03-14 16:36:20 +00001513 sqlite3VdbeAddOp3(v, OP_AggValue,pWin->regAccum,nArg,pWin->regResult);
drh8f26da62018-07-05 21:22:57 +00001514 sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
danc9a86682018-05-30 20:44:58 +00001515 }
dand6f784e2018-05-28 18:30:45 +00001516 }
1517 }
1518}
1519
dan0525b6f2019-03-18 21:19:40 +00001520/*
1521** Generate code to calculate the current values of all window functions in the
1522** p->pMWin list by doing a full scan of the current window frame. Store the
1523** results in the Window.regResult registers, ready to return the upper
1524** layer.
1525*/
danc782a812019-03-15 20:46:19 +00001526static void windowFullScan(WindowCodeArg *p){
1527 Window *pWin;
1528 Parse *pParse = p->pParse;
1529 Window *pMWin = p->pMWin;
1530 Vdbe *v = p->pVdbe;
1531
1532 int regCRowid = 0; /* Current rowid value */
1533 int regCPeer = 0; /* Current peer values */
1534 int regRowid = 0; /* AggStep rowid value */
1535 int regPeer = 0; /* AggStep peer values */
1536
1537 int nPeer;
1538 int lblNext;
1539 int lblBrk;
1540 int addrNext;
1541 int csr = pMWin->csrApp;
1542
1543 nPeer = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);
1544
1545 lblNext = sqlite3VdbeMakeLabel(pParse);
1546 lblBrk = sqlite3VdbeMakeLabel(pParse);
1547
1548 regCRowid = sqlite3GetTempReg(pParse);
1549 regRowid = sqlite3GetTempReg(pParse);
1550 if( nPeer ){
1551 regCPeer = sqlite3GetTempRange(pParse, nPeer);
1552 regPeer = sqlite3GetTempRange(pParse, nPeer);
1553 }
1554
1555 sqlite3VdbeAddOp2(v, OP_Rowid, pMWin->iEphCsr, regCRowid);
1556 windowReadPeerValues(p, pMWin->iEphCsr, regCPeer);
1557
1558 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1559 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
1560 }
1561
1562 sqlite3VdbeAddOp3(v, OP_SeekGE, csr, lblBrk, pMWin->regStartRowid);
dan1d4b25f2019-03-19 16:49:15 +00001563 VdbeCoverage(v);
danc782a812019-03-15 20:46:19 +00001564 addrNext = sqlite3VdbeCurrentAddr(v);
1565 sqlite3VdbeAddOp2(v, OP_Rowid, csr, regRowid);
1566 sqlite3VdbeAddOp3(v, OP_Gt, pMWin->regEndRowid, lblBrk, regRowid);
dan1d4b25f2019-03-19 16:49:15 +00001567 VdbeCoverageNeverNull(v);
dan108e6b22019-03-18 18:55:35 +00001568
danc782a812019-03-15 20:46:19 +00001569 if( pMWin->eExclude==TK_CURRENT ){
1570 sqlite3VdbeAddOp3(v, OP_Eq, regCRowid, lblNext, regRowid);
1571 }else if( pMWin->eExclude!=TK_NO ){
1572 int addr;
dan108e6b22019-03-18 18:55:35 +00001573 int addrEq = 0;
dan66033422019-03-19 19:19:53 +00001574 KeyInfo *pKeyInfo = 0;
dan108e6b22019-03-18 18:55:35 +00001575
dan66033422019-03-19 19:19:53 +00001576 if( pMWin->pOrderBy ){
1577 pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pMWin->pOrderBy, 0, 0);
danc782a812019-03-15 20:46:19 +00001578 }
dan66033422019-03-19 19:19:53 +00001579 if( pMWin->eExclude==TK_TIES ){
1580 addrEq = sqlite3VdbeAddOp3(v, OP_Eq, regCRowid, 0, regRowid);
1581 }
1582 if( pKeyInfo ){
1583 windowReadPeerValues(p, csr, regPeer);
1584 sqlite3VdbeAddOp3(v, OP_Compare, regPeer, regCPeer, nPeer);
1585 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
1586 addr = sqlite3VdbeCurrentAddr(v)+1;
1587 sqlite3VdbeAddOp3(v, OP_Jump, addr, lblNext, addr);
1588 VdbeCoverageEqNe(v);
1589 }else{
1590 sqlite3VdbeAddOp2(v, OP_Goto, 0, lblNext);
1591 }
danc782a812019-03-15 20:46:19 +00001592 if( addrEq ) sqlite3VdbeJumpHere(v, addrEq);
1593 }
1594
1595 windowAggStep(pParse, pMWin, csr, 0, p->regArg);
1596
1597 sqlite3VdbeResolveLabel(v, lblNext);
1598 sqlite3VdbeAddOp2(v, OP_Next, csr, addrNext);
dan1d4b25f2019-03-19 16:49:15 +00001599 VdbeCoverage(v);
danc782a812019-03-15 20:46:19 +00001600 sqlite3VdbeJumpHere(v, addrNext-1);
1601 sqlite3VdbeJumpHere(v, addrNext+1);
1602 sqlite3ReleaseTempReg(pParse, regRowid);
1603 sqlite3ReleaseTempReg(pParse, regCRowid);
1604 if( nPeer ){
1605 sqlite3ReleaseTempRange(pParse, regPeer, nPeer);
1606 sqlite3ReleaseTempRange(pParse, regCPeer, nPeer);
1607 }
1608
1609 windowAggFinal(p, 1);
1610}
1611
dan13078ca2018-06-13 20:29:38 +00001612/*
dan13078ca2018-06-13 20:29:38 +00001613** Invoke the sub-routine at regGosub (generated by code in select.c) to
1614** return the current row of Window.iEphCsr. If all window functions are
1615** aggregate window functions that use the standard API, a single
1616** OP_Gosub instruction is all that this routine generates. Extra VM code
1617** for per-row processing is only generated for the following built-in window
1618** functions:
1619**
1620** nth_value()
1621** first_value()
1622** lag()
1623** lead()
1624*/
danc782a812019-03-15 20:46:19 +00001625static void windowReturnOneRow(WindowCodeArg *p){
1626 Window *pMWin = p->pMWin;
1627 Vdbe *v = p->pVdbe;
dan7095c002018-06-07 17:45:22 +00001628
danc782a812019-03-15 20:46:19 +00001629 if( pMWin->regStartRowid ){
1630 windowFullScan(p);
1631 }else{
1632 Parse *pParse = p->pParse;
1633 Window *pWin;
1634
1635 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1636 FuncDef *pFunc = pWin->pFunc;
1637 if( pFunc->zName==nth_valueName
1638 || pFunc->zName==first_valueName
1639 ){
dana0f6b832019-03-14 16:36:20 +00001640 int csr = pWin->csrApp;
danc782a812019-03-15 20:46:19 +00001641 int lbl = sqlite3VdbeMakeLabel(pParse);
1642 int tmpReg = sqlite3GetTempReg(pParse);
1643 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
1644
1645 if( pFunc->zName==nth_valueName ){
1646 sqlite3VdbeAddOp3(v, OP_Column,pMWin->iEphCsr,pWin->iArgCol+1,tmpReg);
1647 windowCheckValue(pParse, tmpReg, 2);
1648 }else{
1649 sqlite3VdbeAddOp2(v, OP_Integer, 1, tmpReg);
1650 }
dana0f6b832019-03-14 16:36:20 +00001651 sqlite3VdbeAddOp3(v, OP_Add, tmpReg, pWin->regApp, tmpReg);
1652 sqlite3VdbeAddOp3(v, OP_Gt, pWin->regApp+1, lbl, tmpReg);
1653 VdbeCoverageNeverNull(v);
1654 sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, 0, tmpReg);
1655 VdbeCoverageNeverTaken(v);
1656 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
danc782a812019-03-15 20:46:19 +00001657 sqlite3VdbeResolveLabel(v, lbl);
1658 sqlite3ReleaseTempReg(pParse, tmpReg);
dana0f6b832019-03-14 16:36:20 +00001659 }
danc782a812019-03-15 20:46:19 +00001660 else if( pFunc->zName==leadName || pFunc->zName==lagName ){
1661 int nArg = pWin->pOwner->x.pList->nExpr;
1662 int csr = pWin->csrApp;
1663 int lbl = sqlite3VdbeMakeLabel(pParse);
1664 int tmpReg = sqlite3GetTempReg(pParse);
1665 int iEph = pMWin->iEphCsr;
1666
1667 if( nArg<3 ){
1668 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
1669 }else{
1670 sqlite3VdbeAddOp3(v, OP_Column, iEph,pWin->iArgCol+2,pWin->regResult);
1671 }
1672 sqlite3VdbeAddOp2(v, OP_Rowid, iEph, tmpReg);
1673 if( nArg<2 ){
1674 int val = (pFunc->zName==leadName ? 1 : -1);
1675 sqlite3VdbeAddOp2(v, OP_AddImm, tmpReg, val);
1676 }else{
1677 int op = (pFunc->zName==leadName ? OP_Add : OP_Subtract);
1678 int tmpReg2 = sqlite3GetTempReg(pParse);
1679 sqlite3VdbeAddOp3(v, OP_Column, iEph, pWin->iArgCol+1, tmpReg2);
1680 sqlite3VdbeAddOp3(v, op, tmpReg2, tmpReg, tmpReg);
1681 sqlite3ReleaseTempReg(pParse, tmpReg2);
1682 }
1683
1684 sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, lbl, tmpReg);
1685 VdbeCoverage(v);
1686 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
1687 sqlite3VdbeResolveLabel(v, lbl);
1688 sqlite3ReleaseTempReg(pParse, tmpReg);
danfe4e25a2018-06-07 20:08:59 +00001689 }
danfe4e25a2018-06-07 20:08:59 +00001690 }
danec891fd2018-06-06 20:51:02 +00001691 }
danc782a812019-03-15 20:46:19 +00001692 sqlite3VdbeAddOp2(v, OP_Gosub, p->regGosub, p->addrGosub);
danec891fd2018-06-06 20:51:02 +00001693}
1694
dan13078ca2018-06-13 20:29:38 +00001695/*
dan54a9ab32018-06-14 14:27:05 +00001696** Generate code to set the accumulator register for each window function
1697** in the linked list passed as the second argument to NULL. And perform
1698** any equivalent initialization required by any built-in window functions
1699** in the list.
1700*/
dan2e605682018-06-07 15:54:26 +00001701static int windowInitAccum(Parse *pParse, Window *pMWin){
1702 Vdbe *v = sqlite3GetVdbe(pParse);
1703 int regArg;
1704 int nArg = 0;
1705 Window *pWin;
1706 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
dan9a947222018-06-14 19:06:36 +00001707 FuncDef *pFunc = pWin->pFunc;
dan2e605682018-06-07 15:54:26 +00001708 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
dan2a11bb22018-06-11 20:50:25 +00001709 nArg = MAX(nArg, windowArgCount(pWin));
dan108e6b22019-03-18 18:55:35 +00001710 if( pMWin->regStartRowid==0 ){
dana0f6b832019-03-14 16:36:20 +00001711 if( pFunc->zName==nth_valueName || pFunc->zName==first_valueName ){
1712 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp);
1713 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
1714 }
dan9a947222018-06-14 19:06:36 +00001715
dana0f6b832019-03-14 16:36:20 +00001716 if( (pFunc->funcFlags & SQLITE_FUNC_MINMAX) && pWin->csrApp ){
1717 assert( pWin->eStart!=TK_UNBOUNDED );
1718 sqlite3VdbeAddOp1(v, OP_ResetSorter, pWin->csrApp);
1719 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
1720 }
dan9a947222018-06-14 19:06:36 +00001721 }
dan2e605682018-06-07 15:54:26 +00001722 }
1723 regArg = pParse->nMem+1;
1724 pParse->nMem += nArg;
1725 return regArg;
1726}
1727
danb33487b2019-03-06 17:12:32 +00001728/*
dancc7a8502019-03-11 19:50:54 +00001729** Return true if the current frame should be cached in the ephemeral table,
1730** even if there are no xInverse() calls required.
danb33487b2019-03-06 17:12:32 +00001731*/
dancc7a8502019-03-11 19:50:54 +00001732static int windowCacheFrame(Window *pMWin){
danb33487b2019-03-06 17:12:32 +00001733 Window *pWin;
dana0f6b832019-03-14 16:36:20 +00001734 if( pMWin->regStartRowid ) return 1;
danb33487b2019-03-06 17:12:32 +00001735 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1736 FuncDef *pFunc = pWin->pFunc;
dancc7a8502019-03-11 19:50:54 +00001737 if( (pFunc->zName==nth_valueName)
danb33487b2019-03-06 17:12:32 +00001738 || (pFunc->zName==first_valueName)
danb560a712019-03-13 15:29:14 +00001739 || (pFunc->zName==leadName)
danb33487b2019-03-06 17:12:32 +00001740 || (pFunc->zName==lagName)
1741 ){
1742 return 1;
1743 }
1744 }
1745 return 0;
1746}
1747
dan6c75b392019-03-08 20:02:52 +00001748/*
1749** regOld and regNew are each the first register in an array of size
1750** pOrderBy->nExpr. This function generates code to compare the two
1751** arrays of registers using the collation sequences and other comparison
1752** parameters specified by pOrderBy.
1753**
1754** If the two arrays are not equal, the contents of regNew is copied to
1755** regOld and control falls through. Otherwise, if the contents of the arrays
1756** are equal, an OP_Goto is executed. The address of the OP_Goto is returned.
1757*/
dan935d9d82019-03-12 15:21:51 +00001758static void windowIfNewPeer(
dan6c75b392019-03-08 20:02:52 +00001759 Parse *pParse,
1760 ExprList *pOrderBy,
1761 int regNew, /* First in array of new values */
dan935d9d82019-03-12 15:21:51 +00001762 int regOld, /* First in array of old values */
1763 int addr /* Jump here */
dan6c75b392019-03-08 20:02:52 +00001764){
1765 Vdbe *v = sqlite3GetVdbe(pParse);
dan6c75b392019-03-08 20:02:52 +00001766 if( pOrderBy ){
1767 int nVal = pOrderBy->nExpr;
1768 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pOrderBy, 0, 0);
1769 sqlite3VdbeAddOp3(v, OP_Compare, regOld, regNew, nVal);
1770 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
dan935d9d82019-03-12 15:21:51 +00001771 sqlite3VdbeAddOp3(v, OP_Jump,
1772 sqlite3VdbeCurrentAddr(v)+1, addr, sqlite3VdbeCurrentAddr(v)+1
dan72b9fdc2019-03-09 20:49:17 +00001773 );
dan6c75b392019-03-08 20:02:52 +00001774 VdbeCoverageEqNe(v);
1775 sqlite3VdbeAddOp3(v, OP_Copy, regNew, regOld, nVal-1);
1776 }else{
dan935d9d82019-03-12 15:21:51 +00001777 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
dan6c75b392019-03-08 20:02:52 +00001778 }
dan6c75b392019-03-08 20:02:52 +00001779}
1780
dan72b9fdc2019-03-09 20:49:17 +00001781/*
1782** This function is called as part of generating VM programs for RANGE
dan1e7cb192019-03-16 20:29:54 +00001783** offset PRECEDING/FOLLOWING frame boundaries. Assuming "ASC" order for
1784** the ORDER BY term in the window, it generates code equivalent to:
dan72b9fdc2019-03-09 20:49:17 +00001785**
1786** if( csr1.peerVal + regVal >= csr2.peerVal ) goto lbl;
dan1e7cb192019-03-16 20:29:54 +00001787**
1788** A special type of arithmetic is used such that if csr.peerVal is not
1789** a numeric type (real or integer), then the result of the addition is
1790** a copy of csr1.peerVal.
dan72b9fdc2019-03-09 20:49:17 +00001791*/
1792static void windowCodeRangeTest(
1793 WindowCodeArg *p,
1794 int op, /* OP_Ge or OP_Gt */
1795 int csr1,
1796 int regVal,
1797 int csr2,
1798 int lbl
1799){
1800 Parse *pParse = p->pParse;
1801 Vdbe *v = sqlite3GetVdbe(pParse);
1802 int reg1 = sqlite3GetTempReg(pParse);
1803 int reg2 = sqlite3GetTempReg(pParse);
dan71fddaf2019-03-11 11:12:34 +00001804 int arith = OP_Add;
dan1e7cb192019-03-16 20:29:54 +00001805 int addrGe;
dan1e7cb192019-03-16 20:29:54 +00001806
1807 int regString = ++pParse->nMem;
dan71fddaf2019-03-11 11:12:34 +00001808
1809 assert( op==OP_Ge || op==OP_Gt || op==OP_Le );
1810 assert( p->pMWin->pOrderBy && p->pMWin->pOrderBy->nExpr==1 );
1811 if( p->pMWin->pOrderBy->a[0].sortOrder ){
1812 switch( op ){
1813 case OP_Ge: op = OP_Le; break;
1814 case OP_Gt: op = OP_Lt; break;
1815 default: assert( op==OP_Le ); op = OP_Ge; break;
1816 }
1817 arith = OP_Subtract;
1818 }
1819
dan72b9fdc2019-03-09 20:49:17 +00001820 windowReadPeerValues(p, csr1, reg1);
1821 windowReadPeerValues(p, csr2, reg2);
dan1e7cb192019-03-16 20:29:54 +00001822
1823 /* Check if the peer value for csr1 value is a text or blob by comparing
danbdabe742019-03-18 16:51:24 +00001824 ** it to the smallest possible string - ''. If it is, jump over the
1825 ** OP_Add or OP_Subtract operation and proceed directly to the comparison. */
dan1e7cb192019-03-16 20:29:54 +00001826 sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC);
1827 addrGe = sqlite3VdbeAddOp3(v, OP_Ge, regString, 0, reg1);
dan1d4b25f2019-03-19 16:49:15 +00001828 VdbeCoverage(v);
dan71fddaf2019-03-11 11:12:34 +00001829 sqlite3VdbeAddOp3(v, arith, regVal, reg1, reg1);
dan1e7cb192019-03-16 20:29:54 +00001830 sqlite3VdbeJumpHere(v, addrGe);
dan72b9fdc2019-03-09 20:49:17 +00001831 sqlite3VdbeAddOp3(v, op, reg2, lbl, reg1);
danbdabe742019-03-18 16:51:24 +00001832 sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
dan1d4b25f2019-03-19 16:49:15 +00001833 VdbeCoverage(v);
dan1e7cb192019-03-16 20:29:54 +00001834
dan72b9fdc2019-03-09 20:49:17 +00001835 sqlite3ReleaseTempReg(pParse, reg1);
1836 sqlite3ReleaseTempReg(pParse, reg2);
dan72b9fdc2019-03-09 20:49:17 +00001837}
1838
dan0525b6f2019-03-18 21:19:40 +00001839/*
1840** Helper function for sqlite3WindowCodeStep(). Each call to this function
1841** generates VM code for a single RETURN_ROW, AGGSTEP or AGGINVERSE
1842** operation. Refer to the header comment for sqlite3WindowCodeStep() for
1843** details.
1844*/
dan00267b82019-03-06 21:04:11 +00001845static int windowCodeOp(
dan0525b6f2019-03-18 21:19:40 +00001846 WindowCodeArg *p, /* Context object */
1847 int op, /* WINDOW_RETURN_ROW, AGGSTEP or AGGINVERSE */
1848 int regCountdown, /* Register for OP_IfPos countdown */
1849 int jumpOnEof /* Jump here if stepped cursor reaches EOF */
dan00267b82019-03-06 21:04:11 +00001850){
dan6c75b392019-03-08 20:02:52 +00001851 int csr, reg;
1852 Parse *pParse = p->pParse;
dan54975cd2019-03-07 20:47:46 +00001853 Window *pMWin = p->pMWin;
dan00267b82019-03-06 21:04:11 +00001854 int ret = 0;
1855 Vdbe *v = p->pVdbe;
1856 int addrIf = 0;
dan6c75b392019-03-08 20:02:52 +00001857 int addrContinue = 0;
1858 int addrGoto = 0;
1859 int bPeer = (pMWin->eType!=TK_ROWS);
dan00267b82019-03-06 21:04:11 +00001860
dan72b9fdc2019-03-09 20:49:17 +00001861 int lblDone = sqlite3VdbeMakeLabel(pParse);
1862 int addrNextRange = 0;
1863
dan54975cd2019-03-07 20:47:46 +00001864 /* Special case - WINDOW_AGGINVERSE is always a no-op if the frame
1865 ** starts with UNBOUNDED PRECEDING. */
1866 if( op==WINDOW_AGGINVERSE && pMWin->eStart==TK_UNBOUNDED ){
1867 assert( regCountdown==0 && jumpOnEof==0 );
1868 return 0;
1869 }
1870
dan00267b82019-03-06 21:04:11 +00001871 if( regCountdown>0 ){
dan72b9fdc2019-03-09 20:49:17 +00001872 if( pMWin->eType==TK_RANGE ){
1873 addrNextRange = sqlite3VdbeCurrentAddr(v);
dan0525b6f2019-03-18 21:19:40 +00001874 assert( op==WINDOW_AGGINVERSE || op==WINDOW_AGGSTEP );
1875 if( op==WINDOW_AGGINVERSE ){
1876 if( pMWin->eStart==TK_FOLLOWING ){
dan72b9fdc2019-03-09 20:49:17 +00001877 windowCodeRangeTest(
dan0525b6f2019-03-18 21:19:40 +00001878 p, OP_Le, p->current.csr, regCountdown, p->start.csr, lblDone
dan72b9fdc2019-03-09 20:49:17 +00001879 );
dan0525b6f2019-03-18 21:19:40 +00001880 }else{
1881 windowCodeRangeTest(
1882 p, OP_Ge, p->start.csr, regCountdown, p->current.csr, lblDone
1883 );
dan72b9fdc2019-03-09 20:49:17 +00001884 }
dan0525b6f2019-03-18 21:19:40 +00001885 }else{
1886 windowCodeRangeTest(
1887 p, OP_Gt, p->end.csr, regCountdown, p->current.csr, lblDone
1888 );
dan72b9fdc2019-03-09 20:49:17 +00001889 }
dan72b9fdc2019-03-09 20:49:17 +00001890 }else{
1891 addrIf = sqlite3VdbeAddOp3(v, OP_IfPos, regCountdown, 0, 1);
dan1d4b25f2019-03-19 16:49:15 +00001892 VdbeCoverage(v);
dan72b9fdc2019-03-09 20:49:17 +00001893 }
dan00267b82019-03-06 21:04:11 +00001894 }
1895
dan0525b6f2019-03-18 21:19:40 +00001896 if( op==WINDOW_RETURN_ROW && pMWin->regStartRowid==0 ){
danc782a812019-03-15 20:46:19 +00001897 windowAggFinal(p, 0);
dan6c75b392019-03-08 20:02:52 +00001898 }
1899 addrContinue = sqlite3VdbeCurrentAddr(v);
dan00267b82019-03-06 21:04:11 +00001900 switch( op ){
1901 case WINDOW_RETURN_ROW:
dan6c75b392019-03-08 20:02:52 +00001902 csr = p->current.csr;
1903 reg = p->current.reg;
danc782a812019-03-15 20:46:19 +00001904 windowReturnOneRow(p);
dan00267b82019-03-06 21:04:11 +00001905 break;
1906
1907 case WINDOW_AGGINVERSE:
dan6c75b392019-03-08 20:02:52 +00001908 csr = p->start.csr;
1909 reg = p->start.reg;
dana0f6b832019-03-14 16:36:20 +00001910 if( pMWin->regStartRowid ){
1911 assert( pMWin->regEndRowid );
1912 sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regStartRowid, 1);
1913 }else{
1914 windowAggStep(pParse, pMWin, csr, 1, p->regArg);
1915 }
dan00267b82019-03-06 21:04:11 +00001916 break;
1917
dan0525b6f2019-03-18 21:19:40 +00001918 default:
1919 assert( op==WINDOW_AGGSTEP );
dan6c75b392019-03-08 20:02:52 +00001920 csr = p->end.csr;
1921 reg = p->end.reg;
dana0f6b832019-03-14 16:36:20 +00001922 if( pMWin->regStartRowid ){
1923 assert( pMWin->regEndRowid );
1924 sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regEndRowid, 1);
1925 }else{
1926 windowAggStep(pParse, pMWin, csr, 0, p->regArg);
1927 }
dan00267b82019-03-06 21:04:11 +00001928 break;
1929 }
1930
danb560a712019-03-13 15:29:14 +00001931 if( op==p->eDelete ){
1932 sqlite3VdbeAddOp1(v, OP_Delete, csr);
1933 sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
1934 }
1935
danc8137502019-03-07 19:26:17 +00001936 if( jumpOnEof ){
1937 sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+2);
dan1d4b25f2019-03-19 16:49:15 +00001938 VdbeCoverage(v);
danc8137502019-03-07 19:26:17 +00001939 ret = sqlite3VdbeAddOp0(v, OP_Goto);
1940 }else{
dan6c75b392019-03-08 20:02:52 +00001941 sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+1+bPeer);
dan1d4b25f2019-03-19 16:49:15 +00001942 VdbeCoverage(v);
dan6c75b392019-03-08 20:02:52 +00001943 if( bPeer ){
1944 addrGoto = sqlite3VdbeAddOp0(v, OP_Goto);
1945 }
dan00267b82019-03-06 21:04:11 +00001946 }
danc8137502019-03-07 19:26:17 +00001947
dan6c75b392019-03-08 20:02:52 +00001948 if( bPeer ){
dan6c75b392019-03-08 20:02:52 +00001949 int nReg = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);
1950 int regTmp = (nReg ? sqlite3GetTempRange(pParse, nReg) : 0);
1951 windowReadPeerValues(p, csr, regTmp);
dan935d9d82019-03-12 15:21:51 +00001952 windowIfNewPeer(pParse, pMWin->pOrderBy, regTmp, reg, addrContinue);
dan6c75b392019-03-08 20:02:52 +00001953 sqlite3ReleaseTempRange(pParse, regTmp, nReg);
dan00267b82019-03-06 21:04:11 +00001954 }
dan6c75b392019-03-08 20:02:52 +00001955
dan72b9fdc2019-03-09 20:49:17 +00001956 if( addrNextRange ){
1957 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNextRange);
1958 }
1959 sqlite3VdbeResolveLabel(v, lblDone);
dan6c75b392019-03-08 20:02:52 +00001960 if( addrGoto ) sqlite3VdbeJumpHere(v, addrGoto);
1961 if( addrIf ) sqlite3VdbeJumpHere(v, addrIf);
dan00267b82019-03-06 21:04:11 +00001962 return ret;
1963}
1964
dana786e452019-03-11 18:17:04 +00001965
dan00267b82019-03-06 21:04:11 +00001966/*
dana786e452019-03-11 18:17:04 +00001967** Allocate and return a duplicate of the Window object indicated by the
1968** third argument. Set the Window.pOwner field of the new object to
1969** pOwner.
1970*/
1971Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p){
1972 Window *pNew = 0;
1973 if( ALWAYS(p) ){
1974 pNew = sqlite3DbMallocZero(db, sizeof(Window));
1975 if( pNew ){
1976 pNew->zName = sqlite3DbStrDup(db, p->zName);
1977 pNew->pFilter = sqlite3ExprDup(db, p->pFilter, 0);
1978 pNew->pFunc = p->pFunc;
1979 pNew->pPartition = sqlite3ExprListDup(db, p->pPartition, 0);
1980 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, 0);
1981 pNew->eType = p->eType;
1982 pNew->eEnd = p->eEnd;
1983 pNew->eStart = p->eStart;
danc782a812019-03-15 20:46:19 +00001984 pNew->eExclude = p->eExclude;
dana786e452019-03-11 18:17:04 +00001985 pNew->pStart = sqlite3ExprDup(db, p->pStart, 0);
1986 pNew->pEnd = sqlite3ExprDup(db, p->pEnd, 0);
1987 pNew->pOwner = pOwner;
1988 }
1989 }
1990 return pNew;
1991}
1992
1993/*
1994** Return a copy of the linked list of Window objects passed as the
1995** second argument.
1996*/
1997Window *sqlite3WindowListDup(sqlite3 *db, Window *p){
1998 Window *pWin;
1999 Window *pRet = 0;
2000 Window **pp = &pRet;
2001
2002 for(pWin=p; pWin; pWin=pWin->pNextWin){
2003 *pp = sqlite3WindowDup(db, 0, pWin);
2004 if( *pp==0 ) break;
2005 pp = &((*pp)->pNextWin);
2006 }
2007
2008 return pRet;
2009}
2010
2011/*
2012** sqlite3WhereBegin() has already been called for the SELECT statement
2013** passed as the second argument when this function is invoked. It generates
2014** code to populate the Window.regResult register for each window function
2015** and invoke the sub-routine at instruction addrGosub once for each row.
2016** sqlite3WhereEnd() is always called before returning.
dan00267b82019-03-06 21:04:11 +00002017**
dana786e452019-03-11 18:17:04 +00002018** This function handles several different types of window frames, which
2019** require slightly different processing. The following pseudo code is
2020** used to implement window frames of the form:
dan00267b82019-03-06 21:04:11 +00002021**
dana786e452019-03-11 18:17:04 +00002022** ROWS BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
dan00267b82019-03-06 21:04:11 +00002023**
dana786e452019-03-11 18:17:04 +00002024** Other window frame types use variants of the following:
2025**
2026** ... loop started by sqlite3WhereBegin() ...
dan00267b82019-03-06 21:04:11 +00002027** if( new partition ){
2028** Gosub flush
dana786e452019-03-11 18:17:04 +00002029** }
dan00267b82019-03-06 21:04:11 +00002030** Insert new row into eph table.
dana786e452019-03-11 18:17:04 +00002031**
dan00267b82019-03-06 21:04:11 +00002032** if( first row of partition ){
dana786e452019-03-11 18:17:04 +00002033** // Rewind three cursors, all open on the eph table.
2034** Rewind(csrEnd);
2035** Rewind(csrStart);
2036** Rewind(csrCurrent);
2037**
dan00267b82019-03-06 21:04:11 +00002038** regEnd = <expr2> // FOLLOWING expression
2039** regStart = <expr1> // PRECEDING expression
2040** }else{
dana786e452019-03-11 18:17:04 +00002041** // First time this branch is taken, the eph table contains two
2042** // rows. The first row in the partition, which all three cursors
2043** // currently point to, and the following row.
2044** AGGSTEP
dan00267b82019-03-06 21:04:11 +00002045** if( (regEnd--)<=0 ){
dana786e452019-03-11 18:17:04 +00002046** RETURN_ROW
2047** if( (regStart--)<=0 ){
2048** AGGINVERSE
dan00267b82019-03-06 21:04:11 +00002049** }
2050** }
dana786e452019-03-11 18:17:04 +00002051** }
2052** }
dan00267b82019-03-06 21:04:11 +00002053** flush:
dana786e452019-03-11 18:17:04 +00002054** AGGSTEP
2055** while( 1 ){
2056** RETURN ROW
2057** if( csrCurrent is EOF ) break;
2058** if( (regStart--)<=0 ){
2059** AggInverse(csrStart)
2060** Next(csrStart)
dan00267b82019-03-06 21:04:11 +00002061** }
dana786e452019-03-11 18:17:04 +00002062** }
dan00267b82019-03-06 21:04:11 +00002063**
dana786e452019-03-11 18:17:04 +00002064** The pseudo-code above uses the following shorthand:
dan00267b82019-03-06 21:04:11 +00002065**
dana786e452019-03-11 18:17:04 +00002066** AGGSTEP: invoke the aggregate xStep() function for each window function
2067** with arguments read from the current row of cursor csrEnd, then
2068** step cursor csrEnd forward one row (i.e. sqlite3BtreeNext()).
2069**
2070** RETURN_ROW: return a row to the caller based on the contents of the
2071** current row of csrCurrent and the current state of all
2072** aggregates. Then step cursor csrCurrent forward one row.
2073**
2074** AGGINVERSE: invoke the aggregate xInverse() function for each window
2075** functions with arguments read from the current row of cursor
2076** csrStart. Then step csrStart forward one row.
2077**
2078** There are two other ROWS window frames that are handled significantly
2079** differently from the above - "BETWEEN <expr> PRECEDING AND <expr> PRECEDING"
2080** and "BETWEEN <expr> FOLLOWING AND <expr> FOLLOWING". These are special
2081** cases because they change the order in which the three cursors (csrStart,
2082** csrCurrent and csrEnd) iterate through the ephemeral table. Cases that
2083** use UNBOUNDED or CURRENT ROW are much simpler variations on one of these
2084** three.
2085**
2086** ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
2087**
2088** ... loop started by sqlite3WhereBegin() ...
dan00267b82019-03-06 21:04:11 +00002089** if( new partition ){
2090** Gosub flush
dana786e452019-03-11 18:17:04 +00002091** }
dan00267b82019-03-06 21:04:11 +00002092** Insert new row into eph table.
2093** if( first row of partition ){
dan935d9d82019-03-12 15:21:51 +00002094** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
dana786e452019-03-11 18:17:04 +00002095** regEnd = <expr2>
2096** regStart = <expr1>
dan00267b82019-03-06 21:04:11 +00002097** }else{
dana786e452019-03-11 18:17:04 +00002098** if( (regEnd--)<=0 ){
2099** AGGSTEP
2100** }
2101** RETURN_ROW
2102** if( (regStart--)<=0 ){
2103** AGGINVERSE
2104** }
2105** }
2106** }
dan00267b82019-03-06 21:04:11 +00002107** flush:
dana786e452019-03-11 18:17:04 +00002108** if( (regEnd--)<=0 ){
2109** AGGSTEP
2110** }
2111** RETURN_ROW
2112**
2113**
2114** ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
2115**
2116** ... loop started by sqlite3WhereBegin() ...
2117** if( new partition ){
2118** Gosub flush
2119** }
2120** Insert new row into eph table.
2121** if( first row of partition ){
dan935d9d82019-03-12 15:21:51 +00002122** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
dana786e452019-03-11 18:17:04 +00002123** regEnd = <expr2>
2124** regStart = regEnd - <expr1>
2125** }else{
2126** AGGSTEP
2127** if( (regEnd--)<=0 ){
2128** RETURN_ROW
2129** }
2130** if( (regStart--)<=0 ){
2131** AGGINVERSE
2132** }
2133** }
2134** }
2135** flush:
2136** AGGSTEP
2137** while( 1 ){
2138** if( (regEnd--)<=0 ){
2139** RETURN_ROW
2140** if( eof ) break;
2141** }
2142** if( (regStart--)<=0 ){
2143** AGGINVERSE
2144** if( eof ) break
2145** }
2146** }
2147** while( !eof csrCurrent ){
2148** RETURN_ROW
2149** }
2150**
2151** For the most part, the patterns above are adapted to support UNBOUNDED by
2152** assuming that it is equivalent to "infinity PRECEDING/FOLLOWING" and
2153** CURRENT ROW by assuming that it is equivilent to "0 PRECEDING/FOLLOWING".
2154** This is optimized of course - branches that will never be taken and
2155** conditions that are always true are omitted from the VM code. The only
2156** exceptional case is:
2157**
2158** ROWS BETWEEN <expr1> FOLLOWING AND UNBOUNDED FOLLOWING
2159**
2160** ... loop started by sqlite3WhereBegin() ...
2161** if( new partition ){
2162** Gosub flush
2163** }
2164** Insert new row into eph table.
2165** if( first row of partition ){
dan935d9d82019-03-12 15:21:51 +00002166** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
dana786e452019-03-11 18:17:04 +00002167** regStart = <expr1>
2168** }else{
2169** AGGSTEP
2170** }
2171** }
2172** flush:
2173** AGGSTEP
2174** while( 1 ){
2175** if( (regStart--)<=0 ){
2176** AGGINVERSE
2177** if( eof ) break
2178** }
2179** RETURN_ROW
2180** }
2181** while( !eof csrCurrent ){
2182** RETURN_ROW
2183** }
dan935d9d82019-03-12 15:21:51 +00002184**
2185** Also requiring special handling are the cases:
2186**
2187** ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
2188** ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
2189**
2190** when (expr1 < expr2). This is detected at runtime, not by this function.
2191** To handle this case, the pseudo-code programs depicted above are modified
2192** slightly to be:
2193**
2194** ... loop started by sqlite3WhereBegin() ...
2195** if( new partition ){
2196** Gosub flush
2197** }
2198** Insert new row into eph table.
2199** if( first row of partition ){
2200** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2201** regEnd = <expr2>
2202** regStart = <expr1>
2203** if( regEnd < regStart ){
2204** RETURN_ROW
2205** delete eph table contents
2206** continue
2207** }
2208** ...
2209**
2210** The new "continue" statement in the above jumps to the next iteration
2211** of the outer loop - the one started by sqlite3WhereBegin().
2212**
2213** The various GROUPS cases are implemented using the same patterns as
2214** ROWS. The VM code is modified slightly so that:
2215**
2216** 1. The else branch in the main loop is only taken if the row just
2217** added to the ephemeral table is the start of a new group. In
2218** other words, it becomes:
2219**
2220** ... loop started by sqlite3WhereBegin() ...
2221** if( new partition ){
2222** Gosub flush
2223** }
2224** Insert new row into eph table.
2225** if( first row of partition ){
2226** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2227** regEnd = <expr2>
2228** regStart = <expr1>
2229** }else if( new group ){
2230** ...
2231** }
2232** }
2233**
2234** 2. Instead of processing a single row, each RETURN_ROW, AGGSTEP or
2235** AGGINVERSE step processes the current row of the relevant cursor and
2236** all subsequent rows belonging to the same group.
2237**
2238** RANGE window frames are a little different again. As for GROUPS, the
2239** main loop runs once per group only. And RETURN_ROW, AGGSTEP and AGGINVERSE
2240** deal in groups instead of rows. As for ROWS and GROUPS, there are three
2241** basic cases:
2242**
2243** RANGE BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
2244**
2245** ... loop started by sqlite3WhereBegin() ...
2246** if( new partition ){
2247** Gosub flush
2248** }
2249** Insert new row into eph table.
2250** if( first row of partition ){
2251** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2252** regEnd = <expr2>
2253** regStart = <expr1>
2254** }else{
2255** AGGSTEP
2256** while( (csrCurrent.key + regEnd) < csrEnd.key ){
2257** RETURN_ROW
2258** while( csrStart.key + regStart) < csrCurrent.key ){
2259** AGGINVERSE
2260** }
2261** }
2262** }
2263** }
2264** flush:
2265** AGGSTEP
2266** while( 1 ){
2267** RETURN ROW
2268** if( csrCurrent is EOF ) break;
2269** while( csrStart.key + regStart) < csrCurrent.key ){
2270** AGGINVERSE
2271** }
2272** }
2273** }
2274**
2275** In the above notation, "csr.key" means the current value of the ORDER BY
2276** expression (there is only ever 1 for a RANGE that uses an <expr> FOLLOWING
2277** or <expr PRECEDING) read from cursor csr.
2278**
2279** RANGE BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
2280**
2281** ... loop started by sqlite3WhereBegin() ...
2282** if( new partition ){
2283** Gosub flush
2284** }
2285** Insert new row into eph table.
2286** if( first row of partition ){
2287** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2288** regEnd = <expr2>
2289** regStart = <expr1>
2290** }else{
2291** while( (csrEnd.key + regEnd) <= csrCurrent.key ){
2292** AGGSTEP
2293** }
2294** RETURN_ROW
2295** while( (csrStart.key + regStart) < csrCurrent.key ){
2296** AGGINVERSE
2297** }
2298** }
2299** }
2300** flush:
2301** while( (csrEnd.key + regEnd) <= csrCurrent.key ){
2302** AGGSTEP
2303** }
2304** RETURN_ROW
2305**
2306** RANGE BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
2307**
2308** ... loop started by sqlite3WhereBegin() ...
2309** if( new partition ){
2310** Gosub flush
2311** }
2312** Insert new row into eph table.
2313** if( first row of partition ){
2314** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2315** regEnd = <expr2>
2316** regStart = <expr1>
2317** }else{
2318** AGGSTEP
2319** while( (csrCurrent.key + regEnd) < csrEnd.key ){
2320** while( (csrCurrent.key + regStart) > csrStart.key ){
2321** AGGINVERSE
2322** }
2323** RETURN_ROW
2324** }
2325** }
2326** }
2327** flush:
2328** AGGSTEP
2329** while( 1 ){
2330** while( (csrCurrent.key + regStart) > csrStart.key ){
2331** AGGINVERSE
2332** if( eof ) break "while( 1 )" loop.
2333** }
2334** RETURN_ROW
2335** }
2336** while( !eof csrCurrent ){
2337** RETURN_ROW
2338** }
2339**
danb6f2dea2019-03-13 17:20:27 +00002340** The text above leaves out many details. Refer to the code and comments
2341** below for a more complete picture.
dan00267b82019-03-06 21:04:11 +00002342*/
dana786e452019-03-11 18:17:04 +00002343void sqlite3WindowCodeStep(
dancc7a8502019-03-11 19:50:54 +00002344 Parse *pParse, /* Parse context */
dana786e452019-03-11 18:17:04 +00002345 Select *p, /* Rewritten SELECT statement */
2346 WhereInfo *pWInfo, /* Context returned by sqlite3WhereBegin() */
2347 int regGosub, /* Register for OP_Gosub */
2348 int addrGosub /* OP_Gosub here to return each row */
dan680f6e82019-03-04 21:07:11 +00002349){
2350 Window *pMWin = p->pWin;
dan6c75b392019-03-08 20:02:52 +00002351 ExprList *pOrderBy = pMWin->pOrderBy;
dan680f6e82019-03-04 21:07:11 +00002352 Vdbe *v = sqlite3GetVdbe(pParse);
dana786e452019-03-11 18:17:04 +00002353 int csrWrite; /* Cursor used to write to eph. table */
2354 int csrInput = p->pSrc->a[0].iCursor; /* Cursor of sub-select */
2355 int nInput = p->pSrc->a[0].pTab->nCol; /* Number of cols returned by sub */
2356 int iInput; /* To iterate through sub cols */
danbf845152019-03-16 10:15:24 +00002357 int addrNe; /* Address of OP_Ne */
dana786e452019-03-11 18:17:04 +00002358 int addrGosubFlush; /* Address of OP_Gosub to flush: */
2359 int addrInteger; /* Address of OP_Integer */
dand4461652019-03-13 08:28:51 +00002360 int addrEmpty; /* Address of OP_Rewind in flush: */
dan54975cd2019-03-07 20:47:46 +00002361 int regStart = 0; /* Value of <expr> PRECEDING */
2362 int regEnd = 0; /* Value of <expr> FOLLOWING */
dana786e452019-03-11 18:17:04 +00002363 int regNew; /* Array of registers holding new input row */
2364 int regRecord; /* regNew array in record form */
2365 int regRowid; /* Rowid for regRecord in eph table */
2366 int regNewPeer = 0; /* Peer values for new row (part of regNew) */
2367 int regPeer = 0; /* Peer values for current row */
dand4461652019-03-13 08:28:51 +00002368 int regFlushPart = 0; /* Register for "Gosub flush_partition" */
dana786e452019-03-11 18:17:04 +00002369 WindowCodeArg s; /* Context object for sub-routines */
dan935d9d82019-03-12 15:21:51 +00002370 int lblWhereEnd; /* Label just before sqlite3WhereEnd() code */
dan680f6e82019-03-04 21:07:11 +00002371
dan72b9fdc2019-03-09 20:49:17 +00002372 assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_CURRENT
2373 || pMWin->eStart==TK_FOLLOWING || pMWin->eStart==TK_UNBOUNDED
2374 );
2375 assert( pMWin->eEnd==TK_FOLLOWING || pMWin->eEnd==TK_CURRENT
2376 || pMWin->eEnd==TK_UNBOUNDED || pMWin->eEnd==TK_PRECEDING
2377 );
dan108e6b22019-03-18 18:55:35 +00002378 assert( pMWin->eExclude==0 || pMWin->eExclude==TK_CURRENT
2379 || pMWin->eExclude==TK_GROUP || pMWin->eExclude==TK_TIES
2380 || pMWin->eExclude==TK_NO
2381 );
dan72b9fdc2019-03-09 20:49:17 +00002382
dan935d9d82019-03-12 15:21:51 +00002383 lblWhereEnd = sqlite3VdbeMakeLabel(pParse);
dana786e452019-03-11 18:17:04 +00002384
2385 /* Fill in the context object */
dan00267b82019-03-06 21:04:11 +00002386 memset(&s, 0, sizeof(WindowCodeArg));
2387 s.pParse = pParse;
2388 s.pMWin = pMWin;
2389 s.pVdbe = v;
2390 s.regGosub = regGosub;
2391 s.addrGosub = addrGosub;
dan6c75b392019-03-08 20:02:52 +00002392 s.current.csr = pMWin->iEphCsr;
dana786e452019-03-11 18:17:04 +00002393 csrWrite = s.current.csr+1;
dan6c75b392019-03-08 20:02:52 +00002394 s.start.csr = s.current.csr+2;
2395 s.end.csr = s.current.csr+3;
danb33487b2019-03-06 17:12:32 +00002396
danb560a712019-03-13 15:29:14 +00002397 /* Figure out when rows may be deleted from the ephemeral table. There
2398 ** are four options - they may never be deleted (eDelete==0), they may
2399 ** be deleted as soon as they are no longer part of the window frame
2400 ** (eDelete==WINDOW_AGGINVERSE), they may be deleted as after the row
2401 ** has been returned to the caller (WINDOW_RETURN_ROW), or they may
2402 ** be deleted after they enter the frame (WINDOW_AGGSTEP). */
2403 switch( pMWin->eStart ){
2404 case TK_FOLLOWING: {
danbdabe742019-03-18 16:51:24 +00002405 if( pMWin->eType!=TK_RANGE ){
2406 sqlite3 *db = pParse->db;
2407 sqlite3_value *pVal = 0;
2408 sqlite3ValueFromExpr(db,pMWin->pStart,db->enc,SQLITE_AFF_NUMERIC,&pVal);
2409 if( pVal && sqlite3_value_int(pVal)>0 ){
2410 s.eDelete = WINDOW_RETURN_ROW;
2411 }
2412 sqlite3ValueFree(pVal);
danb560a712019-03-13 15:29:14 +00002413 }
danb560a712019-03-13 15:29:14 +00002414 break;
2415 }
2416 case TK_UNBOUNDED:
2417 if( windowCacheFrame(pMWin)==0 ){
2418 if( pMWin->eEnd==TK_PRECEDING ){
2419 s.eDelete = WINDOW_AGGSTEP;
2420 }else{
2421 s.eDelete = WINDOW_RETURN_ROW;
2422 }
2423 }
2424 break;
2425 default:
2426 s.eDelete = WINDOW_AGGINVERSE;
2427 break;
2428 }
2429
dand4461652019-03-13 08:28:51 +00002430 /* Allocate registers for the array of values from the sub-query, the
2431 ** samve values in record form, and the rowid used to insert said record
2432 ** into the ephemeral table. */
dana786e452019-03-11 18:17:04 +00002433 regNew = pParse->nMem+1;
2434 pParse->nMem += nInput;
2435 regRecord = ++pParse->nMem;
2436 regRowid = ++pParse->nMem;
dan54975cd2019-03-07 20:47:46 +00002437
dana786e452019-03-11 18:17:04 +00002438 /* If the window frame contains an "<expr> PRECEDING" or "<expr> FOLLOWING"
2439 ** clause, allocate registers to store the results of evaluating each
2440 ** <expr>. */
dan54975cd2019-03-07 20:47:46 +00002441 if( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_FOLLOWING ){
2442 regStart = ++pParse->nMem;
2443 }
2444 if( pMWin->eEnd==TK_PRECEDING || pMWin->eEnd==TK_FOLLOWING ){
2445 regEnd = ++pParse->nMem;
2446 }
dan680f6e82019-03-04 21:07:11 +00002447
dan72b9fdc2019-03-09 20:49:17 +00002448 /* If this is not a "ROWS BETWEEN ..." frame, then allocate arrays of
dana786e452019-03-11 18:17:04 +00002449 ** registers to store copies of the ORDER BY expressions (peer values)
2450 ** for the main loop, and for each cursor (start, current and end). */
dan6c75b392019-03-08 20:02:52 +00002451 if( pMWin->eType!=TK_ROWS ){
2452 int nPeer = (pOrderBy ? pOrderBy->nExpr : 0);
dana786e452019-03-11 18:17:04 +00002453 regNewPeer = regNew + pMWin->nBufferCol;
dan6c75b392019-03-08 20:02:52 +00002454 if( pMWin->pPartition ) regNewPeer += pMWin->pPartition->nExpr;
dan6c75b392019-03-08 20:02:52 +00002455 regPeer = pParse->nMem+1; pParse->nMem += nPeer;
2456 s.start.reg = pParse->nMem+1; pParse->nMem += nPeer;
2457 s.current.reg = pParse->nMem+1; pParse->nMem += nPeer;
2458 s.end.reg = pParse->nMem+1; pParse->nMem += nPeer;
2459 }
2460
dan680f6e82019-03-04 21:07:11 +00002461 /* Load the column values for the row returned by the sub-select
dana786e452019-03-11 18:17:04 +00002462 ** into an array of registers starting at regNew. Assemble them into
2463 ** a record in register regRecord. */
2464 for(iInput=0; iInput<nInput; iInput++){
2465 sqlite3VdbeAddOp3(v, OP_Column, csrInput, iInput, regNew+iInput);
dan680f6e82019-03-04 21:07:11 +00002466 }
dana786e452019-03-11 18:17:04 +00002467 sqlite3VdbeAddOp3(v, OP_MakeRecord, regNew, nInput, regRecord);
dan680f6e82019-03-04 21:07:11 +00002468
danb33487b2019-03-06 17:12:32 +00002469 /* An input row has just been read into an array of registers starting
dana786e452019-03-11 18:17:04 +00002470 ** at regNew. If the window has a PARTITION clause, this block generates
danb33487b2019-03-06 17:12:32 +00002471 ** VM code to check if the input row is the start of a new partition.
2472 ** If so, it does an OP_Gosub to an address to be filled in later. The
dana786e452019-03-11 18:17:04 +00002473 ** address of the OP_Gosub is stored in local variable addrGosubFlush. */
dan680f6e82019-03-04 21:07:11 +00002474 if( pMWin->pPartition ){
2475 int addr;
2476 ExprList *pPart = pMWin->pPartition;
2477 int nPart = pPart->nExpr;
dana786e452019-03-11 18:17:04 +00002478 int regNewPart = regNew + pMWin->nBufferCol;
dan680f6e82019-03-04 21:07:11 +00002479 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pPart, 0, 0);
2480
dand4461652019-03-13 08:28:51 +00002481 regFlushPart = ++pParse->nMem;
dan680f6e82019-03-04 21:07:11 +00002482 addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPart, pMWin->regPart, nPart);
2483 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
danb33487b2019-03-06 17:12:32 +00002484 sqlite3VdbeAddOp3(v, OP_Jump, addr+2, addr+4, addr+2);
dan680f6e82019-03-04 21:07:11 +00002485 VdbeCoverageEqNe(v);
2486 addrGosubFlush = sqlite3VdbeAddOp1(v, OP_Gosub, regFlushPart);
2487 VdbeComment((v, "call flush_partition"));
danb33487b2019-03-06 17:12:32 +00002488 sqlite3VdbeAddOp3(v, OP_Copy, regNewPart, pMWin->regPart, nPart-1);
dan680f6e82019-03-04 21:07:11 +00002489 }
2490
2491 /* Insert the new row into the ephemeral table */
2492 sqlite3VdbeAddOp2(v, OP_NewRowid, csrWrite, regRowid);
2493 sqlite3VdbeAddOp3(v, OP_Insert, csrWrite, regRecord, regRowid);
danbf845152019-03-16 10:15:24 +00002494 addrNe = sqlite3VdbeAddOp3(v, OP_Ne, pMWin->regOne, 0, regRowid);
dan1d4b25f2019-03-19 16:49:15 +00002495 VdbeCoverage(v);
danb25a2142019-03-05 19:29:36 +00002496
danb33487b2019-03-06 17:12:32 +00002497 /* This block is run for the first row of each partition */
dana786e452019-03-11 18:17:04 +00002498 s.regArg = windowInitAccum(pParse, pMWin);
dan680f6e82019-03-04 21:07:11 +00002499
dan54975cd2019-03-07 20:47:46 +00002500 if( regStart ){
2501 sqlite3ExprCode(pParse, pMWin->pStart, regStart);
danbb407272019-03-12 18:28:51 +00002502 windowCheckValue(pParse, regStart, 0 + (pMWin->eType==TK_RANGE ? 3 : 0));
dan54975cd2019-03-07 20:47:46 +00002503 }
2504 if( regEnd ){
2505 sqlite3ExprCode(pParse, pMWin->pEnd, regEnd);
danbb407272019-03-12 18:28:51 +00002506 windowCheckValue(pParse, regEnd, 1 + (pMWin->eType==TK_RANGE ? 3 : 0));
dan54975cd2019-03-07 20:47:46 +00002507 }
danb25a2142019-03-05 19:29:36 +00002508
dan0525b6f2019-03-18 21:19:40 +00002509 if( pMWin->eStart==pMWin->eEnd && regStart ){
danb25a2142019-03-05 19:29:36 +00002510 int op = ((pMWin->eStart==TK_FOLLOWING) ? OP_Ge : OP_Le);
2511 int addrGe = sqlite3VdbeAddOp3(v, op, regStart, 0, regEnd);
dan1d4b25f2019-03-19 16:49:15 +00002512 VdbeCoverage(v);
danc782a812019-03-15 20:46:19 +00002513 windowAggFinal(&s, 0);
dancc7a8502019-03-11 19:50:54 +00002514 sqlite3VdbeAddOp2(v, OP_Rewind, s.current.csr, 1);
dan1d4b25f2019-03-19 16:49:15 +00002515 VdbeCoverageNeverTaken(v);
danc782a812019-03-15 20:46:19 +00002516 windowReturnOneRow(&s);
dancc7a8502019-03-11 19:50:54 +00002517 sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr);
dan935d9d82019-03-12 15:21:51 +00002518 sqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd);
danb25a2142019-03-05 19:29:36 +00002519 sqlite3VdbeJumpHere(v, addrGe);
2520 }
dan72b9fdc2019-03-09 20:49:17 +00002521 if( pMWin->eStart==TK_FOLLOWING && pMWin->eType!=TK_RANGE && regEnd ){
dan54975cd2019-03-07 20:47:46 +00002522 assert( pMWin->eEnd==TK_FOLLOWING );
danb25a2142019-03-05 19:29:36 +00002523 sqlite3VdbeAddOp3(v, OP_Subtract, regStart, regEnd, regStart);
2524 }
2525
dan54975cd2019-03-07 20:47:46 +00002526 if( pMWin->eStart!=TK_UNBOUNDED ){
dan6c75b392019-03-08 20:02:52 +00002527 sqlite3VdbeAddOp2(v, OP_Rewind, s.start.csr, 1);
dan1d4b25f2019-03-19 16:49:15 +00002528 VdbeCoverageNeverTaken(v);
dan54975cd2019-03-07 20:47:46 +00002529 }
dan6c75b392019-03-08 20:02:52 +00002530 sqlite3VdbeAddOp2(v, OP_Rewind, s.current.csr, 1);
dan1d4b25f2019-03-19 16:49:15 +00002531 VdbeCoverageNeverTaken(v);
dan6c75b392019-03-08 20:02:52 +00002532 sqlite3VdbeAddOp2(v, OP_Rewind, s.end.csr, 1);
dan1d4b25f2019-03-19 16:49:15 +00002533 VdbeCoverageNeverTaken(v);
dan6c75b392019-03-08 20:02:52 +00002534 if( regPeer && pOrderBy ){
dancc7a8502019-03-11 19:50:54 +00002535 sqlite3VdbeAddOp3(v, OP_Copy, regNewPeer, regPeer, pOrderBy->nExpr-1);
dan6c75b392019-03-08 20:02:52 +00002536 sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.start.reg, pOrderBy->nExpr-1);
2537 sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.current.reg, pOrderBy->nExpr-1);
2538 sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.end.reg, pOrderBy->nExpr-1);
2539 }
danb25a2142019-03-05 19:29:36 +00002540
dan935d9d82019-03-12 15:21:51 +00002541 sqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd);
dan680f6e82019-03-04 21:07:11 +00002542
danbf845152019-03-16 10:15:24 +00002543 sqlite3VdbeJumpHere(v, addrNe);
dan6c75b392019-03-08 20:02:52 +00002544 if( regPeer ){
dan935d9d82019-03-12 15:21:51 +00002545 windowIfNewPeer(pParse, pOrderBy, regNewPeer, regPeer, lblWhereEnd);
dan6c75b392019-03-08 20:02:52 +00002546 }
danb25a2142019-03-05 19:29:36 +00002547 if( pMWin->eStart==TK_FOLLOWING ){
dan6c75b392019-03-08 20:02:52 +00002548 windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
dan54975cd2019-03-07 20:47:46 +00002549 if( pMWin->eEnd!=TK_UNBOUNDED ){
dan72b9fdc2019-03-09 20:49:17 +00002550 if( pMWin->eType==TK_RANGE ){
2551 int lbl = sqlite3VdbeMakeLabel(pParse);
2552 int addrNext = sqlite3VdbeCurrentAddr(v);
2553 windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl);
2554 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2555 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
2556 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNext);
2557 sqlite3VdbeResolveLabel(v, lbl);
2558 }else{
2559 windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 0);
2560 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2561 }
dan54975cd2019-03-07 20:47:46 +00002562 }
danb25a2142019-03-05 19:29:36 +00002563 }else
2564 if( pMWin->eEnd==TK_PRECEDING ){
dan6c75b392019-03-08 20:02:52 +00002565 windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0);
2566 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
2567 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
danb25a2142019-03-05 19:29:36 +00002568 }else{
danc8137502019-03-07 19:26:17 +00002569 int addr;
dan6c75b392019-03-08 20:02:52 +00002570 windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
dan54975cd2019-03-07 20:47:46 +00002571 if( pMWin->eEnd!=TK_UNBOUNDED ){
dan72b9fdc2019-03-09 20:49:17 +00002572 if( pMWin->eType==TK_RANGE ){
2573 int lbl;
2574 addr = sqlite3VdbeCurrentAddr(v);
2575 if( regEnd ){
2576 lbl = sqlite3VdbeMakeLabel(pParse);
2577 windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl);
2578 }
2579 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
2580 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2581 if( regEnd ){
2582 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
2583 sqlite3VdbeResolveLabel(v, lbl);
2584 }
2585 }else{
dan1d4b25f2019-03-19 16:49:15 +00002586 if( regEnd ){
2587 addr = sqlite3VdbeAddOp3(v, OP_IfPos, regEnd, 0, 1);
2588 VdbeCoverage(v);
2589 }
dan72b9fdc2019-03-09 20:49:17 +00002590 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
2591 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2592 if( regEnd ) sqlite3VdbeJumpHere(v, addr);
2593 }
dan54975cd2019-03-07 20:47:46 +00002594 }
danb25a2142019-03-05 19:29:36 +00002595 }
dan680f6e82019-03-04 21:07:11 +00002596
dan680f6e82019-03-04 21:07:11 +00002597 /* End of the main input loop */
dan935d9d82019-03-12 15:21:51 +00002598 sqlite3VdbeResolveLabel(v, lblWhereEnd);
dancc7a8502019-03-11 19:50:54 +00002599 sqlite3WhereEnd(pWInfo);
dan680f6e82019-03-04 21:07:11 +00002600
2601 /* Fall through */
dancc7a8502019-03-11 19:50:54 +00002602 if( pMWin->pPartition ){
dan680f6e82019-03-04 21:07:11 +00002603 addrInteger = sqlite3VdbeAddOp2(v, OP_Integer, 0, regFlushPart);
2604 sqlite3VdbeJumpHere(v, addrGosubFlush);
2605 }
2606
danc8137502019-03-07 19:26:17 +00002607 addrEmpty = sqlite3VdbeAddOp1(v, OP_Rewind, csrWrite);
dan1d4b25f2019-03-19 16:49:15 +00002608 VdbeCoverage(v);
dan00267b82019-03-06 21:04:11 +00002609 if( pMWin->eEnd==TK_PRECEDING ){
dan6c75b392019-03-08 20:02:52 +00002610 windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0);
2611 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
danc8137502019-03-07 19:26:17 +00002612 }else if( pMWin->eStart==TK_FOLLOWING ){
2613 int addrStart;
2614 int addrBreak1;
2615 int addrBreak2;
2616 int addrBreak3;
dan6c75b392019-03-08 20:02:52 +00002617 windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
dan72b9fdc2019-03-09 20:49:17 +00002618 if( pMWin->eType==TK_RANGE ){
2619 addrStart = sqlite3VdbeCurrentAddr(v);
2620 addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1);
2621 addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
2622 }else
dan54975cd2019-03-07 20:47:46 +00002623 if( pMWin->eEnd==TK_UNBOUNDED ){
2624 addrStart = sqlite3VdbeCurrentAddr(v);
dan6c75b392019-03-08 20:02:52 +00002625 addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regStart, 1);
2626 addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, 0, 1);
dan54975cd2019-03-07 20:47:46 +00002627 }else{
2628 assert( pMWin->eEnd==TK_FOLLOWING );
2629 addrStart = sqlite3VdbeCurrentAddr(v);
dan6c75b392019-03-08 20:02:52 +00002630 addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 1);
2631 addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1);
dan54975cd2019-03-07 20:47:46 +00002632 }
danc8137502019-03-07 19:26:17 +00002633 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
2634 sqlite3VdbeJumpHere(v, addrBreak2);
2635 addrStart = sqlite3VdbeCurrentAddr(v);
dan6c75b392019-03-08 20:02:52 +00002636 addrBreak3 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
danc8137502019-03-07 19:26:17 +00002637 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
2638 sqlite3VdbeJumpHere(v, addrBreak1);
2639 sqlite3VdbeJumpHere(v, addrBreak3);
danb25a2142019-03-05 19:29:36 +00002640 }else{
dan00267b82019-03-06 21:04:11 +00002641 int addrBreak;
danc8137502019-03-07 19:26:17 +00002642 int addrStart;
dan6c75b392019-03-08 20:02:52 +00002643 windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
danc8137502019-03-07 19:26:17 +00002644 addrStart = sqlite3VdbeCurrentAddr(v);
dan6c75b392019-03-08 20:02:52 +00002645 addrBreak = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
2646 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
dan00267b82019-03-06 21:04:11 +00002647 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
2648 sqlite3VdbeJumpHere(v, addrBreak);
danb25a2142019-03-05 19:29:36 +00002649 }
danc8137502019-03-07 19:26:17 +00002650 sqlite3VdbeJumpHere(v, addrEmpty);
2651
dan6c75b392019-03-08 20:02:52 +00002652 sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr);
dan680f6e82019-03-04 21:07:11 +00002653 if( pMWin->pPartition ){
dana0f6b832019-03-14 16:36:20 +00002654 if( pMWin->regStartRowid ){
2655 sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid);
2656 sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid);
2657 }
dan680f6e82019-03-04 21:07:11 +00002658 sqlite3VdbeChangeP1(v, addrInteger, sqlite3VdbeCurrentAddr(v));
2659 sqlite3VdbeAddOp1(v, OP_Return, regFlushPart);
2660 }
2661}
2662
dan67a9b8e2018-06-22 20:51:35 +00002663#endif /* SQLITE_OMIT_WINDOWFUNC */