blob: 4b5184d9187c35d3405e5c642743bc61841ebe37 [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 );
drhd4a591d2019-03-26 16:21:11 +0000335 UNUSED_PARAMETER(apArg);
dandfa552f2018-06-02 21:04:28 +0000336 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
drh5d6374f2018-07-10 23:31:17 +0000337 if( p ){
dancc7a8502019-03-11 19:50:54 +0000338 p->nTotal++;
dandfa552f2018-06-02 21:04:28 +0000339 }
340}
dancc7a8502019-03-11 19:50:54 +0000341static void percent_rankInvFunc(
342 sqlite3_context *pCtx,
343 int nArg,
344 sqlite3_value **apArg
345){
346 struct CallCount *p;
347 UNUSED_PARAMETER(nArg); assert( nArg==0 );
drhd4a591d2019-03-26 16:21:11 +0000348 UNUSED_PARAMETER(apArg);
dancc7a8502019-03-11 19:50:54 +0000349 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
350 p->nStep++;
351}
dandfa552f2018-06-02 21:04:28 +0000352static void percent_rankValueFunc(sqlite3_context *pCtx){
353 struct CallCount *p;
354 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
355 if( p ){
dancc7a8502019-03-11 19:50:54 +0000356 p->nValue = p->nStep;
dandfa552f2018-06-02 21:04:28 +0000357 if( p->nTotal>1 ){
dancc7a8502019-03-11 19:50:54 +0000358 double r = (double)p->nValue / (double)(p->nTotal-1);
dandfa552f2018-06-02 21:04:28 +0000359 sqlite3_result_double(pCtx, r);
360 }else{
danb7306f62018-06-21 19:20:39 +0000361 sqlite3_result_double(pCtx, 0.0);
dandfa552f2018-06-02 21:04:28 +0000362 }
dandfa552f2018-06-02 21:04:28 +0000363 }
364}
dancc7a8502019-03-11 19:50:54 +0000365#define percent_rankFinalizeFunc percent_rankValueFunc
dandfa552f2018-06-02 21:04:28 +0000366
dan9c277582018-06-20 09:23:49 +0000367/*
368** Implementation of built-in window function cume_dist(). Assumes that
369** the window frame has been set to:
370**
dancc7a8502019-03-11 19:50:54 +0000371** GROUPS BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING
dan9c277582018-06-20 09:23:49 +0000372*/
danf1abe362018-06-04 08:22:09 +0000373static void cume_distStepFunc(
374 sqlite3_context *pCtx,
375 int nArg,
376 sqlite3_value **apArg
377){
378 struct CallCount *p;
dancc7a8502019-03-11 19:50:54 +0000379 UNUSED_PARAMETER(nArg); assert( nArg==0 );
drhd4a591d2019-03-26 16:21:11 +0000380 UNUSED_PARAMETER(apArg);
danf1abe362018-06-04 08:22:09 +0000381 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
drh5d6374f2018-07-10 23:31:17 +0000382 if( p ){
dancc7a8502019-03-11 19:50:54 +0000383 p->nTotal++;
danf1abe362018-06-04 08:22:09 +0000384 }
385}
dancc7a8502019-03-11 19:50:54 +0000386static void cume_distInvFunc(
387 sqlite3_context *pCtx,
388 int nArg,
389 sqlite3_value **apArg
390){
391 struct CallCount *p;
392 UNUSED_PARAMETER(nArg); assert( nArg==0 );
drhd4a591d2019-03-26 16:21:11 +0000393 UNUSED_PARAMETER(apArg);
dancc7a8502019-03-11 19:50:54 +0000394 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
395 p->nStep++;
396}
danf1abe362018-06-04 08:22:09 +0000397static void cume_distValueFunc(sqlite3_context *pCtx){
398 struct CallCount *p;
dan0525b6f2019-03-18 21:19:40 +0000399 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, 0);
400 if( p ){
danf1abe362018-06-04 08:22:09 +0000401 double r = (double)(p->nStep) / (double)(p->nTotal);
402 sqlite3_result_double(pCtx, r);
403 }
404}
dancc7a8502019-03-11 19:50:54 +0000405#define cume_distFinalizeFunc cume_distValueFunc
danf1abe362018-06-04 08:22:09 +0000406
dan2a11bb22018-06-11 20:50:25 +0000407/*
408** Context object for ntile() window function.
409*/
dan6bc5c9e2018-06-04 18:55:11 +0000410struct NtileCtx {
411 i64 nTotal; /* Total rows in partition */
412 i64 nParam; /* Parameter passed to ntile(N) */
413 i64 iRow; /* Current row */
414};
415
416/*
417** Implementation of ntile(). This assumes that the window frame has
418** been coerced to:
419**
dancc7a8502019-03-11 19:50:54 +0000420** ROWS CURRENT ROW AND UNBOUNDED FOLLOWING
dan6bc5c9e2018-06-04 18:55:11 +0000421*/
422static void ntileStepFunc(
423 sqlite3_context *pCtx,
424 int nArg,
425 sqlite3_value **apArg
426){
427 struct NtileCtx *p;
dancc7a8502019-03-11 19:50:54 +0000428 assert( nArg==1 ); UNUSED_PARAMETER(nArg);
dan6bc5c9e2018-06-04 18:55:11 +0000429 p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
drh5d6374f2018-07-10 23:31:17 +0000430 if( p ){
dan6bc5c9e2018-06-04 18:55:11 +0000431 if( p->nTotal==0 ){
432 p->nParam = sqlite3_value_int64(apArg[0]);
dan6bc5c9e2018-06-04 18:55:11 +0000433 if( p->nParam<=0 ){
434 sqlite3_result_error(
435 pCtx, "argument of ntile must be a positive integer", -1
436 );
437 }
438 }
dancc7a8502019-03-11 19:50:54 +0000439 p->nTotal++;
dan6bc5c9e2018-06-04 18:55:11 +0000440 }
441}
dancc7a8502019-03-11 19:50:54 +0000442static void ntileInvFunc(
443 sqlite3_context *pCtx,
444 int nArg,
445 sqlite3_value **apArg
446){
447 struct NtileCtx *p;
448 assert( nArg==1 ); UNUSED_PARAMETER(nArg);
drhd4a591d2019-03-26 16:21:11 +0000449 UNUSED_PARAMETER(apArg);
dancc7a8502019-03-11 19:50:54 +0000450 p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
451 p->iRow++;
452}
dan6bc5c9e2018-06-04 18:55:11 +0000453static void ntileValueFunc(sqlite3_context *pCtx){
454 struct NtileCtx *p;
455 p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
456 if( p && p->nParam>0 ){
457 int nSize = (p->nTotal / p->nParam);
458 if( nSize==0 ){
dancc7a8502019-03-11 19:50:54 +0000459 sqlite3_result_int64(pCtx, p->iRow+1);
dan6bc5c9e2018-06-04 18:55:11 +0000460 }else{
461 i64 nLarge = p->nTotal - p->nParam*nSize;
462 i64 iSmall = nLarge*(nSize+1);
dancc7a8502019-03-11 19:50:54 +0000463 i64 iRow = p->iRow;
dan6bc5c9e2018-06-04 18:55:11 +0000464
465 assert( (nLarge*(nSize+1) + (p->nParam-nLarge)*nSize)==p->nTotal );
466
467 if( iRow<iSmall ){
468 sqlite3_result_int64(pCtx, 1 + iRow/(nSize+1));
469 }else{
470 sqlite3_result_int64(pCtx, 1 + nLarge + (iRow-iSmall)/nSize);
471 }
472 }
473 }
474}
dancc7a8502019-03-11 19:50:54 +0000475#define ntileFinalizeFunc ntileValueFunc
dan6bc5c9e2018-06-04 18:55:11 +0000476
dan2a11bb22018-06-11 20:50:25 +0000477/*
478** Context object for last_value() window function.
479*/
dan1c5ed622018-06-05 16:16:17 +0000480struct LastValueCtx {
481 sqlite3_value *pVal;
482 int nVal;
483};
484
485/*
486** Implementation of last_value().
487*/
488static void last_valueStepFunc(
489 sqlite3_context *pCtx,
490 int nArg,
491 sqlite3_value **apArg
492){
493 struct LastValueCtx *p;
drhc7bf5712018-07-09 22:49:01 +0000494 UNUSED_PARAMETER(nArg);
dan9c277582018-06-20 09:23:49 +0000495 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
dan1c5ed622018-06-05 16:16:17 +0000496 if( p ){
497 sqlite3_value_free(p->pVal);
498 p->pVal = sqlite3_value_dup(apArg[0]);
dan6fde1792018-06-15 19:01:35 +0000499 if( p->pVal==0 ){
500 sqlite3_result_error_nomem(pCtx);
501 }else{
502 p->nVal++;
503 }
dan1c5ed622018-06-05 16:16:17 +0000504 }
505}
dan2a11bb22018-06-11 20:50:25 +0000506static void last_valueInvFunc(
dan1c5ed622018-06-05 16:16:17 +0000507 sqlite3_context *pCtx,
508 int nArg,
509 sqlite3_value **apArg
510){
511 struct LastValueCtx *p;
drhc7bf5712018-07-09 22:49:01 +0000512 UNUSED_PARAMETER(nArg);
513 UNUSED_PARAMETER(apArg);
dan9c277582018-06-20 09:23:49 +0000514 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
515 if( ALWAYS(p) ){
dan1c5ed622018-06-05 16:16:17 +0000516 p->nVal--;
517 if( p->nVal==0 ){
518 sqlite3_value_free(p->pVal);
519 p->pVal = 0;
520 }
521 }
522}
523static void last_valueValueFunc(sqlite3_context *pCtx){
524 struct LastValueCtx *p;
dan0525b6f2019-03-18 21:19:40 +0000525 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, 0);
dan1c5ed622018-06-05 16:16:17 +0000526 if( p && p->pVal ){
527 sqlite3_result_value(pCtx, p->pVal);
528 }
529}
530static void last_valueFinalizeFunc(sqlite3_context *pCtx){
531 struct LastValueCtx *p;
dan9c277582018-06-20 09:23:49 +0000532 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
dan1c5ed622018-06-05 16:16:17 +0000533 if( p && p->pVal ){
534 sqlite3_result_value(pCtx, p->pVal);
535 sqlite3_value_free(p->pVal);
536 p->pVal = 0;
537 }
538}
539
dan2a11bb22018-06-11 20:50:25 +0000540/*
drh19dc4d42018-07-08 01:02:26 +0000541** Static names for the built-in window function names. These static
542** names are used, rather than string literals, so that FuncDef objects
543** can be associated with a particular window function by direct
544** comparison of the zName pointer. Example:
545**
546** if( pFuncDef->zName==row_valueName ){ ... }
dan2a11bb22018-06-11 20:50:25 +0000547*/
drh19dc4d42018-07-08 01:02:26 +0000548static const char row_numberName[] = "row_number";
549static const char dense_rankName[] = "dense_rank";
550static const char rankName[] = "rank";
551static const char percent_rankName[] = "percent_rank";
552static const char cume_distName[] = "cume_dist";
553static const char ntileName[] = "ntile";
554static const char last_valueName[] = "last_value";
555static const char nth_valueName[] = "nth_value";
556static const char first_valueName[] = "first_value";
557static const char leadName[] = "lead";
558static const char lagName[] = "lag";
danfe4e25a2018-06-07 20:08:59 +0000559
drh19dc4d42018-07-08 01:02:26 +0000560/*
561** No-op implementations of xStep() and xFinalize(). Used as place-holders
562** for built-in window functions that never call those interfaces.
563**
564** The noopValueFunc() is called but is expected to do nothing. The
565** noopStepFunc() is never called, and so it is marked with NO_TEST to
566** let the test coverage routine know not to expect this function to be
567** invoked.
568*/
569static void noopStepFunc( /*NO_TEST*/
570 sqlite3_context *p, /*NO_TEST*/
571 int n, /*NO_TEST*/
572 sqlite3_value **a /*NO_TEST*/
573){ /*NO_TEST*/
drhc7bf5712018-07-09 22:49:01 +0000574 UNUSED_PARAMETER(p); /*NO_TEST*/
575 UNUSED_PARAMETER(n); /*NO_TEST*/
576 UNUSED_PARAMETER(a); /*NO_TEST*/
drh19dc4d42018-07-08 01:02:26 +0000577 assert(0); /*NO_TEST*/
578} /*NO_TEST*/
drhc7bf5712018-07-09 22:49:01 +0000579static void noopValueFunc(sqlite3_context *p){ UNUSED_PARAMETER(p); /*no-op*/ }
dandfa552f2018-06-02 21:04:28 +0000580
drh19dc4d42018-07-08 01:02:26 +0000581/* Window functions that use all window interfaces: xStep, xFinal,
582** xValue, and xInverse */
583#define WINDOWFUNCALL(name,nArg,extra) { \
dan1c5ed622018-06-05 16:16:17 +0000584 nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
585 name ## StepFunc, name ## FinalizeFunc, name ## ValueFunc, \
drhc7bf5712018-07-09 22:49:01 +0000586 name ## InvFunc, name ## Name, {0} \
dan1c5ed622018-06-05 16:16:17 +0000587}
588
drh19dc4d42018-07-08 01:02:26 +0000589/* Window functions that are implemented using bytecode and thus have
590** no-op routines for their methods */
591#define WINDOWFUNCNOOP(name,nArg,extra) { \
592 nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
593 noopStepFunc, noopValueFunc, noopValueFunc, \
drhc7bf5712018-07-09 22:49:01 +0000594 noopStepFunc, name ## Name, {0} \
drh19dc4d42018-07-08 01:02:26 +0000595}
596
597/* Window functions that use all window interfaces: xStep, the
598** same routine for xFinalize and xValue and which never call
599** xInverse. */
600#define WINDOWFUNCX(name,nArg,extra) { \
601 nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
602 name ## StepFunc, name ## ValueFunc, name ## ValueFunc, \
drhc7bf5712018-07-09 22:49:01 +0000603 noopStepFunc, name ## Name, {0} \
drh19dc4d42018-07-08 01:02:26 +0000604}
605
606
dandfa552f2018-06-02 21:04:28 +0000607/*
608** Register those built-in window functions that are not also aggregates.
609*/
610void sqlite3WindowFunctions(void){
611 static FuncDef aWindowFuncs[] = {
drh19dc4d42018-07-08 01:02:26 +0000612 WINDOWFUNCX(row_number, 0, 0),
613 WINDOWFUNCX(dense_rank, 0, 0),
614 WINDOWFUNCX(rank, 0, 0),
dancc7a8502019-03-11 19:50:54 +0000615 WINDOWFUNCALL(percent_rank, 0, 0),
616 WINDOWFUNCALL(cume_dist, 0, 0),
617 WINDOWFUNCALL(ntile, 1, 0),
drh19dc4d42018-07-08 01:02:26 +0000618 WINDOWFUNCALL(last_value, 1, 0),
dana0f6b832019-03-14 16:36:20 +0000619 WINDOWFUNCALL(nth_value, 2, 0),
danc782a812019-03-15 20:46:19 +0000620 WINDOWFUNCALL(first_value, 1, 0),
drh19dc4d42018-07-08 01:02:26 +0000621 WINDOWFUNCNOOP(lead, 1, 0),
622 WINDOWFUNCNOOP(lead, 2, 0),
623 WINDOWFUNCNOOP(lead, 3, 0),
624 WINDOWFUNCNOOP(lag, 1, 0),
625 WINDOWFUNCNOOP(lag, 2, 0),
626 WINDOWFUNCNOOP(lag, 3, 0),
dandfa552f2018-06-02 21:04:28 +0000627 };
628 sqlite3InsertBuiltinFuncs(aWindowFuncs, ArraySize(aWindowFuncs));
629}
630
dane7c9ca42019-02-16 17:27:51 +0000631static Window *windowFind(Parse *pParse, Window *pList, const char *zName){
632 Window *p;
633 for(p=pList; p; p=p->pNextWin){
634 if( sqlite3StrICmp(p->zName, zName)==0 ) break;
635 }
636 if( p==0 ){
637 sqlite3ErrorMsg(pParse, "no such window: %s", zName);
638 }
639 return p;
640}
641
danc0bb4452018-06-12 20:53:38 +0000642/*
643** This function is called immediately after resolving the function name
644** for a window function within a SELECT statement. Argument pList is a
645** linked list of WINDOW definitions for the current SELECT statement.
646** Argument pFunc is the function definition just resolved and pWin
647** is the Window object representing the associated OVER clause. This
648** function updates the contents of pWin as follows:
649**
650** * If the OVER clause refered to a named window (as in "max(x) OVER win"),
651** search list pList for a matching WINDOW definition, and update pWin
652** accordingly. If no such WINDOW clause can be found, leave an error
653** in pParse.
654**
655** * If the function is a built-in window function that requires the
656** window to be coerced (see "BUILT-IN WINDOW FUNCTIONS" at the top
657** of this file), pWin is updated here.
658*/
dane3bf6322018-06-08 20:58:27 +0000659void sqlite3WindowUpdate(
660 Parse *pParse,
danc0bb4452018-06-12 20:53:38 +0000661 Window *pList, /* List of named windows for this SELECT */
662 Window *pWin, /* Window frame to update */
663 FuncDef *pFunc /* Window function definition */
dane3bf6322018-06-08 20:58:27 +0000664){
drhfc15f4c2019-03-28 13:03:41 +0000665 if( pWin->zName && pWin->eFrmType==0 ){
dane7c9ca42019-02-16 17:27:51 +0000666 Window *p = windowFind(pParse, pList, pWin->zName);
667 if( p==0 ) return;
dane3bf6322018-06-08 20:58:27 +0000668 pWin->pPartition = sqlite3ExprListDup(pParse->db, p->pPartition, 0);
669 pWin->pOrderBy = sqlite3ExprListDup(pParse->db, p->pOrderBy, 0);
670 pWin->pStart = sqlite3ExprDup(pParse->db, p->pStart, 0);
671 pWin->pEnd = sqlite3ExprDup(pParse->db, p->pEnd, 0);
672 pWin->eStart = p->eStart;
673 pWin->eEnd = p->eEnd;
drhfc15f4c2019-03-28 13:03:41 +0000674 pWin->eFrmType = p->eFrmType;
danc782a812019-03-15 20:46:19 +0000675 pWin->eExclude = p->eExclude;
dane7c9ca42019-02-16 17:27:51 +0000676 }else{
677 sqlite3WindowChain(pParse, pWin, pList);
dane3bf6322018-06-08 20:58:27 +0000678 }
drhfc15f4c2019-03-28 13:03:41 +0000679 if( (pWin->eFrmType==TK_RANGE)
dan72b9fdc2019-03-09 20:49:17 +0000680 && (pWin->pStart || pWin->pEnd)
681 && (pWin->pOrderBy==0 || pWin->pOrderBy->nExpr!=1)
682 ){
683 sqlite3ErrorMsg(pParse,
684 "RANGE with offset PRECEDING/FOLLOWING requires one ORDER BY expression"
685 );
686 }else
dandfa552f2018-06-02 21:04:28 +0000687 if( pFunc->funcFlags & SQLITE_FUNC_WINDOW ){
688 sqlite3 *db = pParse->db;
dan8b985602018-06-09 17:43:45 +0000689 if( pWin->pFilter ){
690 sqlite3ErrorMsg(pParse,
691 "FILTER clause may only be used with aggregate window functions"
692 );
dancc7a8502019-03-11 19:50:54 +0000693 }else{
694 struct WindowUpdate {
695 const char *zFunc;
drhfc15f4c2019-03-28 13:03:41 +0000696 int eFrmType;
dancc7a8502019-03-11 19:50:54 +0000697 int eStart;
698 int eEnd;
699 } aUp[] = {
700 { row_numberName, TK_ROWS, TK_UNBOUNDED, TK_CURRENT },
701 { dense_rankName, TK_RANGE, TK_UNBOUNDED, TK_CURRENT },
702 { rankName, TK_RANGE, TK_UNBOUNDED, TK_CURRENT },
703 { percent_rankName, TK_GROUPS, TK_CURRENT, TK_UNBOUNDED },
704 { cume_distName, TK_GROUPS, TK_FOLLOWING, TK_UNBOUNDED },
705 { ntileName, TK_ROWS, TK_CURRENT, TK_UNBOUNDED },
706 { leadName, TK_ROWS, TK_UNBOUNDED, TK_UNBOUNDED },
danb560a712019-03-13 15:29:14 +0000707 { lagName, TK_ROWS, TK_UNBOUNDED, TK_CURRENT },
dancc7a8502019-03-11 19:50:54 +0000708 };
709 int i;
710 for(i=0; i<ArraySize(aUp); i++){
711 if( pFunc->zName==aUp[i].zFunc ){
712 sqlite3ExprDelete(db, pWin->pStart);
713 sqlite3ExprDelete(db, pWin->pEnd);
714 pWin->pEnd = pWin->pStart = 0;
drhfc15f4c2019-03-28 13:03:41 +0000715 pWin->eFrmType = aUp[i].eFrmType;
dancc7a8502019-03-11 19:50:54 +0000716 pWin->eStart = aUp[i].eStart;
717 pWin->eEnd = aUp[i].eEnd;
dana0f6b832019-03-14 16:36:20 +0000718 pWin->eExclude = 0;
dancc7a8502019-03-11 19:50:54 +0000719 if( pWin->eStart==TK_FOLLOWING ){
720 pWin->pStart = sqlite3Expr(db, TK_INTEGER, "1");
721 }
722 break;
723 }
724 }
dandfa552f2018-06-02 21:04:28 +0000725 }
726 }
dan2a11bb22018-06-11 20:50:25 +0000727 pWin->pFunc = pFunc;
dandfa552f2018-06-02 21:04:28 +0000728}
729
danc0bb4452018-06-12 20:53:38 +0000730/*
731** Context object passed through sqlite3WalkExprList() to
732** selectWindowRewriteExprCb() by selectWindowRewriteEList().
733*/
dandfa552f2018-06-02 21:04:28 +0000734typedef struct WindowRewrite WindowRewrite;
735struct WindowRewrite {
736 Window *pWin;
danb556f262018-07-10 17:26:12 +0000737 SrcList *pSrc;
dandfa552f2018-06-02 21:04:28 +0000738 ExprList *pSub;
danb556f262018-07-10 17:26:12 +0000739 Select *pSubSelect; /* Current sub-select, if any */
dandfa552f2018-06-02 21:04:28 +0000740};
741
danc0bb4452018-06-12 20:53:38 +0000742/*
743** Callback function used by selectWindowRewriteEList(). If necessary,
744** this function appends to the output expression-list and updates
745** expression (*ppExpr) in place.
746*/
dandfa552f2018-06-02 21:04:28 +0000747static int selectWindowRewriteExprCb(Walker *pWalker, Expr *pExpr){
748 struct WindowRewrite *p = pWalker->u.pRewrite;
749 Parse *pParse = pWalker->pParse;
750
danb556f262018-07-10 17:26:12 +0000751 /* If this function is being called from within a scalar sub-select
752 ** that used by the SELECT statement being processed, only process
753 ** TK_COLUMN expressions that refer to it (the outer SELECT). Do
754 ** not process aggregates or window functions at all, as they belong
755 ** to the scalar sub-select. */
756 if( p->pSubSelect ){
757 if( pExpr->op!=TK_COLUMN ){
758 return WRC_Continue;
759 }else{
760 int nSrc = p->pSrc->nSrc;
761 int i;
762 for(i=0; i<nSrc; i++){
763 if( pExpr->iTable==p->pSrc->a[i].iCursor ) break;
764 }
765 if( i==nSrc ) return WRC_Continue;
766 }
767 }
768
dandfa552f2018-06-02 21:04:28 +0000769 switch( pExpr->op ){
770
771 case TK_FUNCTION:
drheda079c2018-09-20 19:02:15 +0000772 if( !ExprHasProperty(pExpr, EP_WinFunc) ){
dandfa552f2018-06-02 21:04:28 +0000773 break;
774 }else{
775 Window *pWin;
776 for(pWin=p->pWin; pWin; pWin=pWin->pNextWin){
drheda079c2018-09-20 19:02:15 +0000777 if( pExpr->y.pWin==pWin ){
dan2a11bb22018-06-11 20:50:25 +0000778 assert( pWin->pOwner==pExpr );
dandfa552f2018-06-02 21:04:28 +0000779 return WRC_Prune;
780 }
781 }
782 }
783 /* Fall through. */
784
dan73925692018-06-12 18:40:17 +0000785 case TK_AGG_FUNCTION:
dandfa552f2018-06-02 21:04:28 +0000786 case TK_COLUMN: {
787 Expr *pDup = sqlite3ExprDup(pParse->db, pExpr, 0);
788 p->pSub = sqlite3ExprListAppend(pParse, p->pSub, pDup);
789 if( p->pSub ){
790 assert( ExprHasProperty(pExpr, EP_Static)==0 );
791 ExprSetProperty(pExpr, EP_Static);
792 sqlite3ExprDelete(pParse->db, pExpr);
793 ExprClearProperty(pExpr, EP_Static);
794 memset(pExpr, 0, sizeof(Expr));
795
796 pExpr->op = TK_COLUMN;
797 pExpr->iColumn = p->pSub->nExpr-1;
798 pExpr->iTable = p->pWin->iEphCsr;
799 }
800
801 break;
802 }
803
804 default: /* no-op */
805 break;
806 }
807
808 return WRC_Continue;
809}
danc0bb4452018-06-12 20:53:38 +0000810static int selectWindowRewriteSelectCb(Walker *pWalker, Select *pSelect){
danb556f262018-07-10 17:26:12 +0000811 struct WindowRewrite *p = pWalker->u.pRewrite;
812 Select *pSave = p->pSubSelect;
813 if( pSave==pSelect ){
814 return WRC_Continue;
815 }else{
816 p->pSubSelect = pSelect;
817 sqlite3WalkSelect(pWalker, pSelect);
818 p->pSubSelect = pSave;
819 }
danc0bb4452018-06-12 20:53:38 +0000820 return WRC_Prune;
821}
dandfa552f2018-06-02 21:04:28 +0000822
danc0bb4452018-06-12 20:53:38 +0000823
824/*
825** Iterate through each expression in expression-list pEList. For each:
826**
827** * TK_COLUMN,
828** * aggregate function, or
829** * window function with a Window object that is not a member of the
danb556f262018-07-10 17:26:12 +0000830** Window list passed as the second argument (pWin).
danc0bb4452018-06-12 20:53:38 +0000831**
832** Append the node to output expression-list (*ppSub). And replace it
833** with a TK_COLUMN that reads the (N-1)th element of table
834** pWin->iEphCsr, where N is the number of elements in (*ppSub) after
835** appending the new one.
836*/
dan13b08bb2018-06-15 20:46:12 +0000837static void selectWindowRewriteEList(
dandfa552f2018-06-02 21:04:28 +0000838 Parse *pParse,
839 Window *pWin,
danb556f262018-07-10 17:26:12 +0000840 SrcList *pSrc,
dandfa552f2018-06-02 21:04:28 +0000841 ExprList *pEList, /* Rewrite expressions in this list */
842 ExprList **ppSub /* IN/OUT: Sub-select expression-list */
843){
844 Walker sWalker;
845 WindowRewrite sRewrite;
dandfa552f2018-06-02 21:04:28 +0000846
847 memset(&sWalker, 0, sizeof(Walker));
848 memset(&sRewrite, 0, sizeof(WindowRewrite));
849
850 sRewrite.pSub = *ppSub;
851 sRewrite.pWin = pWin;
danb556f262018-07-10 17:26:12 +0000852 sRewrite.pSrc = pSrc;
dandfa552f2018-06-02 21:04:28 +0000853
854 sWalker.pParse = pParse;
855 sWalker.xExprCallback = selectWindowRewriteExprCb;
856 sWalker.xSelectCallback = selectWindowRewriteSelectCb;
857 sWalker.u.pRewrite = &sRewrite;
858
dan13b08bb2018-06-15 20:46:12 +0000859 (void)sqlite3WalkExprList(&sWalker, pEList);
dandfa552f2018-06-02 21:04:28 +0000860
861 *ppSub = sRewrite.pSub;
dandfa552f2018-06-02 21:04:28 +0000862}
863
danc0bb4452018-06-12 20:53:38 +0000864/*
865** Append a copy of each expression in expression-list pAppend to
866** expression list pList. Return a pointer to the result list.
867*/
dandfa552f2018-06-02 21:04:28 +0000868static ExprList *exprListAppendList(
869 Parse *pParse, /* Parsing context */
870 ExprList *pList, /* List to which to append. Might be NULL */
871 ExprList *pAppend /* List of values to append. Might be NULL */
872){
873 if( pAppend ){
874 int i;
875 int nInit = pList ? pList->nExpr : 0;
876 for(i=0; i<pAppend->nExpr; i++){
877 Expr *pDup = sqlite3ExprDup(pParse->db, pAppend->a[i].pExpr, 0);
878 pList = sqlite3ExprListAppend(pParse, pList, pDup);
879 if( pList ) pList->a[nInit+i].sortOrder = pAppend->a[i].sortOrder;
880 }
881 }
882 return pList;
883}
884
885/*
886** If the SELECT statement passed as the second argument does not invoke
887** any SQL window functions, this function is a no-op. Otherwise, it
888** rewrites the SELECT statement so that window function xStep functions
danc0bb4452018-06-12 20:53:38 +0000889** are invoked in the correct order as described under "SELECT REWRITING"
890** at the top of this file.
dandfa552f2018-06-02 21:04:28 +0000891*/
892int sqlite3WindowRewrite(Parse *pParse, Select *p){
893 int rc = SQLITE_OK;
dan0f5f5402018-10-23 13:48:19 +0000894 if( p->pWin && p->pPrior==0 ){
dandfa552f2018-06-02 21:04:28 +0000895 Vdbe *v = sqlite3GetVdbe(pParse);
dandfa552f2018-06-02 21:04:28 +0000896 sqlite3 *db = pParse->db;
897 Select *pSub = 0; /* The subquery */
898 SrcList *pSrc = p->pSrc;
899 Expr *pWhere = p->pWhere;
900 ExprList *pGroupBy = p->pGroupBy;
901 Expr *pHaving = p->pHaving;
902 ExprList *pSort = 0;
903
904 ExprList *pSublist = 0; /* Expression list for sub-query */
905 Window *pMWin = p->pWin; /* Master window object */
906 Window *pWin; /* Window object iterator */
907
908 p->pSrc = 0;
909 p->pWhere = 0;
910 p->pGroupBy = 0;
911 p->pHaving = 0;
912
danf02cdd32018-06-27 19:48:50 +0000913 /* Create the ORDER BY clause for the sub-select. This is the concatenation
914 ** of the window PARTITION and ORDER BY clauses. Then, if this makes it
915 ** redundant, remove the ORDER BY from the parent SELECT. */
916 pSort = sqlite3ExprListDup(db, pMWin->pPartition, 0);
917 pSort = exprListAppendList(pParse, pSort, pMWin->pOrderBy);
918 if( pSort && p->pOrderBy ){
919 if( sqlite3ExprListCompare(pSort, p->pOrderBy, -1)==0 ){
920 sqlite3ExprListDelete(db, p->pOrderBy);
921 p->pOrderBy = 0;
922 }
923 }
924
dandfa552f2018-06-02 21:04:28 +0000925 /* Assign a cursor number for the ephemeral table used to buffer rows.
926 ** The OpenEphemeral instruction is coded later, after it is known how
927 ** many columns the table will have. */
928 pMWin->iEphCsr = pParse->nTab++;
dan680f6e82019-03-04 21:07:11 +0000929 pParse->nTab += 3;
dandfa552f2018-06-02 21:04:28 +0000930
danb556f262018-07-10 17:26:12 +0000931 selectWindowRewriteEList(pParse, pMWin, pSrc, p->pEList, &pSublist);
932 selectWindowRewriteEList(pParse, pMWin, pSrc, p->pOrderBy, &pSublist);
dandfa552f2018-06-02 21:04:28 +0000933 pMWin->nBufferCol = (pSublist ? pSublist->nExpr : 0);
934
danf02cdd32018-06-27 19:48:50 +0000935 /* Append the PARTITION BY and ORDER BY expressions to the to the
936 ** sub-select expression list. They are required to figure out where
937 ** boundaries for partitions and sets of peer rows lie. */
938 pSublist = exprListAppendList(pParse, pSublist, pMWin->pPartition);
939 pSublist = exprListAppendList(pParse, pSublist, pMWin->pOrderBy);
dandfa552f2018-06-02 21:04:28 +0000940
941 /* Append the arguments passed to each window function to the
942 ** sub-select expression list. Also allocate two registers for each
943 ** window function - one for the accumulator, another for interim
944 ** results. */
945 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
946 pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);
947 pSublist = exprListAppendList(pParse, pSublist, pWin->pOwner->x.pList);
dan8b985602018-06-09 17:43:45 +0000948 if( pWin->pFilter ){
949 Expr *pFilter = sqlite3ExprDup(db, pWin->pFilter, 0);
950 pSublist = sqlite3ExprListAppend(pParse, pSublist, pFilter);
951 }
dandfa552f2018-06-02 21:04:28 +0000952 pWin->regAccum = ++pParse->nMem;
953 pWin->regResult = ++pParse->nMem;
954 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
955 }
956
dan9c277582018-06-20 09:23:49 +0000957 /* If there is no ORDER BY or PARTITION BY clause, and the window
958 ** function accepts zero arguments, and there are no other columns
959 ** selected (e.g. "SELECT row_number() OVER () FROM t1"), it is possible
960 ** that pSublist is still NULL here. Add a constant expression here to
961 ** keep everything legal in this case.
962 */
963 if( pSublist==0 ){
964 pSublist = sqlite3ExprListAppend(pParse, 0,
965 sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0)
966 );
967 }
968
dandfa552f2018-06-02 21:04:28 +0000969 pSub = sqlite3SelectNew(
970 pParse, pSublist, pSrc, pWhere, pGroupBy, pHaving, pSort, 0, 0
971 );
drh29c992c2019-01-17 15:40:41 +0000972 p->pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
dandfa552f2018-06-02 21:04:28 +0000973 if( p->pSrc ){
dandfa552f2018-06-02 21:04:28 +0000974 p->pSrc->a[0].pSelect = pSub;
975 sqlite3SrcListAssignCursors(pParse, p->pSrc);
976 if( sqlite3ExpandSubquery(pParse, &p->pSrc->a[0]) ){
977 rc = SQLITE_NOMEM;
978 }else{
979 pSub->selFlags |= SF_Expanded;
dan73925692018-06-12 18:40:17 +0000980 p->selFlags &= ~SF_Aggregate;
981 sqlite3SelectPrep(pParse, pSub, 0);
dandfa552f2018-06-02 21:04:28 +0000982 }
dandfa552f2018-06-02 21:04:28 +0000983
dan6fde1792018-06-15 19:01:35 +0000984 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pMWin->iEphCsr, pSublist->nExpr);
dan680f6e82019-03-04 21:07:11 +0000985 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+1, pMWin->iEphCsr);
986 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+2, pMWin->iEphCsr);
987 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+3, pMWin->iEphCsr);
dan6fde1792018-06-15 19:01:35 +0000988 }else{
989 sqlite3SelectDelete(db, pSub);
990 }
991 if( db->mallocFailed ) rc = SQLITE_NOMEM;
dandfa552f2018-06-02 21:04:28 +0000992 }
993
994 return rc;
995}
996
danc0bb4452018-06-12 20:53:38 +0000997/*
998** Free the Window object passed as the second argument.
999*/
dan86fb6e12018-05-16 20:58:07 +00001000void sqlite3WindowDelete(sqlite3 *db, Window *p){
1001 if( p ){
1002 sqlite3ExprDelete(db, p->pFilter);
1003 sqlite3ExprListDelete(db, p->pPartition);
1004 sqlite3ExprListDelete(db, p->pOrderBy);
1005 sqlite3ExprDelete(db, p->pEnd);
1006 sqlite3ExprDelete(db, p->pStart);
dane3bf6322018-06-08 20:58:27 +00001007 sqlite3DbFree(db, p->zName);
dane7c9ca42019-02-16 17:27:51 +00001008 sqlite3DbFree(db, p->zBase);
dan86fb6e12018-05-16 20:58:07 +00001009 sqlite3DbFree(db, p);
1010 }
1011}
1012
danc0bb4452018-06-12 20:53:38 +00001013/*
1014** Free the linked list of Window objects starting at the second argument.
1015*/
dane3bf6322018-06-08 20:58:27 +00001016void sqlite3WindowListDelete(sqlite3 *db, Window *p){
1017 while( p ){
1018 Window *pNext = p->pNextWin;
1019 sqlite3WindowDelete(db, p);
1020 p = pNext;
1021 }
1022}
1023
danc0bb4452018-06-12 20:53:38 +00001024/*
drhe4984a22018-07-06 17:19:20 +00001025** The argument expression is an PRECEDING or FOLLOWING offset. The
1026** value should be a non-negative integer. If the value is not a
1027** constant, change it to NULL. The fact that it is then a non-negative
1028** integer will be caught later. But it is important not to leave
1029** variable values in the expression tree.
1030*/
1031static Expr *sqlite3WindowOffsetExpr(Parse *pParse, Expr *pExpr){
1032 if( 0==sqlite3ExprIsConstant(pExpr) ){
danfb8ac322019-01-16 12:05:22 +00001033 if( IN_RENAME_OBJECT ) sqlite3RenameExprUnmap(pParse, pExpr);
drhe4984a22018-07-06 17:19:20 +00001034 sqlite3ExprDelete(pParse->db, pExpr);
1035 pExpr = sqlite3ExprAlloc(pParse->db, TK_NULL, 0, 0);
1036 }
1037 return pExpr;
1038}
1039
1040/*
1041** Allocate and return a new Window object describing a Window Definition.
danc0bb4452018-06-12 20:53:38 +00001042*/
dan86fb6e12018-05-16 20:58:07 +00001043Window *sqlite3WindowAlloc(
drhe4984a22018-07-06 17:19:20 +00001044 Parse *pParse, /* Parsing context */
drhfc15f4c2019-03-28 13:03:41 +00001045 int eType, /* Frame type. TK_RANGE, TK_ROWS, TK_GROUPS, or 0 */
drhe4984a22018-07-06 17:19:20 +00001046 int eStart, /* Start type: CURRENT, PRECEDING, FOLLOWING, UNBOUNDED */
1047 Expr *pStart, /* Start window size if TK_PRECEDING or FOLLOWING */
1048 int eEnd, /* End type: CURRENT, FOLLOWING, TK_UNBOUNDED, PRECEDING */
dand35300f2019-03-14 20:53:21 +00001049 Expr *pEnd, /* End window size if TK_FOLLOWING or PRECEDING */
1050 u8 eExclude /* EXCLUDE clause */
dan86fb6e12018-05-16 20:58:07 +00001051){
dan7a606e12018-07-05 18:34:53 +00001052 Window *pWin = 0;
dane7c9ca42019-02-16 17:27:51 +00001053 int bImplicitFrame = 0;
dan7a606e12018-07-05 18:34:53 +00001054
drhe4984a22018-07-06 17:19:20 +00001055 /* Parser assures the following: */
dan6c75b392019-03-08 20:02:52 +00001056 assert( eType==0 || eType==TK_RANGE || eType==TK_ROWS || eType==TK_GROUPS );
drhe4984a22018-07-06 17:19:20 +00001057 assert( eStart==TK_CURRENT || eStart==TK_PRECEDING
1058 || eStart==TK_UNBOUNDED || eStart==TK_FOLLOWING );
1059 assert( eEnd==TK_CURRENT || eEnd==TK_FOLLOWING
1060 || eEnd==TK_UNBOUNDED || eEnd==TK_PRECEDING );
1061 assert( (eStart==TK_PRECEDING || eStart==TK_FOLLOWING)==(pStart!=0) );
1062 assert( (eEnd==TK_FOLLOWING || eEnd==TK_PRECEDING)==(pEnd!=0) );
1063
dane7c9ca42019-02-16 17:27:51 +00001064 if( eType==0 ){
1065 bImplicitFrame = 1;
1066 eType = TK_RANGE;
1067 }
drhe4984a22018-07-06 17:19:20 +00001068
drhe4984a22018-07-06 17:19:20 +00001069 /* Additionally, the
dan5d764ac2018-07-06 14:15:49 +00001070 ** starting boundary type may not occur earlier in the following list than
1071 ** the ending boundary type:
1072 **
1073 ** UNBOUNDED PRECEDING
1074 ** <expr> PRECEDING
1075 ** CURRENT ROW
1076 ** <expr> FOLLOWING
1077 ** UNBOUNDED FOLLOWING
1078 **
1079 ** The parser ensures that "UNBOUNDED PRECEDING" cannot be used as an ending
1080 ** boundary, and than "UNBOUNDED FOLLOWING" cannot be used as a starting
1081 ** frame boundary.
1082 */
drhe4984a22018-07-06 17:19:20 +00001083 if( (eStart==TK_CURRENT && eEnd==TK_PRECEDING)
dan5d764ac2018-07-06 14:15:49 +00001084 || (eStart==TK_FOLLOWING && (eEnd==TK_PRECEDING || eEnd==TK_CURRENT))
1085 ){
dan72b9fdc2019-03-09 20:49:17 +00001086 sqlite3ErrorMsg(pParse, "unsupported frame specification");
drhe4984a22018-07-06 17:19:20 +00001087 goto windowAllocErr;
dan7a606e12018-07-05 18:34:53 +00001088 }
dan86fb6e12018-05-16 20:58:07 +00001089
drhe4984a22018-07-06 17:19:20 +00001090 pWin = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
1091 if( pWin==0 ) goto windowAllocErr;
drhfc15f4c2019-03-28 13:03:41 +00001092 pWin->eFrmType = eType;
drhe4984a22018-07-06 17:19:20 +00001093 pWin->eStart = eStart;
1094 pWin->eEnd = eEnd;
drh94809082019-04-02 17:45:56 +00001095 if( eExclude==0 && OptimizationDisabled(pParse->db, SQLITE_WindowFunc) ){
dan108e6b22019-03-18 18:55:35 +00001096 eExclude = TK_NO;
1097 }
dand35300f2019-03-14 20:53:21 +00001098 pWin->eExclude = eExclude;
dane7c9ca42019-02-16 17:27:51 +00001099 pWin->bImplicitFrame = bImplicitFrame;
drhe4984a22018-07-06 17:19:20 +00001100 pWin->pEnd = sqlite3WindowOffsetExpr(pParse, pEnd);
1101 pWin->pStart = sqlite3WindowOffsetExpr(pParse, pStart);
dan86fb6e12018-05-16 20:58:07 +00001102 return pWin;
drhe4984a22018-07-06 17:19:20 +00001103
1104windowAllocErr:
1105 sqlite3ExprDelete(pParse->db, pEnd);
1106 sqlite3ExprDelete(pParse->db, pStart);
1107 return 0;
dan86fb6e12018-05-16 20:58:07 +00001108}
1109
danc0bb4452018-06-12 20:53:38 +00001110/*
dane7c9ca42019-02-16 17:27:51 +00001111** Attach PARTITION and ORDER BY clauses pPartition and pOrderBy to window
1112** pWin. Also, if parameter pBase is not NULL, set pWin->zBase to the
1113** equivalent nul-terminated string.
1114*/
1115Window *sqlite3WindowAssemble(
1116 Parse *pParse,
1117 Window *pWin,
1118 ExprList *pPartition,
1119 ExprList *pOrderBy,
1120 Token *pBase
1121){
1122 if( pWin ){
1123 pWin->pPartition = pPartition;
1124 pWin->pOrderBy = pOrderBy;
1125 if( pBase ){
1126 pWin->zBase = sqlite3DbStrNDup(pParse->db, pBase->z, pBase->n);
1127 }
1128 }else{
1129 sqlite3ExprListDelete(pParse->db, pPartition);
1130 sqlite3ExprListDelete(pParse->db, pOrderBy);
1131 }
1132 return pWin;
1133}
1134
1135/*
1136** Window *pWin has just been created from a WINDOW clause. Tokne pBase
1137** is the base window. Earlier windows from the same WINDOW clause are
1138** stored in the linked list starting at pWin->pNextWin. This function
1139** either updates *pWin according to the base specification, or else
1140** leaves an error in pParse.
1141*/
1142void sqlite3WindowChain(Parse *pParse, Window *pWin, Window *pList){
1143 if( pWin->zBase ){
1144 sqlite3 *db = pParse->db;
1145 Window *pExist = windowFind(pParse, pList, pWin->zBase);
1146 if( pExist ){
1147 const char *zErr = 0;
1148 /* Check for errors */
1149 if( pWin->pPartition ){
1150 zErr = "PARTITION clause";
1151 }else if( pExist->pOrderBy && pWin->pOrderBy ){
1152 zErr = "ORDER BY clause";
1153 }else if( pExist->bImplicitFrame==0 ){
1154 zErr = "frame specification";
1155 }
1156 if( zErr ){
1157 sqlite3ErrorMsg(pParse,
1158 "cannot override %s of window: %s", zErr, pWin->zBase
1159 );
1160 }else{
1161 pWin->pPartition = sqlite3ExprListDup(db, pExist->pPartition, 0);
1162 if( pExist->pOrderBy ){
1163 assert( pWin->pOrderBy==0 );
1164 pWin->pOrderBy = sqlite3ExprListDup(db, pExist->pOrderBy, 0);
1165 }
1166 sqlite3DbFree(db, pWin->zBase);
1167 pWin->zBase = 0;
1168 }
1169 }
1170 }
1171}
1172
1173/*
danc0bb4452018-06-12 20:53:38 +00001174** Attach window object pWin to expression p.
1175*/
dan86fb6e12018-05-16 20:58:07 +00001176void sqlite3WindowAttach(Parse *pParse, Expr *p, Window *pWin){
1177 if( p ){
drheda079c2018-09-20 19:02:15 +00001178 assert( p->op==TK_FUNCTION );
drh954733b2018-07-27 23:33:16 +00001179 /* This routine is only called for the parser. If pWin was not
1180 ** allocated due to an OOM, then the parser would fail before ever
1181 ** invoking this routine */
1182 if( ALWAYS(pWin) ){
drheda079c2018-09-20 19:02:15 +00001183 p->y.pWin = pWin;
1184 ExprSetProperty(p, EP_WinFunc);
dane33f6e72018-07-06 07:42:42 +00001185 pWin->pOwner = p;
1186 if( p->flags & EP_Distinct ){
drhe4984a22018-07-06 17:19:20 +00001187 sqlite3ErrorMsg(pParse,
1188 "DISTINCT is not supported for window functions");
dane33f6e72018-07-06 07:42:42 +00001189 }
1190 }
dan86fb6e12018-05-16 20:58:07 +00001191 }else{
1192 sqlite3WindowDelete(pParse->db, pWin);
1193 }
1194}
dane2f781b2018-05-17 19:24:08 +00001195
1196/*
1197** Return 0 if the two window objects are identical, or non-zero otherwise.
dan13078ca2018-06-13 20:29:38 +00001198** Identical window objects can be processed in a single scan.
dane2f781b2018-05-17 19:24:08 +00001199*/
1200int sqlite3WindowCompare(Parse *pParse, Window *p1, Window *p2){
drhfc15f4c2019-03-28 13:03:41 +00001201 if( p1->eFrmType!=p2->eFrmType ) return 1;
dane2f781b2018-05-17 19:24:08 +00001202 if( p1->eStart!=p2->eStart ) return 1;
1203 if( p1->eEnd!=p2->eEnd ) return 1;
dana0f6b832019-03-14 16:36:20 +00001204 if( p1->eExclude!=p2->eExclude ) return 1;
dane2f781b2018-05-17 19:24:08 +00001205 if( sqlite3ExprCompare(pParse, p1->pStart, p2->pStart, -1) ) return 1;
1206 if( sqlite3ExprCompare(pParse, p1->pEnd, p2->pEnd, -1) ) return 1;
1207 if( sqlite3ExprListCompare(p1->pPartition, p2->pPartition, -1) ) return 1;
1208 if( sqlite3ExprListCompare(p1->pOrderBy, p2->pOrderBy, -1) ) return 1;
1209 return 0;
1210}
1211
dan13078ca2018-06-13 20:29:38 +00001212
1213/*
1214** This is called by code in select.c before it calls sqlite3WhereBegin()
1215** to begin iterating through the sub-query results. It is used to allocate
1216** and initialize registers and cursors used by sqlite3WindowCodeStep().
1217*/
1218void sqlite3WindowCodeInit(Parse *pParse, Window *pMWin){
danc9a86682018-05-30 20:44:58 +00001219 Window *pWin;
dan13078ca2018-06-13 20:29:38 +00001220 Vdbe *v = sqlite3GetVdbe(pParse);
danb6f2dea2019-03-13 17:20:27 +00001221
1222 /* Allocate registers to use for PARTITION BY values, if any. Initialize
1223 ** said registers to NULL. */
1224 if( pMWin->pPartition ){
1225 int nExpr = pMWin->pPartition->nExpr;
dan13078ca2018-06-13 20:29:38 +00001226 pMWin->regPart = pParse->nMem+1;
danb6f2dea2019-03-13 17:20:27 +00001227 pParse->nMem += nExpr;
1228 sqlite3VdbeAddOp3(v, OP_Null, 0, pMWin->regPart, pMWin->regPart+nExpr-1);
dan13078ca2018-06-13 20:29:38 +00001229 }
1230
danbf845152019-03-16 10:15:24 +00001231 pMWin->regOne = ++pParse->nMem;
1232 sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regOne);
dan680f6e82019-03-04 21:07:11 +00001233
dana0f6b832019-03-14 16:36:20 +00001234 if( pMWin->eExclude ){
1235 pMWin->regStartRowid = ++pParse->nMem;
1236 pMWin->regEndRowid = ++pParse->nMem;
1237 pMWin->csrApp = pParse->nTab++;
1238 sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid);
1239 sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid);
1240 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->csrApp, pMWin->iEphCsr);
1241 return;
1242 }
1243
danc9a86682018-05-30 20:44:58 +00001244 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
danec891fd2018-06-06 20:51:02 +00001245 FuncDef *p = pWin->pFunc;
1246 if( (p->funcFlags & SQLITE_FUNC_MINMAX) && pWin->eStart!=TK_UNBOUNDED ){
dan9a947222018-06-14 19:06:36 +00001247 /* The inline versions of min() and max() require a single ephemeral
1248 ** table and 3 registers. The registers are used as follows:
1249 **
1250 ** regApp+0: slot to copy min()/max() argument to for MakeRecord
1251 ** regApp+1: integer value used to ensure keys are unique
1252 ** regApp+2: output of MakeRecord
1253 */
danc9a86682018-05-30 20:44:58 +00001254 ExprList *pList = pWin->pOwner->x.pList;
1255 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pList, 0, 0);
danc9a86682018-05-30 20:44:58 +00001256 pWin->csrApp = pParse->nTab++;
1257 pWin->regApp = pParse->nMem+1;
1258 pParse->nMem += 3;
1259 if( pKeyInfo && pWin->pFunc->zName[1]=='i' ){
1260 assert( pKeyInfo->aSortOrder[0]==0 );
1261 pKeyInfo->aSortOrder[0] = 1;
1262 }
1263 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pWin->csrApp, 2);
1264 sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
1265 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
1266 }
drh19dc4d42018-07-08 01:02:26 +00001267 else if( p->zName==nth_valueName || p->zName==first_valueName ){
danec891fd2018-06-06 20:51:02 +00001268 /* Allocate two registers at pWin->regApp. These will be used to
1269 ** store the start and end index of the current frame. */
danec891fd2018-06-06 20:51:02 +00001270 pWin->regApp = pParse->nMem+1;
1271 pWin->csrApp = pParse->nTab++;
1272 pParse->nMem += 2;
danec891fd2018-06-06 20:51:02 +00001273 sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
1274 }
drh19dc4d42018-07-08 01:02:26 +00001275 else if( p->zName==leadName || p->zName==lagName ){
danfe4e25a2018-06-07 20:08:59 +00001276 pWin->csrApp = pParse->nTab++;
1277 sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
1278 }
danc9a86682018-05-30 20:44:58 +00001279 }
1280}
1281
danbb407272019-03-12 18:28:51 +00001282#define WINDOW_STARTING_INT 0
1283#define WINDOW_ENDING_INT 1
1284#define WINDOW_NTH_VALUE_INT 2
1285#define WINDOW_STARTING_NUM 3
1286#define WINDOW_ENDING_NUM 4
1287
dan13078ca2018-06-13 20:29:38 +00001288/*
dana1a7e112018-07-09 13:31:18 +00001289** A "PRECEDING <expr>" (eCond==0) or "FOLLOWING <expr>" (eCond==1) or the
1290** value of the second argument to nth_value() (eCond==2) has just been
1291** evaluated and the result left in register reg. This function generates VM
1292** code to check that the value is a non-negative integer and throws an
1293** exception if it is not.
dan13078ca2018-06-13 20:29:38 +00001294*/
danbb407272019-03-12 18:28:51 +00001295static void windowCheckValue(Parse *pParse, int reg, int eCond){
danc3a20c12018-05-23 20:55:37 +00001296 static const char *azErr[] = {
1297 "frame starting offset must be a non-negative integer",
dana1a7e112018-07-09 13:31:18 +00001298 "frame ending offset must be a non-negative integer",
danbb407272019-03-12 18:28:51 +00001299 "second argument to nth_value must be a positive integer",
1300 "frame starting offset must be a non-negative number",
1301 "frame ending offset must be a non-negative number",
danc3a20c12018-05-23 20:55:37 +00001302 };
danbb407272019-03-12 18:28:51 +00001303 static int aOp[] = { OP_Ge, OP_Ge, OP_Gt, OP_Ge, OP_Ge };
danc3a20c12018-05-23 20:55:37 +00001304 Vdbe *v = sqlite3GetVdbe(pParse);
dan13078ca2018-06-13 20:29:38 +00001305 int regZero = sqlite3GetTempReg(pParse);
danbb407272019-03-12 18:28:51 +00001306 assert( eCond>=0 && eCond<ArraySize(azErr) );
danc3a20c12018-05-23 20:55:37 +00001307 sqlite3VdbeAddOp2(v, OP_Integer, 0, regZero);
dane5166e02019-03-19 11:56:39 +00001308 if( eCond>=WINDOW_STARTING_NUM ){
1309 int regString = sqlite3GetTempReg(pParse);
1310 sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC);
1311 sqlite3VdbeAddOp3(v, OP_Ge, regString, sqlite3VdbeCurrentAddr(v)+2, reg);
drh21826f42019-04-01 14:30:30 +00001312 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC|SQLITE_JUMPIFNULL);
drh6f883592019-03-30 20:37:04 +00001313 VdbeCoverage(v);
1314 assert( eCond==3 || eCond==4 );
1315 VdbeCoverageIf(v, eCond==3);
1316 VdbeCoverageIf(v, eCond==4);
dane5166e02019-03-19 11:56:39 +00001317 }else{
1318 sqlite3VdbeAddOp2(v, OP_MustBeInt, reg, sqlite3VdbeCurrentAddr(v)+2);
drh6f883592019-03-30 20:37:04 +00001319 VdbeCoverage(v);
1320 assert( eCond==0 || eCond==1 || eCond==2 );
1321 VdbeCoverageIf(v, eCond==0);
1322 VdbeCoverageIf(v, eCond==1);
1323 VdbeCoverageIf(v, eCond==2);
dane5166e02019-03-19 11:56:39 +00001324 }
dana1a7e112018-07-09 13:31:18 +00001325 sqlite3VdbeAddOp3(v, aOp[eCond], regZero, sqlite3VdbeCurrentAddr(v)+2, reg);
drh21826f42019-04-01 14:30:30 +00001326 VdbeCoverageNeverNullIf(v, eCond==0); /* NULL case captured by */
1327 VdbeCoverageNeverNullIf(v, eCond==1); /* the OP_MustBeInt */
1328 VdbeCoverageNeverNullIf(v, eCond==2);
1329 VdbeCoverageNeverNullIf(v, eCond==3); /* NULL case caught by */
1330 VdbeCoverageNeverNullIf(v, eCond==4); /* the OP_Ge */
drh211a0852019-01-27 02:41:34 +00001331 sqlite3MayAbort(pParse);
danc3a20c12018-05-23 20:55:37 +00001332 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_ERROR, OE_Abort);
dana1a7e112018-07-09 13:31:18 +00001333 sqlite3VdbeAppendP4(v, (void*)azErr[eCond], P4_STATIC);
dan13078ca2018-06-13 20:29:38 +00001334 sqlite3ReleaseTempReg(pParse, regZero);
danc3a20c12018-05-23 20:55:37 +00001335}
1336
dan13078ca2018-06-13 20:29:38 +00001337/*
1338** Return the number of arguments passed to the window-function associated
1339** with the object passed as the only argument to this function.
1340*/
dan2a11bb22018-06-11 20:50:25 +00001341static int windowArgCount(Window *pWin){
1342 ExprList *pList = pWin->pOwner->x.pList;
1343 return (pList ? pList->nExpr : 0);
1344}
1345
danc9a86682018-05-30 20:44:58 +00001346/*
1347** Generate VM code to invoke either xStep() (if bInverse is 0) or
1348** xInverse (if bInverse is non-zero) for each window function in the
dan13078ca2018-06-13 20:29:38 +00001349** linked list starting at pMWin. Or, for built-in window functions
1350** that do not use the standard function API, generate the required
1351** inline VM code.
1352**
1353** If argument csr is greater than or equal to 0, then argument reg is
1354** the first register in an array of registers guaranteed to be large
1355** enough to hold the array of arguments for each function. In this case
1356** the arguments are extracted from the current row of csr into the
drh8f26da62018-07-05 21:22:57 +00001357** array of registers before invoking OP_AggStep or OP_AggInverse
dan13078ca2018-06-13 20:29:38 +00001358**
1359** Or, if csr is less than zero, then the array of registers at reg is
1360** already populated with all columns from the current row of the sub-query.
1361**
1362** If argument regPartSize is non-zero, then it is a register containing the
1363** number of rows in the current partition.
danc9a86682018-05-30 20:44:58 +00001364*/
dan31f56392018-05-24 21:10:57 +00001365static void windowAggStep(
1366 Parse *pParse,
dan13078ca2018-06-13 20:29:38 +00001367 Window *pMWin, /* Linked list of window functions */
1368 int csr, /* Read arguments from this cursor */
1369 int bInverse, /* True to invoke xInverse instead of xStep */
dana0f6b832019-03-14 16:36:20 +00001370 int reg /* Array of registers */
dan31f56392018-05-24 21:10:57 +00001371){
1372 Vdbe *v = sqlite3GetVdbe(pParse);
1373 Window *pWin;
1374 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
dana0f6b832019-03-14 16:36:20 +00001375 FuncDef *pFunc = pWin->pFunc;
danc9a86682018-05-30 20:44:58 +00001376 int regArg;
dan2a11bb22018-06-11 20:50:25 +00001377 int nArg = windowArgCount(pWin);
dana0f6b832019-03-14 16:36:20 +00001378 int i;
dandfa552f2018-06-02 21:04:28 +00001379
dana0f6b832019-03-14 16:36:20 +00001380 for(i=0; i<nArg; i++){
danc782a812019-03-15 20:46:19 +00001381 if( i!=1 || pFunc->zName!=nth_valueName ){
1382 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+i, reg+i);
1383 }else{
1384 sqlite3VdbeAddOp3(v, OP_Column, pMWin->iEphCsr, pWin->iArgCol+i, reg+i);
1385 }
dan31f56392018-05-24 21:10:57 +00001386 }
dana0f6b832019-03-14 16:36:20 +00001387 regArg = reg;
danc9a86682018-05-30 20:44:58 +00001388
dana0f6b832019-03-14 16:36:20 +00001389 if( pMWin->regStartRowid==0
1390 && (pFunc->funcFlags & SQLITE_FUNC_MINMAX)
1391 && (pWin->eStart!=TK_UNBOUNDED)
danec891fd2018-06-06 20:51:02 +00001392 ){
dand4fc49f2018-07-07 17:30:44 +00001393 int addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regArg);
1394 VdbeCoverage(v);
danc9a86682018-05-30 20:44:58 +00001395 if( bInverse==0 ){
1396 sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1, 1);
1397 sqlite3VdbeAddOp2(v, OP_SCopy, regArg, pWin->regApp);
1398 sqlite3VdbeAddOp3(v, OP_MakeRecord, pWin->regApp, 2, pWin->regApp+2);
1399 sqlite3VdbeAddOp2(v, OP_IdxInsert, pWin->csrApp, pWin->regApp+2);
1400 }else{
1401 sqlite3VdbeAddOp4Int(v, OP_SeekGE, pWin->csrApp, 0, regArg, 1);
drh93419162018-07-11 03:27:52 +00001402 VdbeCoverageNeverTaken(v);
danc9a86682018-05-30 20:44:58 +00001403 sqlite3VdbeAddOp1(v, OP_Delete, pWin->csrApp);
1404 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
1405 }
dand4fc49f2018-07-07 17:30:44 +00001406 sqlite3VdbeJumpHere(v, addrIsNull);
danec891fd2018-06-06 20:51:02 +00001407 }else if( pWin->regApp ){
dana0f6b832019-03-14 16:36:20 +00001408 assert( pFunc->zName==nth_valueName
1409 || pFunc->zName==first_valueName
dan7095c002018-06-07 17:45:22 +00001410 );
danec891fd2018-06-06 20:51:02 +00001411 assert( bInverse==0 || bInverse==1 );
1412 sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1-bInverse, 1);
dana0f6b832019-03-14 16:36:20 +00001413 }else if( pFunc->xSFunc!=noopStepFunc ){
dan8b985602018-06-09 17:43:45 +00001414 int addrIf = 0;
1415 if( pWin->pFilter ){
1416 int regTmp;
danf5e8e312018-07-09 06:51:36 +00001417 assert( nArg==0 || nArg==pWin->pOwner->x.pList->nExpr );
1418 assert( nArg || pWin->pOwner->x.pList==0 );
dana0f6b832019-03-14 16:36:20 +00001419 regTmp = sqlite3GetTempReg(pParse);
1420 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+nArg,regTmp);
dan8b985602018-06-09 17:43:45 +00001421 addrIf = sqlite3VdbeAddOp3(v, OP_IfNot, regTmp, 0, 1);
dan01e12292018-06-27 20:24:59 +00001422 VdbeCoverage(v);
dana0f6b832019-03-14 16:36:20 +00001423 sqlite3ReleaseTempReg(pParse, regTmp);
dan8b985602018-06-09 17:43:45 +00001424 }
dana0f6b832019-03-14 16:36:20 +00001425 if( pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
danc9a86682018-05-30 20:44:58 +00001426 CollSeq *pColl;
danf5e8e312018-07-09 06:51:36 +00001427 assert( nArg>0 );
dan8b985602018-06-09 17:43:45 +00001428 pColl = sqlite3ExprNNCollSeq(pParse, pWin->pOwner->x.pList->a[0].pExpr);
danc9a86682018-05-30 20:44:58 +00001429 sqlite3VdbeAddOp4(v, OP_CollSeq, 0,0,0, (const char*)pColl, P4_COLLSEQ);
1430 }
drh8f26da62018-07-05 21:22:57 +00001431 sqlite3VdbeAddOp3(v, bInverse? OP_AggInverse : OP_AggStep,
1432 bInverse, regArg, pWin->regAccum);
dana0f6b832019-03-14 16:36:20 +00001433 sqlite3VdbeAppendP4(v, pFunc, P4_FUNCDEF);
dandfa552f2018-06-02 21:04:28 +00001434 sqlite3VdbeChangeP5(v, (u8)nArg);
dan8b985602018-06-09 17:43:45 +00001435 if( addrIf ) sqlite3VdbeJumpHere(v, addrIf);
danc9a86682018-05-30 20:44:58 +00001436 }
dan31f56392018-05-24 21:10:57 +00001437 }
1438}
1439
danc782a812019-03-15 20:46:19 +00001440typedef struct WindowCodeArg WindowCodeArg;
1441typedef struct WindowCsrAndReg WindowCsrAndReg;
1442struct WindowCsrAndReg {
1443 int csr;
1444 int reg;
1445};
1446
1447struct WindowCodeArg {
1448 Parse *pParse;
1449 Window *pMWin;
1450 Vdbe *pVdbe;
1451 int regGosub;
1452 int addrGosub;
1453 int regArg;
1454 int eDelete;
1455
1456 WindowCsrAndReg start;
1457 WindowCsrAndReg current;
1458 WindowCsrAndReg end;
1459};
1460
1461/*
1462** Values that may be passed as the second argument to windowCodeOp().
1463*/
1464#define WINDOW_RETURN_ROW 1
1465#define WINDOW_AGGINVERSE 2
1466#define WINDOW_AGGSTEP 3
1467
1468/*
1469** Generate VM code to read the window frames peer values from cursor csr into
1470** an array of registers starting at reg.
1471*/
1472static void windowReadPeerValues(
1473 WindowCodeArg *p,
1474 int csr,
1475 int reg
1476){
1477 Window *pMWin = p->pMWin;
1478 ExprList *pOrderBy = pMWin->pOrderBy;
1479 if( pOrderBy ){
1480 Vdbe *v = sqlite3GetVdbe(p->pParse);
1481 ExprList *pPart = pMWin->pPartition;
1482 int iColOff = pMWin->nBufferCol + (pPart ? pPart->nExpr : 0);
1483 int i;
1484 for(i=0; i<pOrderBy->nExpr; i++){
1485 sqlite3VdbeAddOp3(v, OP_Column, csr, iColOff+i, reg+i);
1486 }
1487 }
1488}
1489
dan13078ca2018-06-13 20:29:38 +00001490/*
dana0f6b832019-03-14 16:36:20 +00001491** Generate VM code to invoke either xValue() (bFin==0) or xFinalize()
1492** (bFin==1) for each window function in the linked list starting at
dan13078ca2018-06-13 20:29:38 +00001493** pMWin. Or, for built-in window-functions that do not use the standard
1494** API, generate the equivalent VM code.
1495*/
danc782a812019-03-15 20:46:19 +00001496static void windowAggFinal(WindowCodeArg *p, int bFin){
1497 Parse *pParse = p->pParse;
1498 Window *pMWin = p->pMWin;
dand6f784e2018-05-28 18:30:45 +00001499 Vdbe *v = sqlite3GetVdbe(pParse);
1500 Window *pWin;
1501
1502 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
dana0f6b832019-03-14 16:36:20 +00001503 if( pMWin->regStartRowid==0
1504 && (pWin->pFunc->funcFlags & SQLITE_FUNC_MINMAX)
1505 && (pWin->eStart!=TK_UNBOUNDED)
danec891fd2018-06-06 20:51:02 +00001506 ){
dand6f784e2018-05-28 18:30:45 +00001507 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
danc9a86682018-05-30 20:44:58 +00001508 sqlite3VdbeAddOp1(v, OP_Last, pWin->csrApp);
dan01e12292018-06-27 20:24:59 +00001509 VdbeCoverage(v);
danc9a86682018-05-30 20:44:58 +00001510 sqlite3VdbeAddOp3(v, OP_Column, pWin->csrApp, 0, pWin->regResult);
1511 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
danec891fd2018-06-06 20:51:02 +00001512 }else if( pWin->regApp ){
dana0f6b832019-03-14 16:36:20 +00001513 assert( pMWin->regStartRowid==0 );
dand6f784e2018-05-28 18:30:45 +00001514 }else{
dana0f6b832019-03-14 16:36:20 +00001515 int nArg = windowArgCount(pWin);
1516 if( bFin ){
1517 sqlite3VdbeAddOp2(v, OP_AggFinal, pWin->regAccum, nArg);
drh8f26da62018-07-05 21:22:57 +00001518 sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
danc9a86682018-05-30 20:44:58 +00001519 sqlite3VdbeAddOp2(v, OP_Copy, pWin->regAccum, pWin->regResult);
dan8b985602018-06-09 17:43:45 +00001520 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
danc9a86682018-05-30 20:44:58 +00001521 }else{
dana0f6b832019-03-14 16:36:20 +00001522 sqlite3VdbeAddOp3(v, OP_AggValue,pWin->regAccum,nArg,pWin->regResult);
drh8f26da62018-07-05 21:22:57 +00001523 sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
danc9a86682018-05-30 20:44:58 +00001524 }
dand6f784e2018-05-28 18:30:45 +00001525 }
1526 }
1527}
1528
dan0525b6f2019-03-18 21:19:40 +00001529/*
1530** Generate code to calculate the current values of all window functions in the
1531** p->pMWin list by doing a full scan of the current window frame. Store the
1532** results in the Window.regResult registers, ready to return the upper
1533** layer.
1534*/
danc782a812019-03-15 20:46:19 +00001535static void windowFullScan(WindowCodeArg *p){
1536 Window *pWin;
1537 Parse *pParse = p->pParse;
1538 Window *pMWin = p->pMWin;
1539 Vdbe *v = p->pVdbe;
1540
1541 int regCRowid = 0; /* Current rowid value */
1542 int regCPeer = 0; /* Current peer values */
1543 int regRowid = 0; /* AggStep rowid value */
1544 int regPeer = 0; /* AggStep peer values */
1545
1546 int nPeer;
1547 int lblNext;
1548 int lblBrk;
1549 int addrNext;
1550 int csr = pMWin->csrApp;
1551
1552 nPeer = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);
1553
1554 lblNext = sqlite3VdbeMakeLabel(pParse);
1555 lblBrk = sqlite3VdbeMakeLabel(pParse);
1556
1557 regCRowid = sqlite3GetTempReg(pParse);
1558 regRowid = sqlite3GetTempReg(pParse);
1559 if( nPeer ){
1560 regCPeer = sqlite3GetTempRange(pParse, nPeer);
1561 regPeer = sqlite3GetTempRange(pParse, nPeer);
1562 }
1563
1564 sqlite3VdbeAddOp2(v, OP_Rowid, pMWin->iEphCsr, regCRowid);
1565 windowReadPeerValues(p, pMWin->iEphCsr, regCPeer);
1566
1567 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1568 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
1569 }
1570
1571 sqlite3VdbeAddOp3(v, OP_SeekGE, csr, lblBrk, pMWin->regStartRowid);
dan1d4b25f2019-03-19 16:49:15 +00001572 VdbeCoverage(v);
danc782a812019-03-15 20:46:19 +00001573 addrNext = sqlite3VdbeCurrentAddr(v);
1574 sqlite3VdbeAddOp2(v, OP_Rowid, csr, regRowid);
1575 sqlite3VdbeAddOp3(v, OP_Gt, pMWin->regEndRowid, lblBrk, regRowid);
dan1d4b25f2019-03-19 16:49:15 +00001576 VdbeCoverageNeverNull(v);
dan108e6b22019-03-18 18:55:35 +00001577
danc782a812019-03-15 20:46:19 +00001578 if( pMWin->eExclude==TK_CURRENT ){
1579 sqlite3VdbeAddOp3(v, OP_Eq, regCRowid, lblNext, regRowid);
drh83c5bb92019-04-01 15:55:38 +00001580 VdbeCoverageNeverNull(v);
danc782a812019-03-15 20:46:19 +00001581 }else if( pMWin->eExclude!=TK_NO ){
1582 int addr;
dan108e6b22019-03-18 18:55:35 +00001583 int addrEq = 0;
dan66033422019-03-19 19:19:53 +00001584 KeyInfo *pKeyInfo = 0;
dan108e6b22019-03-18 18:55:35 +00001585
dan66033422019-03-19 19:19:53 +00001586 if( pMWin->pOrderBy ){
1587 pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pMWin->pOrderBy, 0, 0);
danc782a812019-03-15 20:46:19 +00001588 }
dan66033422019-03-19 19:19:53 +00001589 if( pMWin->eExclude==TK_TIES ){
1590 addrEq = sqlite3VdbeAddOp3(v, OP_Eq, regCRowid, 0, regRowid);
drh83c5bb92019-04-01 15:55:38 +00001591 VdbeCoverageNeverNull(v);
dan66033422019-03-19 19:19:53 +00001592 }
1593 if( pKeyInfo ){
1594 windowReadPeerValues(p, csr, regPeer);
1595 sqlite3VdbeAddOp3(v, OP_Compare, regPeer, regCPeer, nPeer);
1596 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
1597 addr = sqlite3VdbeCurrentAddr(v)+1;
1598 sqlite3VdbeAddOp3(v, OP_Jump, addr, lblNext, addr);
1599 VdbeCoverageEqNe(v);
1600 }else{
1601 sqlite3VdbeAddOp2(v, OP_Goto, 0, lblNext);
1602 }
danc782a812019-03-15 20:46:19 +00001603 if( addrEq ) sqlite3VdbeJumpHere(v, addrEq);
1604 }
1605
1606 windowAggStep(pParse, pMWin, csr, 0, p->regArg);
1607
1608 sqlite3VdbeResolveLabel(v, lblNext);
1609 sqlite3VdbeAddOp2(v, OP_Next, csr, addrNext);
dan1d4b25f2019-03-19 16:49:15 +00001610 VdbeCoverage(v);
danc782a812019-03-15 20:46:19 +00001611 sqlite3VdbeJumpHere(v, addrNext-1);
1612 sqlite3VdbeJumpHere(v, addrNext+1);
1613 sqlite3ReleaseTempReg(pParse, regRowid);
1614 sqlite3ReleaseTempReg(pParse, regCRowid);
1615 if( nPeer ){
1616 sqlite3ReleaseTempRange(pParse, regPeer, nPeer);
1617 sqlite3ReleaseTempRange(pParse, regCPeer, nPeer);
1618 }
1619
1620 windowAggFinal(p, 1);
1621}
1622
dan13078ca2018-06-13 20:29:38 +00001623/*
dan13078ca2018-06-13 20:29:38 +00001624** Invoke the sub-routine at regGosub (generated by code in select.c) to
1625** return the current row of Window.iEphCsr. If all window functions are
1626** aggregate window functions that use the standard API, a single
1627** OP_Gosub instruction is all that this routine generates. Extra VM code
1628** for per-row processing is only generated for the following built-in window
1629** functions:
1630**
1631** nth_value()
1632** first_value()
1633** lag()
1634** lead()
1635*/
danc782a812019-03-15 20:46:19 +00001636static void windowReturnOneRow(WindowCodeArg *p){
1637 Window *pMWin = p->pMWin;
1638 Vdbe *v = p->pVdbe;
dan7095c002018-06-07 17:45:22 +00001639
danc782a812019-03-15 20:46:19 +00001640 if( pMWin->regStartRowid ){
1641 windowFullScan(p);
1642 }else{
1643 Parse *pParse = p->pParse;
1644 Window *pWin;
1645
1646 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1647 FuncDef *pFunc = pWin->pFunc;
1648 if( pFunc->zName==nth_valueName
1649 || pFunc->zName==first_valueName
1650 ){
dana0f6b832019-03-14 16:36:20 +00001651 int csr = pWin->csrApp;
danc782a812019-03-15 20:46:19 +00001652 int lbl = sqlite3VdbeMakeLabel(pParse);
1653 int tmpReg = sqlite3GetTempReg(pParse);
1654 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
1655
1656 if( pFunc->zName==nth_valueName ){
1657 sqlite3VdbeAddOp3(v, OP_Column,pMWin->iEphCsr,pWin->iArgCol+1,tmpReg);
1658 windowCheckValue(pParse, tmpReg, 2);
1659 }else{
1660 sqlite3VdbeAddOp2(v, OP_Integer, 1, tmpReg);
1661 }
dana0f6b832019-03-14 16:36:20 +00001662 sqlite3VdbeAddOp3(v, OP_Add, tmpReg, pWin->regApp, tmpReg);
1663 sqlite3VdbeAddOp3(v, OP_Gt, pWin->regApp+1, lbl, tmpReg);
1664 VdbeCoverageNeverNull(v);
1665 sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, 0, tmpReg);
1666 VdbeCoverageNeverTaken(v);
1667 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
danc782a812019-03-15 20:46:19 +00001668 sqlite3VdbeResolveLabel(v, lbl);
1669 sqlite3ReleaseTempReg(pParse, tmpReg);
dana0f6b832019-03-14 16:36:20 +00001670 }
danc782a812019-03-15 20:46:19 +00001671 else if( pFunc->zName==leadName || pFunc->zName==lagName ){
1672 int nArg = pWin->pOwner->x.pList->nExpr;
1673 int csr = pWin->csrApp;
1674 int lbl = sqlite3VdbeMakeLabel(pParse);
1675 int tmpReg = sqlite3GetTempReg(pParse);
1676 int iEph = pMWin->iEphCsr;
1677
1678 if( nArg<3 ){
1679 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
1680 }else{
1681 sqlite3VdbeAddOp3(v, OP_Column, iEph,pWin->iArgCol+2,pWin->regResult);
1682 }
1683 sqlite3VdbeAddOp2(v, OP_Rowid, iEph, tmpReg);
1684 if( nArg<2 ){
1685 int val = (pFunc->zName==leadName ? 1 : -1);
1686 sqlite3VdbeAddOp2(v, OP_AddImm, tmpReg, val);
1687 }else{
1688 int op = (pFunc->zName==leadName ? OP_Add : OP_Subtract);
1689 int tmpReg2 = sqlite3GetTempReg(pParse);
1690 sqlite3VdbeAddOp3(v, OP_Column, iEph, pWin->iArgCol+1, tmpReg2);
1691 sqlite3VdbeAddOp3(v, op, tmpReg2, tmpReg, tmpReg);
1692 sqlite3ReleaseTempReg(pParse, tmpReg2);
1693 }
1694
1695 sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, lbl, tmpReg);
1696 VdbeCoverage(v);
1697 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
1698 sqlite3VdbeResolveLabel(v, lbl);
1699 sqlite3ReleaseTempReg(pParse, tmpReg);
danfe4e25a2018-06-07 20:08:59 +00001700 }
danfe4e25a2018-06-07 20:08:59 +00001701 }
danec891fd2018-06-06 20:51:02 +00001702 }
danc782a812019-03-15 20:46:19 +00001703 sqlite3VdbeAddOp2(v, OP_Gosub, p->regGosub, p->addrGosub);
danec891fd2018-06-06 20:51:02 +00001704}
1705
dan13078ca2018-06-13 20:29:38 +00001706/*
dan54a9ab32018-06-14 14:27:05 +00001707** Generate code to set the accumulator register for each window function
1708** in the linked list passed as the second argument to NULL. And perform
1709** any equivalent initialization required by any built-in window functions
1710** in the list.
1711*/
dan2e605682018-06-07 15:54:26 +00001712static int windowInitAccum(Parse *pParse, Window *pMWin){
1713 Vdbe *v = sqlite3GetVdbe(pParse);
1714 int regArg;
1715 int nArg = 0;
1716 Window *pWin;
1717 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
dan9a947222018-06-14 19:06:36 +00001718 FuncDef *pFunc = pWin->pFunc;
dan2e605682018-06-07 15:54:26 +00001719 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
dan2a11bb22018-06-11 20:50:25 +00001720 nArg = MAX(nArg, windowArgCount(pWin));
dan108e6b22019-03-18 18:55:35 +00001721 if( pMWin->regStartRowid==0 ){
dana0f6b832019-03-14 16:36:20 +00001722 if( pFunc->zName==nth_valueName || pFunc->zName==first_valueName ){
1723 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp);
1724 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
1725 }
dan9a947222018-06-14 19:06:36 +00001726
dana0f6b832019-03-14 16:36:20 +00001727 if( (pFunc->funcFlags & SQLITE_FUNC_MINMAX) && pWin->csrApp ){
1728 assert( pWin->eStart!=TK_UNBOUNDED );
1729 sqlite3VdbeAddOp1(v, OP_ResetSorter, pWin->csrApp);
1730 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
1731 }
dan9a947222018-06-14 19:06:36 +00001732 }
dan2e605682018-06-07 15:54:26 +00001733 }
1734 regArg = pParse->nMem+1;
1735 pParse->nMem += nArg;
1736 return regArg;
1737}
1738
danb33487b2019-03-06 17:12:32 +00001739/*
dancc7a8502019-03-11 19:50:54 +00001740** Return true if the current frame should be cached in the ephemeral table,
1741** even if there are no xInverse() calls required.
danb33487b2019-03-06 17:12:32 +00001742*/
dancc7a8502019-03-11 19:50:54 +00001743static int windowCacheFrame(Window *pMWin){
danb33487b2019-03-06 17:12:32 +00001744 Window *pWin;
dana0f6b832019-03-14 16:36:20 +00001745 if( pMWin->regStartRowid ) return 1;
danb33487b2019-03-06 17:12:32 +00001746 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1747 FuncDef *pFunc = pWin->pFunc;
dancc7a8502019-03-11 19:50:54 +00001748 if( (pFunc->zName==nth_valueName)
danb33487b2019-03-06 17:12:32 +00001749 || (pFunc->zName==first_valueName)
danb560a712019-03-13 15:29:14 +00001750 || (pFunc->zName==leadName)
danb33487b2019-03-06 17:12:32 +00001751 || (pFunc->zName==lagName)
1752 ){
1753 return 1;
1754 }
1755 }
1756 return 0;
1757}
1758
dan6c75b392019-03-08 20:02:52 +00001759/*
1760** regOld and regNew are each the first register in an array of size
1761** pOrderBy->nExpr. This function generates code to compare the two
1762** arrays of registers using the collation sequences and other comparison
1763** parameters specified by pOrderBy.
1764**
1765** If the two arrays are not equal, the contents of regNew is copied to
1766** regOld and control falls through. Otherwise, if the contents of the arrays
1767** are equal, an OP_Goto is executed. The address of the OP_Goto is returned.
1768*/
dan935d9d82019-03-12 15:21:51 +00001769static void windowIfNewPeer(
dan6c75b392019-03-08 20:02:52 +00001770 Parse *pParse,
1771 ExprList *pOrderBy,
1772 int regNew, /* First in array of new values */
dan935d9d82019-03-12 15:21:51 +00001773 int regOld, /* First in array of old values */
1774 int addr /* Jump here */
dan6c75b392019-03-08 20:02:52 +00001775){
1776 Vdbe *v = sqlite3GetVdbe(pParse);
dan6c75b392019-03-08 20:02:52 +00001777 if( pOrderBy ){
1778 int nVal = pOrderBy->nExpr;
1779 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pOrderBy, 0, 0);
1780 sqlite3VdbeAddOp3(v, OP_Compare, regOld, regNew, nVal);
1781 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
dan935d9d82019-03-12 15:21:51 +00001782 sqlite3VdbeAddOp3(v, OP_Jump,
1783 sqlite3VdbeCurrentAddr(v)+1, addr, sqlite3VdbeCurrentAddr(v)+1
dan72b9fdc2019-03-09 20:49:17 +00001784 );
dan6c75b392019-03-08 20:02:52 +00001785 VdbeCoverageEqNe(v);
1786 sqlite3VdbeAddOp3(v, OP_Copy, regNew, regOld, nVal-1);
1787 }else{
dan935d9d82019-03-12 15:21:51 +00001788 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
dan6c75b392019-03-08 20:02:52 +00001789 }
dan6c75b392019-03-08 20:02:52 +00001790}
1791
dan72b9fdc2019-03-09 20:49:17 +00001792/*
1793** This function is called as part of generating VM programs for RANGE
dan1e7cb192019-03-16 20:29:54 +00001794** offset PRECEDING/FOLLOWING frame boundaries. Assuming "ASC" order for
1795** the ORDER BY term in the window, it generates code equivalent to:
dan72b9fdc2019-03-09 20:49:17 +00001796**
1797** if( csr1.peerVal + regVal >= csr2.peerVal ) goto lbl;
dan1e7cb192019-03-16 20:29:54 +00001798**
1799** A special type of arithmetic is used such that if csr.peerVal is not
1800** a numeric type (real or integer), then the result of the addition is
1801** a copy of csr1.peerVal.
dan72b9fdc2019-03-09 20:49:17 +00001802*/
1803static void windowCodeRangeTest(
1804 WindowCodeArg *p,
1805 int op, /* OP_Ge or OP_Gt */
1806 int csr1,
1807 int regVal,
1808 int csr2,
1809 int lbl
1810){
1811 Parse *pParse = p->pParse;
1812 Vdbe *v = sqlite3GetVdbe(pParse);
1813 int reg1 = sqlite3GetTempReg(pParse);
1814 int reg2 = sqlite3GetTempReg(pParse);
dan71fddaf2019-03-11 11:12:34 +00001815 int arith = OP_Add;
dan1e7cb192019-03-16 20:29:54 +00001816 int addrGe;
dan1e7cb192019-03-16 20:29:54 +00001817
1818 int regString = ++pParse->nMem;
dan71fddaf2019-03-11 11:12:34 +00001819
1820 assert( op==OP_Ge || op==OP_Gt || op==OP_Le );
1821 assert( p->pMWin->pOrderBy && p->pMWin->pOrderBy->nExpr==1 );
1822 if( p->pMWin->pOrderBy->a[0].sortOrder ){
1823 switch( op ){
1824 case OP_Ge: op = OP_Le; break;
1825 case OP_Gt: op = OP_Lt; break;
1826 default: assert( op==OP_Le ); op = OP_Ge; break;
1827 }
1828 arith = OP_Subtract;
1829 }
1830
dan72b9fdc2019-03-09 20:49:17 +00001831 windowReadPeerValues(p, csr1, reg1);
1832 windowReadPeerValues(p, csr2, reg2);
dan1e7cb192019-03-16 20:29:54 +00001833
1834 /* Check if the peer value for csr1 value is a text or blob by comparing
danbdabe742019-03-18 16:51:24 +00001835 ** it to the smallest possible string - ''. If it is, jump over the
1836 ** OP_Add or OP_Subtract operation and proceed directly to the comparison. */
dan1e7cb192019-03-16 20:29:54 +00001837 sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC);
1838 addrGe = sqlite3VdbeAddOp3(v, OP_Ge, regString, 0, reg1);
dan1d4b25f2019-03-19 16:49:15 +00001839 VdbeCoverage(v);
dan71fddaf2019-03-11 11:12:34 +00001840 sqlite3VdbeAddOp3(v, arith, regVal, reg1, reg1);
dan1e7cb192019-03-16 20:29:54 +00001841 sqlite3VdbeJumpHere(v, addrGe);
drh6f883592019-03-30 20:37:04 +00001842 sqlite3VdbeAddOp3(v, op, reg2, lbl, reg1); VdbeCoverage(v);
danbdabe742019-03-18 16:51:24 +00001843 sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
drh6f883592019-03-30 20:37:04 +00001844 assert( op==OP_Ge || op==OP_Gt || op==OP_Lt || op==OP_Le );
1845 testcase(op==OP_Ge); VdbeCoverageIf(v, op==OP_Ge);
1846 testcase(op==OP_Lt); VdbeCoverageIf(v, op==OP_Lt);
1847 testcase(op==OP_Le); VdbeCoverageIf(v, op==OP_Le);
1848 testcase(op==OP_Gt); VdbeCoverageIf(v, op==OP_Gt);
dan1e7cb192019-03-16 20:29:54 +00001849
dan72b9fdc2019-03-09 20:49:17 +00001850 sqlite3ReleaseTempReg(pParse, reg1);
1851 sqlite3ReleaseTempReg(pParse, reg2);
dan72b9fdc2019-03-09 20:49:17 +00001852}
1853
dan0525b6f2019-03-18 21:19:40 +00001854/*
1855** Helper function for sqlite3WindowCodeStep(). Each call to this function
1856** generates VM code for a single RETURN_ROW, AGGSTEP or AGGINVERSE
1857** operation. Refer to the header comment for sqlite3WindowCodeStep() for
1858** details.
1859*/
dan00267b82019-03-06 21:04:11 +00001860static int windowCodeOp(
dan0525b6f2019-03-18 21:19:40 +00001861 WindowCodeArg *p, /* Context object */
1862 int op, /* WINDOW_RETURN_ROW, AGGSTEP or AGGINVERSE */
1863 int regCountdown, /* Register for OP_IfPos countdown */
1864 int jumpOnEof /* Jump here if stepped cursor reaches EOF */
dan00267b82019-03-06 21:04:11 +00001865){
dan6c75b392019-03-08 20:02:52 +00001866 int csr, reg;
1867 Parse *pParse = p->pParse;
dan54975cd2019-03-07 20:47:46 +00001868 Window *pMWin = p->pMWin;
dan00267b82019-03-06 21:04:11 +00001869 int ret = 0;
1870 Vdbe *v = p->pVdbe;
1871 int addrIf = 0;
dan6c75b392019-03-08 20:02:52 +00001872 int addrContinue = 0;
1873 int addrGoto = 0;
drhfc15f4c2019-03-28 13:03:41 +00001874 int bPeer = (pMWin->eFrmType!=TK_ROWS);
dan00267b82019-03-06 21:04:11 +00001875
dan72b9fdc2019-03-09 20:49:17 +00001876 int lblDone = sqlite3VdbeMakeLabel(pParse);
1877 int addrNextRange = 0;
1878
dan54975cd2019-03-07 20:47:46 +00001879 /* Special case - WINDOW_AGGINVERSE is always a no-op if the frame
1880 ** starts with UNBOUNDED PRECEDING. */
1881 if( op==WINDOW_AGGINVERSE && pMWin->eStart==TK_UNBOUNDED ){
1882 assert( regCountdown==0 && jumpOnEof==0 );
1883 return 0;
1884 }
1885
dan00267b82019-03-06 21:04:11 +00001886 if( regCountdown>0 ){
drhfc15f4c2019-03-28 13:03:41 +00001887 if( pMWin->eFrmType==TK_RANGE ){
dan72b9fdc2019-03-09 20:49:17 +00001888 addrNextRange = sqlite3VdbeCurrentAddr(v);
dan0525b6f2019-03-18 21:19:40 +00001889 assert( op==WINDOW_AGGINVERSE || op==WINDOW_AGGSTEP );
1890 if( op==WINDOW_AGGINVERSE ){
1891 if( pMWin->eStart==TK_FOLLOWING ){
dan72b9fdc2019-03-09 20:49:17 +00001892 windowCodeRangeTest(
dan0525b6f2019-03-18 21:19:40 +00001893 p, OP_Le, p->current.csr, regCountdown, p->start.csr, lblDone
dan72b9fdc2019-03-09 20:49:17 +00001894 );
dan0525b6f2019-03-18 21:19:40 +00001895 }else{
1896 windowCodeRangeTest(
1897 p, OP_Ge, p->start.csr, regCountdown, p->current.csr, lblDone
1898 );
dan72b9fdc2019-03-09 20:49:17 +00001899 }
dan0525b6f2019-03-18 21:19:40 +00001900 }else{
1901 windowCodeRangeTest(
1902 p, OP_Gt, p->end.csr, regCountdown, p->current.csr, lblDone
1903 );
dan72b9fdc2019-03-09 20:49:17 +00001904 }
dan72b9fdc2019-03-09 20:49:17 +00001905 }else{
1906 addrIf = sqlite3VdbeAddOp3(v, OP_IfPos, regCountdown, 0, 1);
dan1d4b25f2019-03-19 16:49:15 +00001907 VdbeCoverage(v);
dan72b9fdc2019-03-09 20:49:17 +00001908 }
dan00267b82019-03-06 21:04:11 +00001909 }
1910
dan0525b6f2019-03-18 21:19:40 +00001911 if( op==WINDOW_RETURN_ROW && pMWin->regStartRowid==0 ){
danc782a812019-03-15 20:46:19 +00001912 windowAggFinal(p, 0);
dan6c75b392019-03-08 20:02:52 +00001913 }
1914 addrContinue = sqlite3VdbeCurrentAddr(v);
dan00267b82019-03-06 21:04:11 +00001915 switch( op ){
1916 case WINDOW_RETURN_ROW:
dan6c75b392019-03-08 20:02:52 +00001917 csr = p->current.csr;
1918 reg = p->current.reg;
danc782a812019-03-15 20:46:19 +00001919 windowReturnOneRow(p);
dan00267b82019-03-06 21:04:11 +00001920 break;
1921
1922 case WINDOW_AGGINVERSE:
dan6c75b392019-03-08 20:02:52 +00001923 csr = p->start.csr;
1924 reg = p->start.reg;
dana0f6b832019-03-14 16:36:20 +00001925 if( pMWin->regStartRowid ){
1926 assert( pMWin->regEndRowid );
1927 sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regStartRowid, 1);
1928 }else{
1929 windowAggStep(pParse, pMWin, csr, 1, p->regArg);
1930 }
dan00267b82019-03-06 21:04:11 +00001931 break;
1932
dan0525b6f2019-03-18 21:19:40 +00001933 default:
1934 assert( op==WINDOW_AGGSTEP );
dan6c75b392019-03-08 20:02:52 +00001935 csr = p->end.csr;
1936 reg = p->end.reg;
dana0f6b832019-03-14 16:36:20 +00001937 if( pMWin->regStartRowid ){
1938 assert( pMWin->regEndRowid );
1939 sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regEndRowid, 1);
1940 }else{
1941 windowAggStep(pParse, pMWin, csr, 0, p->regArg);
1942 }
dan00267b82019-03-06 21:04:11 +00001943 break;
1944 }
1945
danb560a712019-03-13 15:29:14 +00001946 if( op==p->eDelete ){
1947 sqlite3VdbeAddOp1(v, OP_Delete, csr);
1948 sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
1949 }
1950
danc8137502019-03-07 19:26:17 +00001951 if( jumpOnEof ){
1952 sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+2);
dan1d4b25f2019-03-19 16:49:15 +00001953 VdbeCoverage(v);
danc8137502019-03-07 19:26:17 +00001954 ret = sqlite3VdbeAddOp0(v, OP_Goto);
1955 }else{
dan6c75b392019-03-08 20:02:52 +00001956 sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+1+bPeer);
dan1d4b25f2019-03-19 16:49:15 +00001957 VdbeCoverage(v);
dan6c75b392019-03-08 20:02:52 +00001958 if( bPeer ){
1959 addrGoto = sqlite3VdbeAddOp0(v, OP_Goto);
1960 }
dan00267b82019-03-06 21:04:11 +00001961 }
danc8137502019-03-07 19:26:17 +00001962
dan6c75b392019-03-08 20:02:52 +00001963 if( bPeer ){
dan6c75b392019-03-08 20:02:52 +00001964 int nReg = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);
1965 int regTmp = (nReg ? sqlite3GetTempRange(pParse, nReg) : 0);
1966 windowReadPeerValues(p, csr, regTmp);
dan935d9d82019-03-12 15:21:51 +00001967 windowIfNewPeer(pParse, pMWin->pOrderBy, regTmp, reg, addrContinue);
dan6c75b392019-03-08 20:02:52 +00001968 sqlite3ReleaseTempRange(pParse, regTmp, nReg);
dan00267b82019-03-06 21:04:11 +00001969 }
dan6c75b392019-03-08 20:02:52 +00001970
dan72b9fdc2019-03-09 20:49:17 +00001971 if( addrNextRange ){
1972 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNextRange);
1973 }
1974 sqlite3VdbeResolveLabel(v, lblDone);
dan6c75b392019-03-08 20:02:52 +00001975 if( addrGoto ) sqlite3VdbeJumpHere(v, addrGoto);
1976 if( addrIf ) sqlite3VdbeJumpHere(v, addrIf);
dan00267b82019-03-06 21:04:11 +00001977 return ret;
1978}
1979
dana786e452019-03-11 18:17:04 +00001980
dan00267b82019-03-06 21:04:11 +00001981/*
dana786e452019-03-11 18:17:04 +00001982** Allocate and return a duplicate of the Window object indicated by the
1983** third argument. Set the Window.pOwner field of the new object to
1984** pOwner.
1985*/
1986Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p){
1987 Window *pNew = 0;
1988 if( ALWAYS(p) ){
1989 pNew = sqlite3DbMallocZero(db, sizeof(Window));
1990 if( pNew ){
1991 pNew->zName = sqlite3DbStrDup(db, p->zName);
1992 pNew->pFilter = sqlite3ExprDup(db, p->pFilter, 0);
1993 pNew->pFunc = p->pFunc;
1994 pNew->pPartition = sqlite3ExprListDup(db, p->pPartition, 0);
1995 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, 0);
drhfc15f4c2019-03-28 13:03:41 +00001996 pNew->eFrmType = p->eFrmType;
dana786e452019-03-11 18:17:04 +00001997 pNew->eEnd = p->eEnd;
1998 pNew->eStart = p->eStart;
danc782a812019-03-15 20:46:19 +00001999 pNew->eExclude = p->eExclude;
dana786e452019-03-11 18:17:04 +00002000 pNew->pStart = sqlite3ExprDup(db, p->pStart, 0);
2001 pNew->pEnd = sqlite3ExprDup(db, p->pEnd, 0);
2002 pNew->pOwner = pOwner;
2003 }
2004 }
2005 return pNew;
2006}
2007
2008/*
2009** Return a copy of the linked list of Window objects passed as the
2010** second argument.
2011*/
2012Window *sqlite3WindowListDup(sqlite3 *db, Window *p){
2013 Window *pWin;
2014 Window *pRet = 0;
2015 Window **pp = &pRet;
2016
2017 for(pWin=p; pWin; pWin=pWin->pNextWin){
2018 *pp = sqlite3WindowDup(db, 0, pWin);
2019 if( *pp==0 ) break;
2020 pp = &((*pp)->pNextWin);
2021 }
2022
2023 return pRet;
2024}
2025
2026/*
dan725b1cf2019-03-26 16:47:17 +00002027** Return true if it can be determined at compile time that expression
2028** pExpr evaluates to a value that, when cast to an integer, is greater
2029** than zero. False otherwise.
2030**
2031** If an OOM error occurs, this function sets the Parse.db.mallocFailed
2032** flag and returns zero.
2033*/
2034static int windowExprGtZero(Parse *pParse, Expr *pExpr){
2035 int ret = 0;
2036 sqlite3 *db = pParse->db;
2037 sqlite3_value *pVal = 0;
2038 sqlite3ValueFromExpr(db, pExpr, db->enc, SQLITE_AFF_NUMERIC, &pVal);
2039 if( pVal && sqlite3_value_int(pVal)>0 ){
2040 ret = 1;
2041 }
2042 sqlite3ValueFree(pVal);
2043 return ret;
2044}
2045
2046/*
dana786e452019-03-11 18:17:04 +00002047** sqlite3WhereBegin() has already been called for the SELECT statement
2048** passed as the second argument when this function is invoked. It generates
2049** code to populate the Window.regResult register for each window function
2050** and invoke the sub-routine at instruction addrGosub once for each row.
2051** sqlite3WhereEnd() is always called before returning.
dan00267b82019-03-06 21:04:11 +00002052**
dana786e452019-03-11 18:17:04 +00002053** This function handles several different types of window frames, which
2054** require slightly different processing. The following pseudo code is
2055** used to implement window frames of the form:
dan00267b82019-03-06 21:04:11 +00002056**
dana786e452019-03-11 18:17:04 +00002057** ROWS BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
dan00267b82019-03-06 21:04:11 +00002058**
dana786e452019-03-11 18:17:04 +00002059** Other window frame types use variants of the following:
2060**
2061** ... loop started by sqlite3WhereBegin() ...
dan00267b82019-03-06 21:04:11 +00002062** if( new partition ){
2063** Gosub flush
dana786e452019-03-11 18:17:04 +00002064** }
dan00267b82019-03-06 21:04:11 +00002065** Insert new row into eph table.
dana786e452019-03-11 18:17:04 +00002066**
dan00267b82019-03-06 21:04:11 +00002067** if( first row of partition ){
dana786e452019-03-11 18:17:04 +00002068** // Rewind three cursors, all open on the eph table.
2069** Rewind(csrEnd);
2070** Rewind(csrStart);
2071** Rewind(csrCurrent);
2072**
dan00267b82019-03-06 21:04:11 +00002073** regEnd = <expr2> // FOLLOWING expression
2074** regStart = <expr1> // PRECEDING expression
2075** }else{
dana786e452019-03-11 18:17:04 +00002076** // First time this branch is taken, the eph table contains two
2077** // rows. The first row in the partition, which all three cursors
2078** // currently point to, and the following row.
2079** AGGSTEP
dan00267b82019-03-06 21:04:11 +00002080** if( (regEnd--)<=0 ){
dana786e452019-03-11 18:17:04 +00002081** RETURN_ROW
2082** if( (regStart--)<=0 ){
2083** AGGINVERSE
dan00267b82019-03-06 21:04:11 +00002084** }
2085** }
dana786e452019-03-11 18:17:04 +00002086** }
2087** }
dan00267b82019-03-06 21:04:11 +00002088** flush:
dana786e452019-03-11 18:17:04 +00002089** AGGSTEP
2090** while( 1 ){
2091** RETURN ROW
2092** if( csrCurrent is EOF ) break;
2093** if( (regStart--)<=0 ){
2094** AggInverse(csrStart)
2095** Next(csrStart)
dan00267b82019-03-06 21:04:11 +00002096** }
dana786e452019-03-11 18:17:04 +00002097** }
dan00267b82019-03-06 21:04:11 +00002098**
dana786e452019-03-11 18:17:04 +00002099** The pseudo-code above uses the following shorthand:
dan00267b82019-03-06 21:04:11 +00002100**
dana786e452019-03-11 18:17:04 +00002101** AGGSTEP: invoke the aggregate xStep() function for each window function
2102** with arguments read from the current row of cursor csrEnd, then
2103** step cursor csrEnd forward one row (i.e. sqlite3BtreeNext()).
2104**
2105** RETURN_ROW: return a row to the caller based on the contents of the
2106** current row of csrCurrent and the current state of all
2107** aggregates. Then step cursor csrCurrent forward one row.
2108**
2109** AGGINVERSE: invoke the aggregate xInverse() function for each window
2110** functions with arguments read from the current row of cursor
2111** csrStart. Then step csrStart forward one row.
2112**
2113** There are two other ROWS window frames that are handled significantly
2114** differently from the above - "BETWEEN <expr> PRECEDING AND <expr> PRECEDING"
2115** and "BETWEEN <expr> FOLLOWING AND <expr> FOLLOWING". These are special
2116** cases because they change the order in which the three cursors (csrStart,
2117** csrCurrent and csrEnd) iterate through the ephemeral table. Cases that
2118** use UNBOUNDED or CURRENT ROW are much simpler variations on one of these
2119** three.
2120**
2121** ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
2122**
2123** ... loop started by sqlite3WhereBegin() ...
dan00267b82019-03-06 21:04:11 +00002124** if( new partition ){
2125** Gosub flush
dana786e452019-03-11 18:17:04 +00002126** }
dan00267b82019-03-06 21:04:11 +00002127** Insert new row into eph table.
2128** if( first row of partition ){
dan935d9d82019-03-12 15:21:51 +00002129** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
dana786e452019-03-11 18:17:04 +00002130** regEnd = <expr2>
2131** regStart = <expr1>
dan00267b82019-03-06 21:04:11 +00002132** }else{
dana786e452019-03-11 18:17:04 +00002133** if( (regEnd--)<=0 ){
2134** AGGSTEP
2135** }
2136** RETURN_ROW
2137** if( (regStart--)<=0 ){
2138** AGGINVERSE
2139** }
2140** }
2141** }
dan00267b82019-03-06 21:04:11 +00002142** flush:
dana786e452019-03-11 18:17:04 +00002143** if( (regEnd--)<=0 ){
2144** AGGSTEP
2145** }
2146** RETURN_ROW
2147**
2148**
2149** ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
2150**
2151** ... loop started by sqlite3WhereBegin() ...
2152** if( new partition ){
2153** Gosub flush
2154** }
2155** Insert new row into eph table.
2156** if( first row of partition ){
dan935d9d82019-03-12 15:21:51 +00002157** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
dana786e452019-03-11 18:17:04 +00002158** regEnd = <expr2>
2159** regStart = regEnd - <expr1>
2160** }else{
2161** AGGSTEP
2162** if( (regEnd--)<=0 ){
2163** RETURN_ROW
2164** }
2165** if( (regStart--)<=0 ){
2166** AGGINVERSE
2167** }
2168** }
2169** }
2170** flush:
2171** AGGSTEP
2172** while( 1 ){
2173** if( (regEnd--)<=0 ){
2174** RETURN_ROW
2175** if( eof ) break;
2176** }
2177** if( (regStart--)<=0 ){
2178** AGGINVERSE
2179** if( eof ) break
2180** }
2181** }
2182** while( !eof csrCurrent ){
2183** RETURN_ROW
2184** }
2185**
2186** For the most part, the patterns above are adapted to support UNBOUNDED by
2187** assuming that it is equivalent to "infinity PRECEDING/FOLLOWING" and
2188** CURRENT ROW by assuming that it is equivilent to "0 PRECEDING/FOLLOWING".
2189** This is optimized of course - branches that will never be taken and
2190** conditions that are always true are omitted from the VM code. The only
2191** exceptional case is:
2192**
2193** ROWS BETWEEN <expr1> FOLLOWING AND UNBOUNDED FOLLOWING
2194**
2195** ... loop started by sqlite3WhereBegin() ...
2196** if( new partition ){
2197** Gosub flush
2198** }
2199** Insert new row into eph table.
2200** if( first row of partition ){
dan935d9d82019-03-12 15:21:51 +00002201** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
dana786e452019-03-11 18:17:04 +00002202** regStart = <expr1>
2203** }else{
2204** AGGSTEP
2205** }
2206** }
2207** flush:
2208** AGGSTEP
2209** while( 1 ){
2210** if( (regStart--)<=0 ){
2211** AGGINVERSE
2212** if( eof ) break
2213** }
2214** RETURN_ROW
2215** }
2216** while( !eof csrCurrent ){
2217** RETURN_ROW
2218** }
dan935d9d82019-03-12 15:21:51 +00002219**
2220** Also requiring special handling are the cases:
2221**
2222** ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
2223** ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
2224**
2225** when (expr1 < expr2). This is detected at runtime, not by this function.
2226** To handle this case, the pseudo-code programs depicted above are modified
2227** slightly to be:
2228**
2229** ... loop started by sqlite3WhereBegin() ...
2230** if( new partition ){
2231** Gosub flush
2232** }
2233** Insert new row into eph table.
2234** if( first row of partition ){
2235** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2236** regEnd = <expr2>
2237** regStart = <expr1>
2238** if( regEnd < regStart ){
2239** RETURN_ROW
2240** delete eph table contents
2241** continue
2242** }
2243** ...
2244**
2245** The new "continue" statement in the above jumps to the next iteration
2246** of the outer loop - the one started by sqlite3WhereBegin().
2247**
2248** The various GROUPS cases are implemented using the same patterns as
2249** ROWS. The VM code is modified slightly so that:
2250**
2251** 1. The else branch in the main loop is only taken if the row just
2252** added to the ephemeral table is the start of a new group. In
2253** other words, it becomes:
2254**
2255** ... loop started by sqlite3WhereBegin() ...
2256** if( new partition ){
2257** Gosub flush
2258** }
2259** Insert new row into eph table.
2260** if( first row of partition ){
2261** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2262** regEnd = <expr2>
2263** regStart = <expr1>
2264** }else if( new group ){
2265** ...
2266** }
2267** }
2268**
2269** 2. Instead of processing a single row, each RETURN_ROW, AGGSTEP or
2270** AGGINVERSE step processes the current row of the relevant cursor and
2271** all subsequent rows belonging to the same group.
2272**
2273** RANGE window frames are a little different again. As for GROUPS, the
2274** main loop runs once per group only. And RETURN_ROW, AGGSTEP and AGGINVERSE
2275** deal in groups instead of rows. As for ROWS and GROUPS, there are three
2276** basic cases:
2277**
2278** RANGE BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
2279**
2280** ... loop started by sqlite3WhereBegin() ...
2281** if( new partition ){
2282** Gosub flush
2283** }
2284** Insert new row into eph table.
2285** if( first row of partition ){
2286** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2287** regEnd = <expr2>
2288** regStart = <expr1>
2289** }else{
2290** AGGSTEP
2291** while( (csrCurrent.key + regEnd) < csrEnd.key ){
2292** RETURN_ROW
2293** while( csrStart.key + regStart) < csrCurrent.key ){
2294** AGGINVERSE
2295** }
2296** }
2297** }
2298** }
2299** flush:
2300** AGGSTEP
2301** while( 1 ){
2302** RETURN ROW
2303** if( csrCurrent is EOF ) break;
2304** while( csrStart.key + regStart) < csrCurrent.key ){
2305** AGGINVERSE
2306** }
2307** }
2308** }
2309**
2310** In the above notation, "csr.key" means the current value of the ORDER BY
2311** expression (there is only ever 1 for a RANGE that uses an <expr> FOLLOWING
2312** or <expr PRECEDING) read from cursor csr.
2313**
2314** RANGE BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
2315**
2316** ... loop started by sqlite3WhereBegin() ...
2317** if( new partition ){
2318** Gosub flush
2319** }
2320** Insert new row into eph table.
2321** if( first row of partition ){
2322** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2323** regEnd = <expr2>
2324** regStart = <expr1>
2325** }else{
dan3f49c322019-04-03 16:27:44 +00002326** if( (csrEnd.key + regEnd) <= csrCurrent.key ){
dan935d9d82019-03-12 15:21:51 +00002327** AGGSTEP
2328** }
dan935d9d82019-03-12 15:21:51 +00002329** while( (csrStart.key + regStart) < csrCurrent.key ){
2330** AGGINVERSE
2331** }
dan3f49c322019-04-03 16:27:44 +00002332** RETURN_ROW
dan935d9d82019-03-12 15:21:51 +00002333** }
2334** }
2335** flush:
2336** while( (csrEnd.key + regEnd) <= csrCurrent.key ){
2337** AGGSTEP
2338** }
dan3f49c322019-04-03 16:27:44 +00002339** while( (csrStart.key + regStart) < csrCurrent.key ){
2340** AGGINVERSE
2341** }
dan935d9d82019-03-12 15:21:51 +00002342** RETURN_ROW
2343**
2344** RANGE BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
2345**
2346** ... loop started by sqlite3WhereBegin() ...
2347** if( new partition ){
2348** Gosub flush
2349** }
2350** Insert new row into eph table.
2351** if( first row of partition ){
2352** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2353** regEnd = <expr2>
2354** regStart = <expr1>
2355** }else{
2356** AGGSTEP
2357** while( (csrCurrent.key + regEnd) < csrEnd.key ){
2358** while( (csrCurrent.key + regStart) > csrStart.key ){
2359** AGGINVERSE
2360** }
2361** RETURN_ROW
2362** }
2363** }
2364** }
2365** flush:
2366** AGGSTEP
2367** while( 1 ){
2368** while( (csrCurrent.key + regStart) > csrStart.key ){
2369** AGGINVERSE
2370** if( eof ) break "while( 1 )" loop.
2371** }
2372** RETURN_ROW
2373** }
2374** while( !eof csrCurrent ){
2375** RETURN_ROW
2376** }
2377**
danb6f2dea2019-03-13 17:20:27 +00002378** The text above leaves out many details. Refer to the code and comments
2379** below for a more complete picture.
dan00267b82019-03-06 21:04:11 +00002380*/
dana786e452019-03-11 18:17:04 +00002381void sqlite3WindowCodeStep(
dancc7a8502019-03-11 19:50:54 +00002382 Parse *pParse, /* Parse context */
dana786e452019-03-11 18:17:04 +00002383 Select *p, /* Rewritten SELECT statement */
2384 WhereInfo *pWInfo, /* Context returned by sqlite3WhereBegin() */
2385 int regGosub, /* Register for OP_Gosub */
2386 int addrGosub /* OP_Gosub here to return each row */
dan680f6e82019-03-04 21:07:11 +00002387){
2388 Window *pMWin = p->pWin;
dan6c75b392019-03-08 20:02:52 +00002389 ExprList *pOrderBy = pMWin->pOrderBy;
dan680f6e82019-03-04 21:07:11 +00002390 Vdbe *v = sqlite3GetVdbe(pParse);
dana786e452019-03-11 18:17:04 +00002391 int csrWrite; /* Cursor used to write to eph. table */
2392 int csrInput = p->pSrc->a[0].iCursor; /* Cursor of sub-select */
2393 int nInput = p->pSrc->a[0].pTab->nCol; /* Number of cols returned by sub */
2394 int iInput; /* To iterate through sub cols */
danbf845152019-03-16 10:15:24 +00002395 int addrNe; /* Address of OP_Ne */
drhd4a591d2019-03-26 16:21:11 +00002396 int addrGosubFlush = 0; /* Address of OP_Gosub to flush: */
2397 int addrInteger = 0; /* Address of OP_Integer */
dand4461652019-03-13 08:28:51 +00002398 int addrEmpty; /* Address of OP_Rewind in flush: */
dan54975cd2019-03-07 20:47:46 +00002399 int regStart = 0; /* Value of <expr> PRECEDING */
2400 int regEnd = 0; /* Value of <expr> FOLLOWING */
dana786e452019-03-11 18:17:04 +00002401 int regNew; /* Array of registers holding new input row */
2402 int regRecord; /* regNew array in record form */
2403 int regRowid; /* Rowid for regRecord in eph table */
2404 int regNewPeer = 0; /* Peer values for new row (part of regNew) */
2405 int regPeer = 0; /* Peer values for current row */
dand4461652019-03-13 08:28:51 +00002406 int regFlushPart = 0; /* Register for "Gosub flush_partition" */
dana786e452019-03-11 18:17:04 +00002407 WindowCodeArg s; /* Context object for sub-routines */
dan935d9d82019-03-12 15:21:51 +00002408 int lblWhereEnd; /* Label just before sqlite3WhereEnd() code */
dan680f6e82019-03-04 21:07:11 +00002409
dan72b9fdc2019-03-09 20:49:17 +00002410 assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_CURRENT
2411 || pMWin->eStart==TK_FOLLOWING || pMWin->eStart==TK_UNBOUNDED
2412 );
2413 assert( pMWin->eEnd==TK_FOLLOWING || pMWin->eEnd==TK_CURRENT
2414 || pMWin->eEnd==TK_UNBOUNDED || pMWin->eEnd==TK_PRECEDING
2415 );
dan108e6b22019-03-18 18:55:35 +00002416 assert( pMWin->eExclude==0 || pMWin->eExclude==TK_CURRENT
2417 || pMWin->eExclude==TK_GROUP || pMWin->eExclude==TK_TIES
2418 || pMWin->eExclude==TK_NO
2419 );
dan72b9fdc2019-03-09 20:49:17 +00002420
dan935d9d82019-03-12 15:21:51 +00002421 lblWhereEnd = sqlite3VdbeMakeLabel(pParse);
dana786e452019-03-11 18:17:04 +00002422
2423 /* Fill in the context object */
dan00267b82019-03-06 21:04:11 +00002424 memset(&s, 0, sizeof(WindowCodeArg));
2425 s.pParse = pParse;
2426 s.pMWin = pMWin;
2427 s.pVdbe = v;
2428 s.regGosub = regGosub;
2429 s.addrGosub = addrGosub;
dan6c75b392019-03-08 20:02:52 +00002430 s.current.csr = pMWin->iEphCsr;
dana786e452019-03-11 18:17:04 +00002431 csrWrite = s.current.csr+1;
dan6c75b392019-03-08 20:02:52 +00002432 s.start.csr = s.current.csr+2;
2433 s.end.csr = s.current.csr+3;
danb33487b2019-03-06 17:12:32 +00002434
danb560a712019-03-13 15:29:14 +00002435 /* Figure out when rows may be deleted from the ephemeral table. There
2436 ** are four options - they may never be deleted (eDelete==0), they may
2437 ** be deleted as soon as they are no longer part of the window frame
2438 ** (eDelete==WINDOW_AGGINVERSE), they may be deleted as after the row
2439 ** has been returned to the caller (WINDOW_RETURN_ROW), or they may
2440 ** be deleted after they enter the frame (WINDOW_AGGSTEP). */
2441 switch( pMWin->eStart ){
dan725b1cf2019-03-26 16:47:17 +00002442 case TK_FOLLOWING:
drhfc15f4c2019-03-28 13:03:41 +00002443 if( pMWin->eFrmType!=TK_RANGE
2444 && windowExprGtZero(pParse, pMWin->pStart)
2445 ){
dan725b1cf2019-03-26 16:47:17 +00002446 s.eDelete = WINDOW_RETURN_ROW;
danb560a712019-03-13 15:29:14 +00002447 }
danb560a712019-03-13 15:29:14 +00002448 break;
danb560a712019-03-13 15:29:14 +00002449 case TK_UNBOUNDED:
2450 if( windowCacheFrame(pMWin)==0 ){
2451 if( pMWin->eEnd==TK_PRECEDING ){
drhfc15f4c2019-03-28 13:03:41 +00002452 if( pMWin->eFrmType!=TK_RANGE
2453 && windowExprGtZero(pParse, pMWin->pEnd)
2454 ){
dan725b1cf2019-03-26 16:47:17 +00002455 s.eDelete = WINDOW_AGGSTEP;
2456 }
danb560a712019-03-13 15:29:14 +00002457 }else{
2458 s.eDelete = WINDOW_RETURN_ROW;
2459 }
2460 }
2461 break;
2462 default:
2463 s.eDelete = WINDOW_AGGINVERSE;
2464 break;
2465 }
2466
dand4461652019-03-13 08:28:51 +00002467 /* Allocate registers for the array of values from the sub-query, the
2468 ** samve values in record form, and the rowid used to insert said record
2469 ** into the ephemeral table. */
dana786e452019-03-11 18:17:04 +00002470 regNew = pParse->nMem+1;
2471 pParse->nMem += nInput;
2472 regRecord = ++pParse->nMem;
2473 regRowid = ++pParse->nMem;
dan54975cd2019-03-07 20:47:46 +00002474
dana786e452019-03-11 18:17:04 +00002475 /* If the window frame contains an "<expr> PRECEDING" or "<expr> FOLLOWING"
2476 ** clause, allocate registers to store the results of evaluating each
2477 ** <expr>. */
dan54975cd2019-03-07 20:47:46 +00002478 if( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_FOLLOWING ){
2479 regStart = ++pParse->nMem;
2480 }
2481 if( pMWin->eEnd==TK_PRECEDING || pMWin->eEnd==TK_FOLLOWING ){
2482 regEnd = ++pParse->nMem;
2483 }
dan680f6e82019-03-04 21:07:11 +00002484
dan72b9fdc2019-03-09 20:49:17 +00002485 /* If this is not a "ROWS BETWEEN ..." frame, then allocate arrays of
dana786e452019-03-11 18:17:04 +00002486 ** registers to store copies of the ORDER BY expressions (peer values)
2487 ** for the main loop, and for each cursor (start, current and end). */
drhfc15f4c2019-03-28 13:03:41 +00002488 if( pMWin->eFrmType!=TK_ROWS ){
dan6c75b392019-03-08 20:02:52 +00002489 int nPeer = (pOrderBy ? pOrderBy->nExpr : 0);
dana786e452019-03-11 18:17:04 +00002490 regNewPeer = regNew + pMWin->nBufferCol;
dan6c75b392019-03-08 20:02:52 +00002491 if( pMWin->pPartition ) regNewPeer += pMWin->pPartition->nExpr;
dan6c75b392019-03-08 20:02:52 +00002492 regPeer = pParse->nMem+1; pParse->nMem += nPeer;
2493 s.start.reg = pParse->nMem+1; pParse->nMem += nPeer;
2494 s.current.reg = pParse->nMem+1; pParse->nMem += nPeer;
2495 s.end.reg = pParse->nMem+1; pParse->nMem += nPeer;
2496 }
2497
dan680f6e82019-03-04 21:07:11 +00002498 /* Load the column values for the row returned by the sub-select
dana786e452019-03-11 18:17:04 +00002499 ** into an array of registers starting at regNew. Assemble them into
2500 ** a record in register regRecord. */
2501 for(iInput=0; iInput<nInput; iInput++){
2502 sqlite3VdbeAddOp3(v, OP_Column, csrInput, iInput, regNew+iInput);
dan680f6e82019-03-04 21:07:11 +00002503 }
dana786e452019-03-11 18:17:04 +00002504 sqlite3VdbeAddOp3(v, OP_MakeRecord, regNew, nInput, regRecord);
dan680f6e82019-03-04 21:07:11 +00002505
danb33487b2019-03-06 17:12:32 +00002506 /* An input row has just been read into an array of registers starting
dana786e452019-03-11 18:17:04 +00002507 ** at regNew. If the window has a PARTITION clause, this block generates
danb33487b2019-03-06 17:12:32 +00002508 ** VM code to check if the input row is the start of a new partition.
2509 ** If so, it does an OP_Gosub to an address to be filled in later. The
dana786e452019-03-11 18:17:04 +00002510 ** address of the OP_Gosub is stored in local variable addrGosubFlush. */
dan680f6e82019-03-04 21:07:11 +00002511 if( pMWin->pPartition ){
2512 int addr;
2513 ExprList *pPart = pMWin->pPartition;
2514 int nPart = pPart->nExpr;
dana786e452019-03-11 18:17:04 +00002515 int regNewPart = regNew + pMWin->nBufferCol;
dan680f6e82019-03-04 21:07:11 +00002516 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pPart, 0, 0);
2517
dand4461652019-03-13 08:28:51 +00002518 regFlushPart = ++pParse->nMem;
dan680f6e82019-03-04 21:07:11 +00002519 addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPart, pMWin->regPart, nPart);
2520 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
danb33487b2019-03-06 17:12:32 +00002521 sqlite3VdbeAddOp3(v, OP_Jump, addr+2, addr+4, addr+2);
dan680f6e82019-03-04 21:07:11 +00002522 VdbeCoverageEqNe(v);
2523 addrGosubFlush = sqlite3VdbeAddOp1(v, OP_Gosub, regFlushPart);
2524 VdbeComment((v, "call flush_partition"));
danb33487b2019-03-06 17:12:32 +00002525 sqlite3VdbeAddOp3(v, OP_Copy, regNewPart, pMWin->regPart, nPart-1);
dan680f6e82019-03-04 21:07:11 +00002526 }
2527
2528 /* Insert the new row into the ephemeral table */
2529 sqlite3VdbeAddOp2(v, OP_NewRowid, csrWrite, regRowid);
2530 sqlite3VdbeAddOp3(v, OP_Insert, csrWrite, regRecord, regRowid);
danbf845152019-03-16 10:15:24 +00002531 addrNe = sqlite3VdbeAddOp3(v, OP_Ne, pMWin->regOne, 0, regRowid);
drh83c5bb92019-04-01 15:55:38 +00002532 VdbeCoverageNeverNull(v);
danb25a2142019-03-05 19:29:36 +00002533
danb33487b2019-03-06 17:12:32 +00002534 /* This block is run for the first row of each partition */
dana786e452019-03-11 18:17:04 +00002535 s.regArg = windowInitAccum(pParse, pMWin);
dan680f6e82019-03-04 21:07:11 +00002536
dan54975cd2019-03-07 20:47:46 +00002537 if( regStart ){
2538 sqlite3ExprCode(pParse, pMWin->pStart, regStart);
drhfc15f4c2019-03-28 13:03:41 +00002539 windowCheckValue(pParse, regStart, 0 + (pMWin->eFrmType==TK_RANGE ? 3 : 0));
dan54975cd2019-03-07 20:47:46 +00002540 }
2541 if( regEnd ){
2542 sqlite3ExprCode(pParse, pMWin->pEnd, regEnd);
drhfc15f4c2019-03-28 13:03:41 +00002543 windowCheckValue(pParse, regEnd, 1 + (pMWin->eFrmType==TK_RANGE ? 3 : 0));
dan54975cd2019-03-07 20:47:46 +00002544 }
danb25a2142019-03-05 19:29:36 +00002545
dan0525b6f2019-03-18 21:19:40 +00002546 if( pMWin->eStart==pMWin->eEnd && regStart ){
danb25a2142019-03-05 19:29:36 +00002547 int op = ((pMWin->eStart==TK_FOLLOWING) ? OP_Ge : OP_Le);
2548 int addrGe = sqlite3VdbeAddOp3(v, op, regStart, 0, regEnd);
drh495ed622019-04-01 16:23:21 +00002549 VdbeCoverageNeverNullIf(v, op==OP_Ge); /* NeverNull because bound <expr> */
2550 VdbeCoverageNeverNullIf(v, op==OP_Le); /* values previously checked */
danc782a812019-03-15 20:46:19 +00002551 windowAggFinal(&s, 0);
dancc7a8502019-03-11 19:50:54 +00002552 sqlite3VdbeAddOp2(v, OP_Rewind, s.current.csr, 1);
dan1d4b25f2019-03-19 16:49:15 +00002553 VdbeCoverageNeverTaken(v);
danc782a812019-03-15 20:46:19 +00002554 windowReturnOneRow(&s);
dancc7a8502019-03-11 19:50:54 +00002555 sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr);
dan935d9d82019-03-12 15:21:51 +00002556 sqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd);
danb25a2142019-03-05 19:29:36 +00002557 sqlite3VdbeJumpHere(v, addrGe);
2558 }
drhfc15f4c2019-03-28 13:03:41 +00002559 if( pMWin->eStart==TK_FOLLOWING && pMWin->eFrmType!=TK_RANGE && regEnd ){
dan54975cd2019-03-07 20:47:46 +00002560 assert( pMWin->eEnd==TK_FOLLOWING );
danb25a2142019-03-05 19:29:36 +00002561 sqlite3VdbeAddOp3(v, OP_Subtract, regStart, regEnd, regStart);
2562 }
2563
dan54975cd2019-03-07 20:47:46 +00002564 if( pMWin->eStart!=TK_UNBOUNDED ){
dan6c75b392019-03-08 20:02:52 +00002565 sqlite3VdbeAddOp2(v, OP_Rewind, s.start.csr, 1);
dan1d4b25f2019-03-19 16:49:15 +00002566 VdbeCoverageNeverTaken(v);
dan54975cd2019-03-07 20:47:46 +00002567 }
dan6c75b392019-03-08 20:02:52 +00002568 sqlite3VdbeAddOp2(v, OP_Rewind, s.current.csr, 1);
dan1d4b25f2019-03-19 16:49:15 +00002569 VdbeCoverageNeverTaken(v);
dan6c75b392019-03-08 20:02:52 +00002570 sqlite3VdbeAddOp2(v, OP_Rewind, s.end.csr, 1);
dan1d4b25f2019-03-19 16:49:15 +00002571 VdbeCoverageNeverTaken(v);
dan6c75b392019-03-08 20:02:52 +00002572 if( regPeer && pOrderBy ){
dancc7a8502019-03-11 19:50:54 +00002573 sqlite3VdbeAddOp3(v, OP_Copy, regNewPeer, regPeer, pOrderBy->nExpr-1);
dan6c75b392019-03-08 20:02:52 +00002574 sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.start.reg, pOrderBy->nExpr-1);
2575 sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.current.reg, pOrderBy->nExpr-1);
2576 sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.end.reg, pOrderBy->nExpr-1);
2577 }
danb25a2142019-03-05 19:29:36 +00002578
dan935d9d82019-03-12 15:21:51 +00002579 sqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd);
dan680f6e82019-03-04 21:07:11 +00002580
danbf845152019-03-16 10:15:24 +00002581 sqlite3VdbeJumpHere(v, addrNe);
dan3f49c322019-04-03 16:27:44 +00002582
2583 /* Beginning of the block executed for the second and subsequent rows. */
dan6c75b392019-03-08 20:02:52 +00002584 if( regPeer ){
dan935d9d82019-03-12 15:21:51 +00002585 windowIfNewPeer(pParse, pOrderBy, regNewPeer, regPeer, lblWhereEnd);
dan6c75b392019-03-08 20:02:52 +00002586 }
danb25a2142019-03-05 19:29:36 +00002587 if( pMWin->eStart==TK_FOLLOWING ){
dan6c75b392019-03-08 20:02:52 +00002588 windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
dan54975cd2019-03-07 20:47:46 +00002589 if( pMWin->eEnd!=TK_UNBOUNDED ){
drhfc15f4c2019-03-28 13:03:41 +00002590 if( pMWin->eFrmType==TK_RANGE ){
dan72b9fdc2019-03-09 20:49:17 +00002591 int lbl = sqlite3VdbeMakeLabel(pParse);
2592 int addrNext = sqlite3VdbeCurrentAddr(v);
2593 windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl);
2594 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2595 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
2596 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNext);
2597 sqlite3VdbeResolveLabel(v, lbl);
2598 }else{
2599 windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 0);
2600 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2601 }
dan54975cd2019-03-07 20:47:46 +00002602 }
danb25a2142019-03-05 19:29:36 +00002603 }else
2604 if( pMWin->eEnd==TK_PRECEDING ){
dan3f49c322019-04-03 16:27:44 +00002605 int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE);
dan6c75b392019-03-08 20:02:52 +00002606 windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0);
dan3f49c322019-04-03 16:27:44 +00002607 if( bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
dan6c75b392019-03-08 20:02:52 +00002608 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
dan3f49c322019-04-03 16:27:44 +00002609 if( !bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
danb25a2142019-03-05 19:29:36 +00002610 }else{
mistachkinba9ee092019-03-27 14:58:18 +00002611 int addr = 0;
dan6c75b392019-03-08 20:02:52 +00002612 windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
dan54975cd2019-03-07 20:47:46 +00002613 if( pMWin->eEnd!=TK_UNBOUNDED ){
drhfc15f4c2019-03-28 13:03:41 +00002614 if( pMWin->eFrmType==TK_RANGE ){
mistachkinba9ee092019-03-27 14:58:18 +00002615 int lbl = 0;
dan72b9fdc2019-03-09 20:49:17 +00002616 addr = sqlite3VdbeCurrentAddr(v);
2617 if( regEnd ){
2618 lbl = sqlite3VdbeMakeLabel(pParse);
2619 windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl);
2620 }
2621 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
2622 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2623 if( regEnd ){
2624 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
2625 sqlite3VdbeResolveLabel(v, lbl);
2626 }
2627 }else{
dan1d4b25f2019-03-19 16:49:15 +00002628 if( regEnd ){
2629 addr = sqlite3VdbeAddOp3(v, OP_IfPos, regEnd, 0, 1);
2630 VdbeCoverage(v);
2631 }
dan72b9fdc2019-03-09 20:49:17 +00002632 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
2633 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2634 if( regEnd ) sqlite3VdbeJumpHere(v, addr);
2635 }
dan54975cd2019-03-07 20:47:46 +00002636 }
danb25a2142019-03-05 19:29:36 +00002637 }
dan680f6e82019-03-04 21:07:11 +00002638
dan680f6e82019-03-04 21:07:11 +00002639 /* End of the main input loop */
dan935d9d82019-03-12 15:21:51 +00002640 sqlite3VdbeResolveLabel(v, lblWhereEnd);
dancc7a8502019-03-11 19:50:54 +00002641 sqlite3WhereEnd(pWInfo);
dan680f6e82019-03-04 21:07:11 +00002642
2643 /* Fall through */
dancc7a8502019-03-11 19:50:54 +00002644 if( pMWin->pPartition ){
dan680f6e82019-03-04 21:07:11 +00002645 addrInteger = sqlite3VdbeAddOp2(v, OP_Integer, 0, regFlushPart);
2646 sqlite3VdbeJumpHere(v, addrGosubFlush);
2647 }
2648
danc8137502019-03-07 19:26:17 +00002649 addrEmpty = sqlite3VdbeAddOp1(v, OP_Rewind, csrWrite);
dan1d4b25f2019-03-19 16:49:15 +00002650 VdbeCoverage(v);
dan00267b82019-03-06 21:04:11 +00002651 if( pMWin->eEnd==TK_PRECEDING ){
dan3f49c322019-04-03 16:27:44 +00002652 int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE);
dan6c75b392019-03-08 20:02:52 +00002653 windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0);
dan3f49c322019-04-03 16:27:44 +00002654 if( bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
dan6c75b392019-03-08 20:02:52 +00002655 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
danc8137502019-03-07 19:26:17 +00002656 }else if( pMWin->eStart==TK_FOLLOWING ){
2657 int addrStart;
2658 int addrBreak1;
2659 int addrBreak2;
2660 int addrBreak3;
dan6c75b392019-03-08 20:02:52 +00002661 windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
drhfc15f4c2019-03-28 13:03:41 +00002662 if( pMWin->eFrmType==TK_RANGE ){
dan72b9fdc2019-03-09 20:49:17 +00002663 addrStart = sqlite3VdbeCurrentAddr(v);
2664 addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1);
2665 addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
2666 }else
dan54975cd2019-03-07 20:47:46 +00002667 if( pMWin->eEnd==TK_UNBOUNDED ){
2668 addrStart = sqlite3VdbeCurrentAddr(v);
dan6c75b392019-03-08 20:02:52 +00002669 addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regStart, 1);
2670 addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, 0, 1);
dan54975cd2019-03-07 20:47:46 +00002671 }else{
2672 assert( pMWin->eEnd==TK_FOLLOWING );
2673 addrStart = sqlite3VdbeCurrentAddr(v);
dan6c75b392019-03-08 20:02:52 +00002674 addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 1);
2675 addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1);
dan54975cd2019-03-07 20:47:46 +00002676 }
danc8137502019-03-07 19:26:17 +00002677 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
2678 sqlite3VdbeJumpHere(v, addrBreak2);
2679 addrStart = sqlite3VdbeCurrentAddr(v);
dan6c75b392019-03-08 20:02:52 +00002680 addrBreak3 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
danc8137502019-03-07 19:26:17 +00002681 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
2682 sqlite3VdbeJumpHere(v, addrBreak1);
2683 sqlite3VdbeJumpHere(v, addrBreak3);
danb25a2142019-03-05 19:29:36 +00002684 }else{
dan00267b82019-03-06 21:04:11 +00002685 int addrBreak;
danc8137502019-03-07 19:26:17 +00002686 int addrStart;
dan6c75b392019-03-08 20:02:52 +00002687 windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
danc8137502019-03-07 19:26:17 +00002688 addrStart = sqlite3VdbeCurrentAddr(v);
dan6c75b392019-03-08 20:02:52 +00002689 addrBreak = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
2690 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
dan00267b82019-03-06 21:04:11 +00002691 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
2692 sqlite3VdbeJumpHere(v, addrBreak);
danb25a2142019-03-05 19:29:36 +00002693 }
danc8137502019-03-07 19:26:17 +00002694 sqlite3VdbeJumpHere(v, addrEmpty);
2695
dan6c75b392019-03-08 20:02:52 +00002696 sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr);
dan680f6e82019-03-04 21:07:11 +00002697 if( pMWin->pPartition ){
dana0f6b832019-03-14 16:36:20 +00002698 if( pMWin->regStartRowid ){
2699 sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid);
2700 sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid);
2701 }
dan680f6e82019-03-04 21:07:11 +00002702 sqlite3VdbeChangeP1(v, addrInteger, sqlite3VdbeCurrentAddr(v));
2703 sqlite3VdbeAddOp1(v, OP_Return, regFlushPart);
2704 }
2705}
2706
dan67a9b8e2018-06-22 20:51:35 +00002707#endif /* SQLITE_OMIT_WINDOWFUNC */