blob: f13ea8b027fd448bba4124ec23f564b35228a34e [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) { \
drhf9751072021-10-07 13:40:29 +0000584 nArg, (SQLITE_FUNC_BUILTIN|SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
dan1c5ed622018-06-05 16:16:17 +0000585 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) { \
drhf9751072021-10-07 13:40:29 +0000592 nArg, (SQLITE_FUNC_BUILTIN|SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
drh19dc4d42018-07-08 01:02:26 +0000593 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) { \
drhf9751072021-10-07 13:40:29 +0000601 nArg, (SQLITE_FUNC_BUILTIN|SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
drh19dc4d42018-07-08 01:02:26 +0000602 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 }
drh105dcaa2022-03-10 16:01:14 +0000727 pWin->pWFunc = 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;
dan62742fd2019-07-08 12:01:39 +0000739 Table *pTab;
danb556f262018-07-10 17:26:12 +0000740 Select *pSubSelect; /* Current sub-select, if any */
dandfa552f2018-06-02 21:04:28 +0000741};
742
danc0bb4452018-06-12 20:53:38 +0000743/*
744** Callback function used by selectWindowRewriteEList(). If necessary,
745** this function appends to the output expression-list and updates
746** expression (*ppExpr) in place.
747*/
dandfa552f2018-06-02 21:04:28 +0000748static int selectWindowRewriteExprCb(Walker *pWalker, Expr *pExpr){
749 struct WindowRewrite *p = pWalker->u.pRewrite;
750 Parse *pParse = pWalker->pParse;
drh55f66b32019-07-16 19:44:32 +0000751 assert( p!=0 );
752 assert( p->pWin!=0 );
dandfa552f2018-06-02 21:04:28 +0000753
danb556f262018-07-10 17:26:12 +0000754 /* If this function is being called from within a scalar sub-select
755 ** that used by the SELECT statement being processed, only process
756 ** TK_COLUMN expressions that refer to it (the outer SELECT). Do
757 ** not process aggregates or window functions at all, as they belong
758 ** to the scalar sub-select. */
759 if( p->pSubSelect ){
760 if( pExpr->op!=TK_COLUMN ){
761 return WRC_Continue;
762 }else{
763 int nSrc = p->pSrc->nSrc;
764 int i;
765 for(i=0; i<nSrc; i++){
766 if( pExpr->iTable==p->pSrc->a[i].iCursor ) break;
767 }
768 if( i==nSrc ) return WRC_Continue;
769 }
770 }
771
dandfa552f2018-06-02 21:04:28 +0000772 switch( pExpr->op ){
773
774 case TK_FUNCTION:
drheda079c2018-09-20 19:02:15 +0000775 if( !ExprHasProperty(pExpr, EP_WinFunc) ){
dandfa552f2018-06-02 21:04:28 +0000776 break;
777 }else{
778 Window *pWin;
779 for(pWin=p->pWin; pWin; pWin=pWin->pNextWin){
drheda079c2018-09-20 19:02:15 +0000780 if( pExpr->y.pWin==pWin ){
dan2a11bb22018-06-11 20:50:25 +0000781 assert( pWin->pOwner==pExpr );
dandfa552f2018-06-02 21:04:28 +0000782 return WRC_Prune;
783 }
784 }
785 }
drh08b92082020-08-10 14:18:00 +0000786 /* no break */ deliberate_fall_through
dandfa552f2018-06-02 21:04:28 +0000787
dan73925692018-06-12 18:40:17 +0000788 case TK_AGG_FUNCTION:
dandfa552f2018-06-02 21:04:28 +0000789 case TK_COLUMN: {
dan62be2dc2019-11-23 15:10:28 +0000790 int iCol = -1;
drhd22ecfd2021-04-06 13:56:46 +0000791 if( pParse->db->mallocFailed ) return WRC_Abort;
dan62be2dc2019-11-23 15:10:28 +0000792 if( p->pSub ){
793 int i;
794 for(i=0; i<p->pSub->nExpr; i++){
795 if( 0==sqlite3ExprCompare(0, p->pSub->a[i].pExpr, pExpr, -1) ){
796 iCol = i;
797 break;
798 }
799 }
800 }
801 if( iCol<0 ){
802 Expr *pDup = sqlite3ExprDup(pParse->db, pExpr, 0);
dan43170432019-12-27 16:25:56 +0000803 if( pDup && pDup->op==TK_AGG_FUNCTION ) pDup->op = TK_FUNCTION;
dan62be2dc2019-11-23 15:10:28 +0000804 p->pSub = sqlite3ExprListAppend(pParse, p->pSub, pDup);
805 }
dandfa552f2018-06-02 21:04:28 +0000806 if( p->pSub ){
dan27da9072020-07-13 15:20:27 +0000807 int f = pExpr->flags & EP_Collate;
dandfa552f2018-06-02 21:04:28 +0000808 assert( ExprHasProperty(pExpr, EP_Static)==0 );
809 ExprSetProperty(pExpr, EP_Static);
810 sqlite3ExprDelete(pParse->db, pExpr);
811 ExprClearProperty(pExpr, EP_Static);
812 memset(pExpr, 0, sizeof(Expr));
813
814 pExpr->op = TK_COLUMN;
dan62be2dc2019-11-23 15:10:28 +0000815 pExpr->iColumn = (iCol<0 ? p->pSub->nExpr-1: iCol);
dandfa552f2018-06-02 21:04:28 +0000816 pExpr->iTable = p->pWin->iEphCsr;
dan62742fd2019-07-08 12:01:39 +0000817 pExpr->y.pTab = p->pTab;
dan27da9072020-07-13 15:20:27 +0000818 pExpr->flags = f;
dandfa552f2018-06-02 21:04:28 +0000819 }
drha2f142d2019-11-23 16:34:40 +0000820 if( pParse->db->mallocFailed ) return WRC_Abort;
dandfa552f2018-06-02 21:04:28 +0000821 break;
822 }
823
824 default: /* no-op */
825 break;
826 }
827
828 return WRC_Continue;
829}
danc0bb4452018-06-12 20:53:38 +0000830static int selectWindowRewriteSelectCb(Walker *pWalker, Select *pSelect){
danb556f262018-07-10 17:26:12 +0000831 struct WindowRewrite *p = pWalker->u.pRewrite;
832 Select *pSave = p->pSubSelect;
833 if( pSave==pSelect ){
834 return WRC_Continue;
835 }else{
836 p->pSubSelect = pSelect;
837 sqlite3WalkSelect(pWalker, pSelect);
838 p->pSubSelect = pSave;
839 }
danc0bb4452018-06-12 20:53:38 +0000840 return WRC_Prune;
841}
dandfa552f2018-06-02 21:04:28 +0000842
danc0bb4452018-06-12 20:53:38 +0000843
844/*
845** Iterate through each expression in expression-list pEList. For each:
846**
847** * TK_COLUMN,
848** * aggregate function, or
849** * window function with a Window object that is not a member of the
danb556f262018-07-10 17:26:12 +0000850** Window list passed as the second argument (pWin).
danc0bb4452018-06-12 20:53:38 +0000851**
852** Append the node to output expression-list (*ppSub). And replace it
853** with a TK_COLUMN that reads the (N-1)th element of table
854** pWin->iEphCsr, where N is the number of elements in (*ppSub) after
855** appending the new one.
856*/
dan13b08bb2018-06-15 20:46:12 +0000857static void selectWindowRewriteEList(
dandfa552f2018-06-02 21:04:28 +0000858 Parse *pParse,
859 Window *pWin,
danb556f262018-07-10 17:26:12 +0000860 SrcList *pSrc,
dandfa552f2018-06-02 21:04:28 +0000861 ExprList *pEList, /* Rewrite expressions in this list */
dan62742fd2019-07-08 12:01:39 +0000862 Table *pTab,
dandfa552f2018-06-02 21:04:28 +0000863 ExprList **ppSub /* IN/OUT: Sub-select expression-list */
864){
865 Walker sWalker;
866 WindowRewrite sRewrite;
dandfa552f2018-06-02 21:04:28 +0000867
drh55f66b32019-07-16 19:44:32 +0000868 assert( pWin!=0 );
dandfa552f2018-06-02 21:04:28 +0000869 memset(&sWalker, 0, sizeof(Walker));
870 memset(&sRewrite, 0, sizeof(WindowRewrite));
871
872 sRewrite.pSub = *ppSub;
873 sRewrite.pWin = pWin;
danb556f262018-07-10 17:26:12 +0000874 sRewrite.pSrc = pSrc;
dan62742fd2019-07-08 12:01:39 +0000875 sRewrite.pTab = pTab;
dandfa552f2018-06-02 21:04:28 +0000876
877 sWalker.pParse = pParse;
878 sWalker.xExprCallback = selectWindowRewriteExprCb;
879 sWalker.xSelectCallback = selectWindowRewriteSelectCb;
880 sWalker.u.pRewrite = &sRewrite;
881
dan13b08bb2018-06-15 20:46:12 +0000882 (void)sqlite3WalkExprList(&sWalker, pEList);
dandfa552f2018-06-02 21:04:28 +0000883
884 *ppSub = sRewrite.pSub;
dandfa552f2018-06-02 21:04:28 +0000885}
886
danc0bb4452018-06-12 20:53:38 +0000887/*
888** Append a copy of each expression in expression-list pAppend to
889** expression list pList. Return a pointer to the result list.
890*/
dandfa552f2018-06-02 21:04:28 +0000891static ExprList *exprListAppendList(
892 Parse *pParse, /* Parsing context */
893 ExprList *pList, /* List to which to append. Might be NULL */
dan08f6de72019-05-10 14:26:32 +0000894 ExprList *pAppend, /* List of values to append. Might be NULL */
895 int bIntToNull
dandfa552f2018-06-02 21:04:28 +0000896){
897 if( pAppend ){
898 int i;
899 int nInit = pList ? pList->nExpr : 0;
900 for(i=0; i<pAppend->nExpr; i++){
drh57f90182021-04-03 23:30:33 +0000901 sqlite3 *db = pParse->db;
902 Expr *pDup = sqlite3ExprDup(db, pAppend->a[i].pExpr, 0);
drh4c4a2572021-04-06 12:50:24 +0000903 if( db->mallocFailed ){
904 sqlite3ExprDelete(db, pDup);
905 break;
906 }
907 if( bIntToNull ){
danefa78882020-05-11 10:55:24 +0000908 int iDummy;
909 Expr *pSub;
dana261c022021-06-23 11:12:48 +0000910 pSub = sqlite3ExprSkipCollateAndLikely(pDup);
danefa78882020-05-11 10:55:24 +0000911 if( sqlite3ExprIsInteger(pSub, &iDummy) ){
912 pSub->op = TK_NULL;
913 pSub->flags &= ~(EP_IntValue|EP_IsTrue|EP_IsFalse);
914 pSub->u.zToken = 0;
915 }
dan08f6de72019-05-10 14:26:32 +0000916 }
dandfa552f2018-06-02 21:04:28 +0000917 pList = sqlite3ExprListAppend(pParse, pList, pDup);
drhd88fd532022-05-02 20:49:30 +0000918 if( pList ) pList->a[nInit+i].fg.sortFlags = pAppend->a[i].fg.sortFlags;
dandfa552f2018-06-02 21:04:28 +0000919 }
920 }
921 return pList;
922}
923
924/*
drhc37577b2020-05-24 03:38:37 +0000925** When rewriting a query, if the new subquery in the FROM clause
926** contains TK_AGG_FUNCTION nodes that refer to an outer query,
927** then we have to increase the Expr->op2 values of those nodes
928** due to the extra subquery layer that was added.
929**
930** See also the incrAggDepth() routine in resolve.c
931*/
932static int sqlite3WindowExtraAggFuncDepth(Walker *pWalker, Expr *pExpr){
933 if( pExpr->op==TK_AGG_FUNCTION
934 && pExpr->op2>=pWalker->walkerDepth
935 ){
936 pExpr->op2++;
937 }
938 return WRC_Continue;
939}
940
drh4752bbd2021-05-07 15:46:36 +0000941static int disallowAggregatesInOrderByCb(Walker *pWalker, Expr *pExpr){
942 if( pExpr->op==TK_AGG_FUNCTION && pExpr->pAggInfo==0 ){
drhf9751072021-10-07 13:40:29 +0000943 assert( !ExprHasProperty(pExpr, EP_IntValue) );
944 sqlite3ErrorMsg(pWalker->pParse,
drh4752bbd2021-05-07 15:46:36 +0000945 "misuse of aggregate: %s()", pExpr->u.zToken);
946 }
947 return WRC_Continue;
948}
949
drhc37577b2020-05-24 03:38:37 +0000950/*
dandfa552f2018-06-02 21:04:28 +0000951** If the SELECT statement passed as the second argument does not invoke
952** any SQL window functions, this function is a no-op. Otherwise, it
953** rewrites the SELECT statement so that window function xStep functions
danc0bb4452018-06-12 20:53:38 +0000954** are invoked in the correct order as described under "SELECT REWRITING"
955** at the top of this file.
dandfa552f2018-06-02 21:04:28 +0000956*/
957int sqlite3WindowRewrite(Parse *pParse, Select *p){
958 int rc = SQLITE_OK;
drh5e121a52022-03-10 16:26:00 +0000959 if( p->pWin
960 && p->pPrior==0
961 && ALWAYS((p->selFlags & SF_WinRewrite)==0)
drhfde30432022-03-10 21:04:49 +0000962 && ALWAYS(!IN_RENAME_OBJECT)
drh5e121a52022-03-10 16:26:00 +0000963 ){
dandfa552f2018-06-02 21:04:28 +0000964 Vdbe *v = sqlite3GetVdbe(pParse);
dandfa552f2018-06-02 21:04:28 +0000965 sqlite3 *db = pParse->db;
966 Select *pSub = 0; /* The subquery */
967 SrcList *pSrc = p->pSrc;
968 Expr *pWhere = p->pWhere;
969 ExprList *pGroupBy = p->pGroupBy;
970 Expr *pHaving = p->pHaving;
971 ExprList *pSort = 0;
972
973 ExprList *pSublist = 0; /* Expression list for sub-query */
drh067b92b2020-06-19 15:24:12 +0000974 Window *pMWin = p->pWin; /* Main window object */
dandfa552f2018-06-02 21:04:28 +0000975 Window *pWin; /* Window object iterator */
dan62742fd2019-07-08 12:01:39 +0000976 Table *pTab;
drh89636622020-06-07 17:33:18 +0000977 Walker w;
978
dan553948e2020-03-16 18:52:53 +0000979 u32 selFlags = p->selFlags;
dan62742fd2019-07-08 12:01:39 +0000980
981 pTab = sqlite3DbMallocZero(db, sizeof(Table));
982 if( pTab==0 ){
drh86541862019-12-19 20:37:32 +0000983 return sqlite3ErrorToParser(db, SQLITE_NOMEM);
dan62742fd2019-07-08 12:01:39 +0000984 }
drh89636622020-06-07 17:33:18 +0000985 sqlite3AggInfoPersistWalkerInit(&w, pParse);
986 sqlite3WalkSelect(&w, p);
drh4752bbd2021-05-07 15:46:36 +0000987 if( (p->selFlags & SF_Aggregate)==0 ){
988 w.xExprCallback = disallowAggregatesInOrderByCb;
dan3d691fd2021-05-19 14:49:51 +0000989 w.xSelectCallback = 0;
drh4752bbd2021-05-07 15:46:36 +0000990 sqlite3WalkExprList(&w, p->pOrderBy);
991 }
dandfa552f2018-06-02 21:04:28 +0000992
993 p->pSrc = 0;
994 p->pWhere = 0;
995 p->pGroupBy = 0;
996 p->pHaving = 0;
dan62742fd2019-07-08 12:01:39 +0000997 p->selFlags &= ~SF_Aggregate;
drhba016342019-11-14 13:24:04 +0000998 p->selFlags |= SF_WinRewrite;
dandfa552f2018-06-02 21:04:28 +0000999
danf02cdd32018-06-27 19:48:50 +00001000 /* Create the ORDER BY clause for the sub-select. This is the concatenation
1001 ** of the window PARTITION and ORDER BY clauses. Then, if this makes it
1002 ** redundant, remove the ORDER BY from the parent SELECT. */
dand8d2fb92019-12-27 15:31:47 +00001003 pSort = exprListAppendList(pParse, 0, pMWin->pPartition, 1);
dan08f6de72019-05-10 14:26:32 +00001004 pSort = exprListAppendList(pParse, pSort, pMWin->pOrderBy, 1);
dan0e3c50c2019-08-07 17:45:37 +00001005 if( pSort && p->pOrderBy && p->pOrderBy->nExpr<=pSort->nExpr ){
1006 int nSave = pSort->nExpr;
1007 pSort->nExpr = p->pOrderBy->nExpr;
danf02cdd32018-06-27 19:48:50 +00001008 if( sqlite3ExprListCompare(pSort, p->pOrderBy, -1)==0 ){
1009 sqlite3ExprListDelete(db, p->pOrderBy);
1010 p->pOrderBy = 0;
1011 }
dan0e3c50c2019-08-07 17:45:37 +00001012 pSort->nExpr = nSave;
danf02cdd32018-06-27 19:48:50 +00001013 }
1014
dandfa552f2018-06-02 21:04:28 +00001015 /* Assign a cursor number for the ephemeral table used to buffer rows.
1016 ** The OpenEphemeral instruction is coded later, after it is known how
1017 ** many columns the table will have. */
1018 pMWin->iEphCsr = pParse->nTab++;
dan680f6e82019-03-04 21:07:11 +00001019 pParse->nTab += 3;
dandfa552f2018-06-02 21:04:28 +00001020
dan62742fd2019-07-08 12:01:39 +00001021 selectWindowRewriteEList(pParse, pMWin, pSrc, p->pEList, pTab, &pSublist);
1022 selectWindowRewriteEList(pParse, pMWin, pSrc, p->pOrderBy, pTab, &pSublist);
dandfa552f2018-06-02 21:04:28 +00001023 pMWin->nBufferCol = (pSublist ? pSublist->nExpr : 0);
1024
danf02cdd32018-06-27 19:48:50 +00001025 /* Append the PARTITION BY and ORDER BY expressions to the to the
1026 ** sub-select expression list. They are required to figure out where
1027 ** boundaries for partitions and sets of peer rows lie. */
dan08f6de72019-05-10 14:26:32 +00001028 pSublist = exprListAppendList(pParse, pSublist, pMWin->pPartition, 0);
1029 pSublist = exprListAppendList(pParse, pSublist, pMWin->pOrderBy, 0);
dandfa552f2018-06-02 21:04:28 +00001030
1031 /* Append the arguments passed to each window function to the
1032 ** sub-select expression list. Also allocate two registers for each
1033 ** window function - one for the accumulator, another for interim
1034 ** results. */
1035 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
drha4eeccd2021-10-07 17:43:30 +00001036 ExprList *pArgs;
1037 assert( ExprUseXList(pWin->pOwner) );
drh5e121a52022-03-10 16:26:00 +00001038 assert( pWin->pWFunc!=0 );
drha4eeccd2021-10-07 17:43:30 +00001039 pArgs = pWin->pOwner->x.pList;
drh105dcaa2022-03-10 16:01:14 +00001040 if( pWin->pWFunc->funcFlags & SQLITE_FUNC_SUBTYPE ){
dane2ba6df2019-09-07 18:20:43 +00001041 selectWindowRewriteEList(pParse, pMWin, pSrc, pArgs, pTab, &pSublist);
1042 pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);
1043 pWin->bExprArgs = 1;
1044 }else{
1045 pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);
1046 pSublist = exprListAppendList(pParse, pSublist, pArgs, 0);
1047 }
dan8b985602018-06-09 17:43:45 +00001048 if( pWin->pFilter ){
1049 Expr *pFilter = sqlite3ExprDup(db, pWin->pFilter, 0);
1050 pSublist = sqlite3ExprListAppend(pParse, pSublist, pFilter);
1051 }
dandfa552f2018-06-02 21:04:28 +00001052 pWin->regAccum = ++pParse->nMem;
1053 pWin->regResult = ++pParse->nMem;
1054 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
1055 }
1056
dan9c277582018-06-20 09:23:49 +00001057 /* If there is no ORDER BY or PARTITION BY clause, and the window
1058 ** function accepts zero arguments, and there are no other columns
1059 ** selected (e.g. "SELECT row_number() OVER () FROM t1"), it is possible
1060 ** that pSublist is still NULL here. Add a constant expression here to
1061 ** keep everything legal in this case.
1062 */
1063 if( pSublist==0 ){
1064 pSublist = sqlite3ExprListAppend(pParse, 0,
drh5776ee52019-09-23 12:38:10 +00001065 sqlite3Expr(db, TK_INTEGER, "0")
dan9c277582018-06-20 09:23:49 +00001066 );
1067 }
1068
dandfa552f2018-06-02 21:04:28 +00001069 pSub = sqlite3SelectNew(
1070 pParse, pSublist, pSrc, pWhere, pGroupBy, pHaving, pSort, 0, 0
1071 );
drh9216de82020-06-11 00:57:09 +00001072 SELECTTRACE(1,pParse,pSub,
1073 ("New window-function subquery in FROM clause of (%u/%p)\n",
1074 p->selId, p));
drh29c992c2019-01-17 15:40:41 +00001075 p->pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
drh82456a62021-09-13 18:16:15 +00001076 assert( pSub!=0 || p->pSrc==0 ); /* Due to db->mallocFailed test inside
1077 ** of sqlite3DbMallocRawNN() called from
1078 ** sqlite3SrcListAppend() */
dandfa552f2018-06-02 21:04:28 +00001079 if( p->pSrc ){
dan62742fd2019-07-08 12:01:39 +00001080 Table *pTab2;
dandfa552f2018-06-02 21:04:28 +00001081 p->pSrc->a[0].pSelect = pSub;
1082 sqlite3SrcListAssignCursors(pParse, p->pSrc);
drhbb301232021-07-15 19:29:43 +00001083 pSub->selFlags |= SF_Expanded|SF_OrderByReqd;
drh96fb16e2019-08-06 14:37:24 +00001084 pTab2 = sqlite3ResultSetOfSelect(pParse, pSub, SQLITE_AFF_NONE);
dan553948e2020-03-16 18:52:53 +00001085 pSub->selFlags |= (selFlags & SF_Aggregate);
dan62742fd2019-07-08 12:01:39 +00001086 if( pTab2==0 ){
drha9ebfe22019-12-25 23:54:21 +00001087 /* Might actually be some other kind of error, but in that case
1088 ** pParse->nErr will be set, so if SQLITE_NOMEM is set, we will get
1089 ** the correct error message regardless. */
dandfa552f2018-06-02 21:04:28 +00001090 rc = SQLITE_NOMEM;
1091 }else{
dan62742fd2019-07-08 12:01:39 +00001092 memcpy(pTab, pTab2, sizeof(Table));
1093 pTab->tabFlags |= TF_Ephemeral;
1094 p->pSrc->a[0].pTab = pTab;
1095 pTab = pTab2;
drhc37577b2020-05-24 03:38:37 +00001096 memset(&w, 0, sizeof(w));
1097 w.xExprCallback = sqlite3WindowExtraAggFuncDepth;
1098 w.xSelectCallback = sqlite3WalkerDepthIncrease;
1099 w.xSelectCallback2 = sqlite3WalkerDepthDecrease;
1100 sqlite3WalkSelect(&w, pSub);
dandfa552f2018-06-02 21:04:28 +00001101 }
dan6fde1792018-06-15 19:01:35 +00001102 }else{
1103 sqlite3SelectDelete(db, pSub);
1104 }
1105 if( db->mallocFailed ) rc = SQLITE_NOMEM;
drh6d64b4a2021-11-07 23:33:01 +00001106
1107 /* Defer deleting the temporary table pTab because if an error occurred,
1108 ** there could still be references to that table embedded in the
1109 ** result-set or ORDER BY clause of the SELECT statement p. */
1110 sqlite3ParserAddCleanup(pParse, sqlite3DbFree, pTab);
dandfa552f2018-06-02 21:04:28 +00001111 }
1112
drh1da88b52022-01-24 19:38:56 +00001113 assert( rc==SQLITE_OK || pParse->nErr!=0 );
dandfa552f2018-06-02 21:04:28 +00001114 return rc;
1115}
1116
danc0bb4452018-06-12 20:53:38 +00001117/*
drhe2094572019-07-22 19:01:38 +00001118** Unlink the Window object from the Select to which it is attached,
1119** if it is attached.
1120*/
1121void sqlite3WindowUnlinkFromSelect(Window *p){
1122 if( p->ppThis ){
1123 *p->ppThis = p->pNextWin;
1124 if( p->pNextWin ) p->pNextWin->ppThis = p->ppThis;
1125 p->ppThis = 0;
1126 }
1127}
1128
1129/*
danc0bb4452018-06-12 20:53:38 +00001130** Free the Window object passed as the second argument.
1131*/
dan86fb6e12018-05-16 20:58:07 +00001132void sqlite3WindowDelete(sqlite3 *db, Window *p){
1133 if( p ){
drhe2094572019-07-22 19:01:38 +00001134 sqlite3WindowUnlinkFromSelect(p);
dan86fb6e12018-05-16 20:58:07 +00001135 sqlite3ExprDelete(db, p->pFilter);
1136 sqlite3ExprListDelete(db, p->pPartition);
1137 sqlite3ExprListDelete(db, p->pOrderBy);
1138 sqlite3ExprDelete(db, p->pEnd);
1139 sqlite3ExprDelete(db, p->pStart);
dane3bf6322018-06-08 20:58:27 +00001140 sqlite3DbFree(db, p->zName);
dane7c9ca42019-02-16 17:27:51 +00001141 sqlite3DbFree(db, p->zBase);
dan86fb6e12018-05-16 20:58:07 +00001142 sqlite3DbFree(db, p);
1143 }
1144}
1145
danc0bb4452018-06-12 20:53:38 +00001146/*
1147** Free the linked list of Window objects starting at the second argument.
1148*/
dane3bf6322018-06-08 20:58:27 +00001149void sqlite3WindowListDelete(sqlite3 *db, Window *p){
1150 while( p ){
1151 Window *pNext = p->pNextWin;
1152 sqlite3WindowDelete(db, p);
1153 p = pNext;
1154 }
1155}
1156
danc0bb4452018-06-12 20:53:38 +00001157/*
drhe4984a22018-07-06 17:19:20 +00001158** The argument expression is an PRECEDING or FOLLOWING offset. The
1159** value should be a non-negative integer. If the value is not a
1160** constant, change it to NULL. The fact that it is then a non-negative
1161** integer will be caught later. But it is important not to leave
1162** variable values in the expression tree.
1163*/
1164static Expr *sqlite3WindowOffsetExpr(Parse *pParse, Expr *pExpr){
1165 if( 0==sqlite3ExprIsConstant(pExpr) ){
danfb8ac322019-01-16 12:05:22 +00001166 if( IN_RENAME_OBJECT ) sqlite3RenameExprUnmap(pParse, pExpr);
drhe4984a22018-07-06 17:19:20 +00001167 sqlite3ExprDelete(pParse->db, pExpr);
1168 pExpr = sqlite3ExprAlloc(pParse->db, TK_NULL, 0, 0);
1169 }
1170 return pExpr;
1171}
1172
1173/*
1174** Allocate and return a new Window object describing a Window Definition.
danc0bb4452018-06-12 20:53:38 +00001175*/
dan86fb6e12018-05-16 20:58:07 +00001176Window *sqlite3WindowAlloc(
drhe4984a22018-07-06 17:19:20 +00001177 Parse *pParse, /* Parsing context */
drhfc15f4c2019-03-28 13:03:41 +00001178 int eType, /* Frame type. TK_RANGE, TK_ROWS, TK_GROUPS, or 0 */
drhe4984a22018-07-06 17:19:20 +00001179 int eStart, /* Start type: CURRENT, PRECEDING, FOLLOWING, UNBOUNDED */
1180 Expr *pStart, /* Start window size if TK_PRECEDING or FOLLOWING */
1181 int eEnd, /* End type: CURRENT, FOLLOWING, TK_UNBOUNDED, PRECEDING */
dand35300f2019-03-14 20:53:21 +00001182 Expr *pEnd, /* End window size if TK_FOLLOWING or PRECEDING */
1183 u8 eExclude /* EXCLUDE clause */
dan86fb6e12018-05-16 20:58:07 +00001184){
dan7a606e12018-07-05 18:34:53 +00001185 Window *pWin = 0;
dane7c9ca42019-02-16 17:27:51 +00001186 int bImplicitFrame = 0;
dan7a606e12018-07-05 18:34:53 +00001187
drhe4984a22018-07-06 17:19:20 +00001188 /* Parser assures the following: */
dan6c75b392019-03-08 20:02:52 +00001189 assert( eType==0 || eType==TK_RANGE || eType==TK_ROWS || eType==TK_GROUPS );
drhe4984a22018-07-06 17:19:20 +00001190 assert( eStart==TK_CURRENT || eStart==TK_PRECEDING
1191 || eStart==TK_UNBOUNDED || eStart==TK_FOLLOWING );
1192 assert( eEnd==TK_CURRENT || eEnd==TK_FOLLOWING
1193 || eEnd==TK_UNBOUNDED || eEnd==TK_PRECEDING );
1194 assert( (eStart==TK_PRECEDING || eStart==TK_FOLLOWING)==(pStart!=0) );
1195 assert( (eEnd==TK_FOLLOWING || eEnd==TK_PRECEDING)==(pEnd!=0) );
1196
dane7c9ca42019-02-16 17:27:51 +00001197 if( eType==0 ){
1198 bImplicitFrame = 1;
1199 eType = TK_RANGE;
1200 }
drhe4984a22018-07-06 17:19:20 +00001201
drhe4984a22018-07-06 17:19:20 +00001202 /* Additionally, the
dan5d764ac2018-07-06 14:15:49 +00001203 ** starting boundary type may not occur earlier in the following list than
1204 ** the ending boundary type:
1205 **
1206 ** UNBOUNDED PRECEDING
1207 ** <expr> PRECEDING
1208 ** CURRENT ROW
1209 ** <expr> FOLLOWING
1210 ** UNBOUNDED FOLLOWING
1211 **
1212 ** The parser ensures that "UNBOUNDED PRECEDING" cannot be used as an ending
1213 ** boundary, and than "UNBOUNDED FOLLOWING" cannot be used as a starting
1214 ** frame boundary.
1215 */
drhe4984a22018-07-06 17:19:20 +00001216 if( (eStart==TK_CURRENT && eEnd==TK_PRECEDING)
dan5d764ac2018-07-06 14:15:49 +00001217 || (eStart==TK_FOLLOWING && (eEnd==TK_PRECEDING || eEnd==TK_CURRENT))
1218 ){
dan72b9fdc2019-03-09 20:49:17 +00001219 sqlite3ErrorMsg(pParse, "unsupported frame specification");
drhe4984a22018-07-06 17:19:20 +00001220 goto windowAllocErr;
dan7a606e12018-07-05 18:34:53 +00001221 }
dan86fb6e12018-05-16 20:58:07 +00001222
drhe4984a22018-07-06 17:19:20 +00001223 pWin = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
1224 if( pWin==0 ) goto windowAllocErr;
drhfc15f4c2019-03-28 13:03:41 +00001225 pWin->eFrmType = eType;
drhe4984a22018-07-06 17:19:20 +00001226 pWin->eStart = eStart;
1227 pWin->eEnd = eEnd;
drh94809082019-04-02 17:45:56 +00001228 if( eExclude==0 && OptimizationDisabled(pParse->db, SQLITE_WindowFunc) ){
dan108e6b22019-03-18 18:55:35 +00001229 eExclude = TK_NO;
1230 }
dand35300f2019-03-14 20:53:21 +00001231 pWin->eExclude = eExclude;
dane7c9ca42019-02-16 17:27:51 +00001232 pWin->bImplicitFrame = bImplicitFrame;
drhe4984a22018-07-06 17:19:20 +00001233 pWin->pEnd = sqlite3WindowOffsetExpr(pParse, pEnd);
1234 pWin->pStart = sqlite3WindowOffsetExpr(pParse, pStart);
dan86fb6e12018-05-16 20:58:07 +00001235 return pWin;
drhe4984a22018-07-06 17:19:20 +00001236
1237windowAllocErr:
1238 sqlite3ExprDelete(pParse->db, pEnd);
1239 sqlite3ExprDelete(pParse->db, pStart);
1240 return 0;
dan86fb6e12018-05-16 20:58:07 +00001241}
1242
danc0bb4452018-06-12 20:53:38 +00001243/*
dane7c9ca42019-02-16 17:27:51 +00001244** Attach PARTITION and ORDER BY clauses pPartition and pOrderBy to window
1245** pWin. Also, if parameter pBase is not NULL, set pWin->zBase to the
1246** equivalent nul-terminated string.
1247*/
1248Window *sqlite3WindowAssemble(
1249 Parse *pParse,
1250 Window *pWin,
1251 ExprList *pPartition,
1252 ExprList *pOrderBy,
1253 Token *pBase
1254){
1255 if( pWin ){
1256 pWin->pPartition = pPartition;
1257 pWin->pOrderBy = pOrderBy;
1258 if( pBase ){
1259 pWin->zBase = sqlite3DbStrNDup(pParse->db, pBase->z, pBase->n);
1260 }
1261 }else{
1262 sqlite3ExprListDelete(pParse->db, pPartition);
1263 sqlite3ExprListDelete(pParse->db, pOrderBy);
1264 }
1265 return pWin;
1266}
1267
1268/*
1269** Window *pWin has just been created from a WINDOW clause. Tokne pBase
1270** is the base window. Earlier windows from the same WINDOW clause are
1271** stored in the linked list starting at pWin->pNextWin. This function
1272** either updates *pWin according to the base specification, or else
1273** leaves an error in pParse.
1274*/
1275void sqlite3WindowChain(Parse *pParse, Window *pWin, Window *pList){
1276 if( pWin->zBase ){
1277 sqlite3 *db = pParse->db;
1278 Window *pExist = windowFind(pParse, pList, pWin->zBase);
1279 if( pExist ){
1280 const char *zErr = 0;
1281 /* Check for errors */
1282 if( pWin->pPartition ){
1283 zErr = "PARTITION clause";
1284 }else if( pExist->pOrderBy && pWin->pOrderBy ){
1285 zErr = "ORDER BY clause";
1286 }else if( pExist->bImplicitFrame==0 ){
1287 zErr = "frame specification";
1288 }
1289 if( zErr ){
1290 sqlite3ErrorMsg(pParse,
1291 "cannot override %s of window: %s", zErr, pWin->zBase
1292 );
1293 }else{
1294 pWin->pPartition = sqlite3ExprListDup(db, pExist->pPartition, 0);
1295 if( pExist->pOrderBy ){
1296 assert( pWin->pOrderBy==0 );
1297 pWin->pOrderBy = sqlite3ExprListDup(db, pExist->pOrderBy, 0);
1298 }
1299 sqlite3DbFree(db, pWin->zBase);
1300 pWin->zBase = 0;
1301 }
1302 }
1303 }
1304}
1305
1306/*
danc0bb4452018-06-12 20:53:38 +00001307** Attach window object pWin to expression p.
1308*/
dan4f9adee2019-07-13 16:22:50 +00001309void sqlite3WindowAttach(Parse *pParse, Expr *p, Window *pWin){
dan86fb6e12018-05-16 20:58:07 +00001310 if( p ){
drheda079c2018-09-20 19:02:15 +00001311 assert( p->op==TK_FUNCTION );
dan4f9adee2019-07-13 16:22:50 +00001312 assert( pWin );
1313 p->y.pWin = pWin;
1314 ExprSetProperty(p, EP_WinFunc);
1315 pWin->pOwner = p;
1316 if( (p->flags & EP_Distinct) && pWin->eFrmType!=TK_FILTER ){
1317 sqlite3ErrorMsg(pParse,
1318 "DISTINCT is not supported for window functions"
1319 );
dane33f6e72018-07-06 07:42:42 +00001320 }
dan86fb6e12018-05-16 20:58:07 +00001321 }else{
1322 sqlite3WindowDelete(pParse->db, pWin);
1323 }
1324}
dane2f781b2018-05-17 19:24:08 +00001325
1326/*
dana3fcc002019-08-15 13:53:22 +00001327** Possibly link window pWin into the list at pSel->pWin (window functions
1328** to be processed as part of SELECT statement pSel). The window is linked
1329** in if either (a) there are no other windows already linked to this
1330** SELECT, or (b) the windows already linked use a compatible window frame.
1331*/
1332void sqlite3WindowLink(Select *pSel, Window *pWin){
dan903fdd42021-02-22 20:56:13 +00001333 if( pSel ){
1334 if( 0==pSel->pWin || 0==sqlite3WindowCompare(0, pSel->pWin, pWin, 0) ){
1335 pWin->pNextWin = pSel->pWin;
1336 if( pSel->pWin ){
1337 pSel->pWin->ppThis = &pWin->pNextWin;
1338 }
1339 pSel->pWin = pWin;
1340 pWin->ppThis = &pSel->pWin;
1341 }else{
1342 if( sqlite3ExprListCompare(pWin->pPartition, pSel->pWin->pPartition,-1) ){
1343 pSel->selFlags |= SF_MultiPart;
1344 }
dana3fcc002019-08-15 13:53:22 +00001345 }
dana3fcc002019-08-15 13:53:22 +00001346 }
1347}
1348
1349/*
danfbb6e9f2020-01-09 20:11:29 +00001350** Return 0 if the two window objects are identical, 1 if they are
1351** different, or 2 if it cannot be determined if the objects are identical
1352** or not. Identical window objects can be processed in a single scan.
dane2f781b2018-05-17 19:24:08 +00001353*/
drh1580d502021-09-25 17:07:57 +00001354int sqlite3WindowCompare(
1355 const Parse *pParse,
1356 const Window *p1,
1357 const Window *p2,
1358 int bFilter
1359){
danfbb6e9f2020-01-09 20:11:29 +00001360 int res;
drha2f142d2019-11-23 16:34:40 +00001361 if( NEVER(p1==0) || NEVER(p2==0) ) return 1;
drhfc15f4c2019-03-28 13:03:41 +00001362 if( p1->eFrmType!=p2->eFrmType ) return 1;
dane2f781b2018-05-17 19:24:08 +00001363 if( p1->eStart!=p2->eStart ) return 1;
1364 if( p1->eEnd!=p2->eEnd ) return 1;
dana0f6b832019-03-14 16:36:20 +00001365 if( p1->eExclude!=p2->eExclude ) return 1;
dane2f781b2018-05-17 19:24:08 +00001366 if( sqlite3ExprCompare(pParse, p1->pStart, p2->pStart, -1) ) return 1;
1367 if( sqlite3ExprCompare(pParse, p1->pEnd, p2->pEnd, -1) ) return 1;
danfbb6e9f2020-01-09 20:11:29 +00001368 if( (res = sqlite3ExprListCompare(p1->pPartition, p2->pPartition, -1)) ){
1369 return res;
1370 }
1371 if( (res = sqlite3ExprListCompare(p1->pOrderBy, p2->pOrderBy, -1)) ){
1372 return res;
1373 }
dan4f9adee2019-07-13 16:22:50 +00001374 if( bFilter ){
danfbb6e9f2020-01-09 20:11:29 +00001375 if( (res = sqlite3ExprCompare(pParse, p1->pFilter, p2->pFilter, -1)) ){
1376 return res;
1377 }
dan4f9adee2019-07-13 16:22:50 +00001378 }
dane2f781b2018-05-17 19:24:08 +00001379 return 0;
1380}
1381
dan13078ca2018-06-13 20:29:38 +00001382
1383/*
1384** This is called by code in select.c before it calls sqlite3WhereBegin()
1385** to begin iterating through the sub-query results. It is used to allocate
1386** and initialize registers and cursors used by sqlite3WindowCodeStep().
1387*/
dan4ea562e2020-01-01 20:17:15 +00001388void sqlite3WindowCodeInit(Parse *pParse, Select *pSelect){
1389 int nEphExpr = pSelect->pSrc->a[0].pSelect->pEList->nExpr;
1390 Window *pMWin = pSelect->pWin;
danc9a86682018-05-30 20:44:58 +00001391 Window *pWin;
dan13078ca2018-06-13 20:29:38 +00001392 Vdbe *v = sqlite3GetVdbe(pParse);
danb6f2dea2019-03-13 17:20:27 +00001393
dan4ea562e2020-01-01 20:17:15 +00001394 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pMWin->iEphCsr, nEphExpr);
1395 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+1, pMWin->iEphCsr);
1396 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+2, pMWin->iEphCsr);
1397 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+3, pMWin->iEphCsr);
1398
danb6f2dea2019-03-13 17:20:27 +00001399 /* Allocate registers to use for PARTITION BY values, if any. Initialize
1400 ** said registers to NULL. */
1401 if( pMWin->pPartition ){
1402 int nExpr = pMWin->pPartition->nExpr;
dan13078ca2018-06-13 20:29:38 +00001403 pMWin->regPart = pParse->nMem+1;
danb6f2dea2019-03-13 17:20:27 +00001404 pParse->nMem += nExpr;
1405 sqlite3VdbeAddOp3(v, OP_Null, 0, pMWin->regPart, pMWin->regPart+nExpr-1);
dan13078ca2018-06-13 20:29:38 +00001406 }
1407
danbf845152019-03-16 10:15:24 +00001408 pMWin->regOne = ++pParse->nMem;
1409 sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regOne);
dan680f6e82019-03-04 21:07:11 +00001410
dana0f6b832019-03-14 16:36:20 +00001411 if( pMWin->eExclude ){
1412 pMWin->regStartRowid = ++pParse->nMem;
1413 pMWin->regEndRowid = ++pParse->nMem;
1414 pMWin->csrApp = pParse->nTab++;
1415 sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid);
1416 sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid);
1417 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->csrApp, pMWin->iEphCsr);
1418 return;
1419 }
1420
danc9a86682018-05-30 20:44:58 +00001421 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
drh105dcaa2022-03-10 16:01:14 +00001422 FuncDef *p = pWin->pWFunc;
danec891fd2018-06-06 20:51:02 +00001423 if( (p->funcFlags & SQLITE_FUNC_MINMAX) && pWin->eStart!=TK_UNBOUNDED ){
dan9a947222018-06-14 19:06:36 +00001424 /* The inline versions of min() and max() require a single ephemeral
1425 ** table and 3 registers. The registers are used as follows:
1426 **
1427 ** regApp+0: slot to copy min()/max() argument to for MakeRecord
1428 ** regApp+1: integer value used to ensure keys are unique
1429 ** regApp+2: output of MakeRecord
1430 */
drha4eeccd2021-10-07 17:43:30 +00001431 ExprList *pList;
1432 KeyInfo *pKeyInfo;
1433 assert( ExprUseXList(pWin->pOwner) );
1434 pList = pWin->pOwner->x.pList;
1435 pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pList, 0, 0);
danc9a86682018-05-30 20:44:58 +00001436 pWin->csrApp = pParse->nTab++;
1437 pWin->regApp = pParse->nMem+1;
1438 pParse->nMem += 3;
drh105dcaa2022-03-10 16:01:14 +00001439 if( pKeyInfo && pWin->pWFunc->zName[1]=='i' ){
dan6e118922019-08-12 16:36:38 +00001440 assert( pKeyInfo->aSortFlags[0]==0 );
1441 pKeyInfo->aSortFlags[0] = KEYINFO_ORDER_DESC;
danc9a86682018-05-30 20:44:58 +00001442 }
1443 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pWin->csrApp, 2);
1444 sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
1445 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
1446 }
drh19dc4d42018-07-08 01:02:26 +00001447 else if( p->zName==nth_valueName || p->zName==first_valueName ){
danec891fd2018-06-06 20:51:02 +00001448 /* Allocate two registers at pWin->regApp. These will be used to
1449 ** store the start and end index of the current frame. */
danec891fd2018-06-06 20:51:02 +00001450 pWin->regApp = pParse->nMem+1;
1451 pWin->csrApp = pParse->nTab++;
1452 pParse->nMem += 2;
danec891fd2018-06-06 20:51:02 +00001453 sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
1454 }
drh19dc4d42018-07-08 01:02:26 +00001455 else if( p->zName==leadName || p->zName==lagName ){
danfe4e25a2018-06-07 20:08:59 +00001456 pWin->csrApp = pParse->nTab++;
1457 sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
1458 }
danc9a86682018-05-30 20:44:58 +00001459 }
1460}
1461
danbb407272019-03-12 18:28:51 +00001462#define WINDOW_STARTING_INT 0
1463#define WINDOW_ENDING_INT 1
1464#define WINDOW_NTH_VALUE_INT 2
1465#define WINDOW_STARTING_NUM 3
1466#define WINDOW_ENDING_NUM 4
1467
dan13078ca2018-06-13 20:29:38 +00001468/*
dana1a7e112018-07-09 13:31:18 +00001469** A "PRECEDING <expr>" (eCond==0) or "FOLLOWING <expr>" (eCond==1) or the
1470** value of the second argument to nth_value() (eCond==2) has just been
1471** evaluated and the result left in register reg. This function generates VM
1472** code to check that the value is a non-negative integer and throws an
1473** exception if it is not.
dan13078ca2018-06-13 20:29:38 +00001474*/
danbb407272019-03-12 18:28:51 +00001475static void windowCheckValue(Parse *pParse, int reg, int eCond){
danc3a20c12018-05-23 20:55:37 +00001476 static const char *azErr[] = {
1477 "frame starting offset must be a non-negative integer",
dana1a7e112018-07-09 13:31:18 +00001478 "frame ending offset must be a non-negative integer",
danbb407272019-03-12 18:28:51 +00001479 "second argument to nth_value must be a positive integer",
1480 "frame starting offset must be a non-negative number",
1481 "frame ending offset must be a non-negative number",
danc3a20c12018-05-23 20:55:37 +00001482 };
danbb407272019-03-12 18:28:51 +00001483 static int aOp[] = { OP_Ge, OP_Ge, OP_Gt, OP_Ge, OP_Ge };
danc3a20c12018-05-23 20:55:37 +00001484 Vdbe *v = sqlite3GetVdbe(pParse);
dan13078ca2018-06-13 20:29:38 +00001485 int regZero = sqlite3GetTempReg(pParse);
danbb407272019-03-12 18:28:51 +00001486 assert( eCond>=0 && eCond<ArraySize(azErr) );
danc3a20c12018-05-23 20:55:37 +00001487 sqlite3VdbeAddOp2(v, OP_Integer, 0, regZero);
dane5166e02019-03-19 11:56:39 +00001488 if( eCond>=WINDOW_STARTING_NUM ){
1489 int regString = sqlite3GetTempReg(pParse);
1490 sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC);
1491 sqlite3VdbeAddOp3(v, OP_Ge, regString, sqlite3VdbeCurrentAddr(v)+2, reg);
drh21826f42019-04-01 14:30:30 +00001492 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC|SQLITE_JUMPIFNULL);
drh6f883592019-03-30 20:37:04 +00001493 VdbeCoverage(v);
1494 assert( eCond==3 || eCond==4 );
1495 VdbeCoverageIf(v, eCond==3);
1496 VdbeCoverageIf(v, eCond==4);
dane5166e02019-03-19 11:56:39 +00001497 }else{
1498 sqlite3VdbeAddOp2(v, OP_MustBeInt, reg, sqlite3VdbeCurrentAddr(v)+2);
drh6f883592019-03-30 20:37:04 +00001499 VdbeCoverage(v);
1500 assert( eCond==0 || eCond==1 || eCond==2 );
1501 VdbeCoverageIf(v, eCond==0);
1502 VdbeCoverageIf(v, eCond==1);
1503 VdbeCoverageIf(v, eCond==2);
dane5166e02019-03-19 11:56:39 +00001504 }
dana1a7e112018-07-09 13:31:18 +00001505 sqlite3VdbeAddOp3(v, aOp[eCond], regZero, sqlite3VdbeCurrentAddr(v)+2, reg);
danb03786a2021-03-31 11:31:19 +00001506 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC);
drh21826f42019-04-01 14:30:30 +00001507 VdbeCoverageNeverNullIf(v, eCond==0); /* NULL case captured by */
1508 VdbeCoverageNeverNullIf(v, eCond==1); /* the OP_MustBeInt */
1509 VdbeCoverageNeverNullIf(v, eCond==2);
1510 VdbeCoverageNeverNullIf(v, eCond==3); /* NULL case caught by */
1511 VdbeCoverageNeverNullIf(v, eCond==4); /* the OP_Ge */
drh211a0852019-01-27 02:41:34 +00001512 sqlite3MayAbort(pParse);
danc3a20c12018-05-23 20:55:37 +00001513 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_ERROR, OE_Abort);
dana1a7e112018-07-09 13:31:18 +00001514 sqlite3VdbeAppendP4(v, (void*)azErr[eCond], P4_STATIC);
dan13078ca2018-06-13 20:29:38 +00001515 sqlite3ReleaseTempReg(pParse, regZero);
danc3a20c12018-05-23 20:55:37 +00001516}
1517
dan13078ca2018-06-13 20:29:38 +00001518/*
1519** Return the number of arguments passed to the window-function associated
1520** with the object passed as the only argument to this function.
1521*/
dan2a11bb22018-06-11 20:50:25 +00001522static int windowArgCount(Window *pWin){
drha4eeccd2021-10-07 17:43:30 +00001523 const ExprList *pList;
1524 assert( ExprUseXList(pWin->pOwner) );
1525 pList = pWin->pOwner->x.pList;
dan2a11bb22018-06-11 20:50:25 +00001526 return (pList ? pList->nExpr : 0);
1527}
1528
danc782a812019-03-15 20:46:19 +00001529typedef struct WindowCodeArg WindowCodeArg;
1530typedef struct WindowCsrAndReg WindowCsrAndReg;
dan1cac1762019-08-30 17:28:55 +00001531
1532/*
1533** See comments above struct WindowCodeArg.
1534*/
danc782a812019-03-15 20:46:19 +00001535struct WindowCsrAndReg {
dan1cac1762019-08-30 17:28:55 +00001536 int csr; /* Cursor number */
1537 int reg; /* First in array of peer values */
danc782a812019-03-15 20:46:19 +00001538};
1539
dan1cac1762019-08-30 17:28:55 +00001540/*
1541** A single instance of this structure is allocated on the stack by
1542** sqlite3WindowCodeStep() and a pointer to it passed to the various helper
1543** routines. This is to reduce the number of arguments required by each
1544** helper function.
1545**
1546** regArg:
1547** Each window function requires an accumulator register (just as an
1548** ordinary aggregate function does). This variable is set to the first
1549** in an array of accumulator registers - one for each window function
1550** in the WindowCodeArg.pMWin list.
1551**
1552** eDelete:
1553** The window functions implementation sometimes caches the input rows
1554** that it processes in a temporary table. If it is not zero, this
1555** variable indicates when rows may be removed from the temp table (in
1556** order to reduce memory requirements - it would always be safe just
1557** to leave them there). Possible values for eDelete are:
1558**
1559** WINDOW_RETURN_ROW:
1560** An input row can be discarded after it is returned to the caller.
1561**
1562** WINDOW_AGGINVERSE:
1563** An input row can be discarded after the window functions xInverse()
1564** callbacks have been invoked in it.
1565**
1566** WINDOW_AGGSTEP:
1567** An input row can be discarded after the window functions xStep()
1568** callbacks have been invoked in it.
1569**
1570** start,current,end
1571** Consider a window-frame similar to the following:
1572**
1573** (ORDER BY a, b GROUPS BETWEEN 2 PRECEDING AND 2 FOLLOWING)
1574**
1575** The windows functions implmentation caches the input rows in a temp
1576** table, sorted by "a, b" (it actually populates the cache lazily, and
1577** aggressively removes rows once they are no longer required, but that's
1578** a mere detail). It keeps three cursors open on the temp table. One
1579** (current) that points to the next row to return to the query engine
1580** once its window function values have been calculated. Another (end)
1581** points to the next row to call the xStep() method of each window function
1582** on (so that it is 2 groups ahead of current). And a third (start) that
1583** points to the next row to call the xInverse() method of each window
1584** function on.
1585**
1586** Each cursor (start, current and end) consists of a VDBE cursor
1587** (WindowCsrAndReg.csr) and an array of registers (starting at
1588** WindowCodeArg.reg) that always contains a copy of the peer values
1589** read from the corresponding cursor.
1590**
1591** Depending on the window-frame in question, all three cursors may not
1592** be required. In this case both WindowCodeArg.csr and reg are set to
1593** 0.
1594*/
danc782a812019-03-15 20:46:19 +00001595struct WindowCodeArg {
dan1cac1762019-08-30 17:28:55 +00001596 Parse *pParse; /* Parse context */
1597 Window *pMWin; /* First in list of functions being processed */
1598 Vdbe *pVdbe; /* VDBE object */
1599 int addrGosub; /* OP_Gosub to this address to return one row */
1600 int regGosub; /* Register used with OP_Gosub(addrGosub) */
1601 int regArg; /* First in array of accumulator registers */
1602 int eDelete; /* See above */
drh113a33c2021-04-24 23:40:05 +00001603 int regRowid;
danc782a812019-03-15 20:46:19 +00001604
1605 WindowCsrAndReg start;
1606 WindowCsrAndReg current;
1607 WindowCsrAndReg end;
1608};
1609
1610/*
danc782a812019-03-15 20:46:19 +00001611** Generate VM code to read the window frames peer values from cursor csr into
1612** an array of registers starting at reg.
1613*/
1614static void windowReadPeerValues(
1615 WindowCodeArg *p,
1616 int csr,
1617 int reg
1618){
1619 Window *pMWin = p->pMWin;
1620 ExprList *pOrderBy = pMWin->pOrderBy;
1621 if( pOrderBy ){
1622 Vdbe *v = sqlite3GetVdbe(p->pParse);
1623 ExprList *pPart = pMWin->pPartition;
1624 int iColOff = pMWin->nBufferCol + (pPart ? pPart->nExpr : 0);
1625 int i;
1626 for(i=0; i<pOrderBy->nExpr; i++){
1627 sqlite3VdbeAddOp3(v, OP_Column, csr, iColOff+i, reg+i);
1628 }
1629 }
1630}
1631
dan13078ca2018-06-13 20:29:38 +00001632/*
dan37d296a2019-09-24 20:20:05 +00001633** Generate VM code to invoke either xStep() (if bInverse is 0) or
1634** xInverse (if bInverse is non-zero) for each window function in the
1635** linked list starting at pMWin. Or, for built-in window functions
1636** that do not use the standard function API, generate the required
1637** inline VM code.
1638**
1639** If argument csr is greater than or equal to 0, then argument reg is
1640** the first register in an array of registers guaranteed to be large
1641** enough to hold the array of arguments for each function. In this case
1642** the arguments are extracted from the current row of csr into the
1643** array of registers before invoking OP_AggStep or OP_AggInverse
1644**
1645** Or, if csr is less than zero, then the array of registers at reg is
1646** already populated with all columns from the current row of the sub-query.
1647**
1648** If argument regPartSize is non-zero, then it is a register containing the
1649** number of rows in the current partition.
1650*/
1651static void windowAggStep(
1652 WindowCodeArg *p,
1653 Window *pMWin, /* Linked list of window functions */
1654 int csr, /* Read arguments from this cursor */
1655 int bInverse, /* True to invoke xInverse instead of xStep */
1656 int reg /* Array of registers */
1657){
1658 Parse *pParse = p->pParse;
1659 Vdbe *v = sqlite3GetVdbe(pParse);
1660 Window *pWin;
1661 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
drh105dcaa2022-03-10 16:01:14 +00001662 FuncDef *pFunc = pWin->pWFunc;
dan37d296a2019-09-24 20:20:05 +00001663 int regArg;
1664 int nArg = pWin->bExprArgs ? 0 : windowArgCount(pWin);
1665 int i;
1666
1667 assert( bInverse==0 || pWin->eStart!=TK_UNBOUNDED );
1668
drhc5b35ae2019-09-25 02:07:50 +00001669 /* All OVER clauses in the same window function aggregate step must
1670 ** be the same. */
danfbb6e9f2020-01-09 20:11:29 +00001671 assert( pWin==pMWin || sqlite3WindowCompare(pParse,pWin,pMWin,0)!=1 );
drhc5b35ae2019-09-25 02:07:50 +00001672
dan37d296a2019-09-24 20:20:05 +00001673 for(i=0; i<nArg; i++){
1674 if( i!=1 || pFunc->zName!=nth_valueName ){
1675 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+i, reg+i);
1676 }else{
1677 sqlite3VdbeAddOp3(v, OP_Column, pMWin->iEphCsr, pWin->iArgCol+i, reg+i);
1678 }
1679 }
1680 regArg = reg;
1681
1682 if( pMWin->regStartRowid==0
1683 && (pFunc->funcFlags & SQLITE_FUNC_MINMAX)
1684 && (pWin->eStart!=TK_UNBOUNDED)
1685 ){
1686 int addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regArg);
1687 VdbeCoverage(v);
1688 if( bInverse==0 ){
1689 sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1, 1);
1690 sqlite3VdbeAddOp2(v, OP_SCopy, regArg, pWin->regApp);
1691 sqlite3VdbeAddOp3(v, OP_MakeRecord, pWin->regApp, 2, pWin->regApp+2);
1692 sqlite3VdbeAddOp2(v, OP_IdxInsert, pWin->csrApp, pWin->regApp+2);
1693 }else{
1694 sqlite3VdbeAddOp4Int(v, OP_SeekGE, pWin->csrApp, 0, regArg, 1);
1695 VdbeCoverageNeverTaken(v);
1696 sqlite3VdbeAddOp1(v, OP_Delete, pWin->csrApp);
1697 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
1698 }
1699 sqlite3VdbeJumpHere(v, addrIsNull);
1700 }else if( pWin->regApp ){
1701 assert( pFunc->zName==nth_valueName
1702 || pFunc->zName==first_valueName
1703 );
1704 assert( bInverse==0 || bInverse==1 );
1705 sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1-bInverse, 1);
1706 }else if( pFunc->xSFunc!=noopStepFunc ){
1707 int addrIf = 0;
dan37d296a2019-09-24 20:20:05 +00001708 if( pWin->pFilter ){
1709 int regTmp;
drha4eeccd2021-10-07 17:43:30 +00001710 assert( ExprUseXList(pWin->pOwner) );
dan37d296a2019-09-24 20:20:05 +00001711 assert( pWin->bExprArgs || !nArg ||nArg==pWin->pOwner->x.pList->nExpr );
1712 assert( pWin->bExprArgs || nArg ||pWin->pOwner->x.pList==0 );
1713 regTmp = sqlite3GetTempReg(pParse);
1714 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+nArg,regTmp);
1715 addrIf = sqlite3VdbeAddOp3(v, OP_IfNot, regTmp, 0, 1);
1716 VdbeCoverage(v);
1717 sqlite3ReleaseTempReg(pParse, regTmp);
1718 }
dan37d296a2019-09-24 20:20:05 +00001719
dan37d296a2019-09-24 20:20:05 +00001720 if( pWin->bExprArgs ){
dan5a9fd232021-04-06 18:40:27 +00001721 int iOp = sqlite3VdbeCurrentAddr(v);
1722 int iEnd;
dan37d296a2019-09-24 20:20:05 +00001723
drha4eeccd2021-10-07 17:43:30 +00001724 assert( ExprUseXList(pWin->pOwner) );
dan37d296a2019-09-24 20:20:05 +00001725 nArg = pWin->pOwner->x.pList->nExpr;
1726 regArg = sqlite3GetTempRange(pParse, nArg);
1727 sqlite3ExprCodeExprList(pParse, pWin->pOwner->x.pList, regArg, 0, 0);
1728
dan5a9fd232021-04-06 18:40:27 +00001729 for(iEnd=sqlite3VdbeCurrentAddr(v); iOp<iEnd; iOp++){
1730 VdbeOp *pOp = sqlite3VdbeGetOp(v, iOp);
dan41150bf2022-04-20 16:42:57 +00001731 if( pOp->opcode==OP_Column && pOp->p1==pMWin->iEphCsr ){
dan37d296a2019-09-24 20:20:05 +00001732 pOp->p1 = csr;
1733 }
1734 }
1735 }
1736 if( pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
1737 CollSeq *pColl;
1738 assert( nArg>0 );
drha4eeccd2021-10-07 17:43:30 +00001739 assert( ExprUseXList(pWin->pOwner) );
dan37d296a2019-09-24 20:20:05 +00001740 pColl = sqlite3ExprNNCollSeq(pParse, pWin->pOwner->x.pList->a[0].pExpr);
1741 sqlite3VdbeAddOp4(v, OP_CollSeq, 0,0,0, (const char*)pColl, P4_COLLSEQ);
1742 }
1743 sqlite3VdbeAddOp3(v, bInverse? OP_AggInverse : OP_AggStep,
1744 bInverse, regArg, pWin->regAccum);
1745 sqlite3VdbeAppendP4(v, pFunc, P4_FUNCDEF);
1746 sqlite3VdbeChangeP5(v, (u8)nArg);
1747 if( pWin->bExprArgs ){
1748 sqlite3ReleaseTempRange(pParse, regArg, nArg);
1749 }
1750 if( addrIf ) sqlite3VdbeJumpHere(v, addrIf);
dan37d296a2019-09-24 20:20:05 +00001751 }
1752 }
1753}
1754
1755/*
1756** Values that may be passed as the second argument to windowCodeOp().
1757*/
1758#define WINDOW_RETURN_ROW 1
1759#define WINDOW_AGGINVERSE 2
1760#define WINDOW_AGGSTEP 3
1761
1762/*
dana0f6b832019-03-14 16:36:20 +00001763** Generate VM code to invoke either xValue() (bFin==0) or xFinalize()
1764** (bFin==1) for each window function in the linked list starting at
dan13078ca2018-06-13 20:29:38 +00001765** pMWin. Or, for built-in window-functions that do not use the standard
1766** API, generate the equivalent VM code.
1767*/
danc782a812019-03-15 20:46:19 +00001768static void windowAggFinal(WindowCodeArg *p, int bFin){
1769 Parse *pParse = p->pParse;
1770 Window *pMWin = p->pMWin;
dand6f784e2018-05-28 18:30:45 +00001771 Vdbe *v = sqlite3GetVdbe(pParse);
1772 Window *pWin;
1773
1774 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
dana0f6b832019-03-14 16:36:20 +00001775 if( pMWin->regStartRowid==0
drh105dcaa2022-03-10 16:01:14 +00001776 && (pWin->pWFunc->funcFlags & SQLITE_FUNC_MINMAX)
dana0f6b832019-03-14 16:36:20 +00001777 && (pWin->eStart!=TK_UNBOUNDED)
danec891fd2018-06-06 20:51:02 +00001778 ){
dand6f784e2018-05-28 18:30:45 +00001779 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
danc9a86682018-05-30 20:44:58 +00001780 sqlite3VdbeAddOp1(v, OP_Last, pWin->csrApp);
dan01e12292018-06-27 20:24:59 +00001781 VdbeCoverage(v);
danc9a86682018-05-30 20:44:58 +00001782 sqlite3VdbeAddOp3(v, OP_Column, pWin->csrApp, 0, pWin->regResult);
1783 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
danec891fd2018-06-06 20:51:02 +00001784 }else if( pWin->regApp ){
dana0f6b832019-03-14 16:36:20 +00001785 assert( pMWin->regStartRowid==0 );
dand6f784e2018-05-28 18:30:45 +00001786 }else{
dana0f6b832019-03-14 16:36:20 +00001787 int nArg = windowArgCount(pWin);
1788 if( bFin ){
1789 sqlite3VdbeAddOp2(v, OP_AggFinal, pWin->regAccum, nArg);
drh105dcaa2022-03-10 16:01:14 +00001790 sqlite3VdbeAppendP4(v, pWin->pWFunc, P4_FUNCDEF);
danc9a86682018-05-30 20:44:58 +00001791 sqlite3VdbeAddOp2(v, OP_Copy, pWin->regAccum, pWin->regResult);
dan8b985602018-06-09 17:43:45 +00001792 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
danc9a86682018-05-30 20:44:58 +00001793 }else{
dana0f6b832019-03-14 16:36:20 +00001794 sqlite3VdbeAddOp3(v, OP_AggValue,pWin->regAccum,nArg,pWin->regResult);
drh105dcaa2022-03-10 16:01:14 +00001795 sqlite3VdbeAppendP4(v, pWin->pWFunc, P4_FUNCDEF);
danc9a86682018-05-30 20:44:58 +00001796 }
dand6f784e2018-05-28 18:30:45 +00001797 }
1798 }
1799}
1800
dan0525b6f2019-03-18 21:19:40 +00001801/*
1802** Generate code to calculate the current values of all window functions in the
1803** p->pMWin list by doing a full scan of the current window frame. Store the
1804** results in the Window.regResult registers, ready to return the upper
1805** layer.
1806*/
danc782a812019-03-15 20:46:19 +00001807static void windowFullScan(WindowCodeArg *p){
1808 Window *pWin;
1809 Parse *pParse = p->pParse;
1810 Window *pMWin = p->pMWin;
1811 Vdbe *v = p->pVdbe;
1812
1813 int regCRowid = 0; /* Current rowid value */
1814 int regCPeer = 0; /* Current peer values */
1815 int regRowid = 0; /* AggStep rowid value */
1816 int regPeer = 0; /* AggStep peer values */
1817
1818 int nPeer;
1819 int lblNext;
1820 int lblBrk;
1821 int addrNext;
drh55f66b32019-07-16 19:44:32 +00001822 int csr;
danc782a812019-03-15 20:46:19 +00001823
dan37d296a2019-09-24 20:20:05 +00001824 VdbeModuleComment((v, "windowFullScan begin"));
1825
drh55f66b32019-07-16 19:44:32 +00001826 assert( pMWin!=0 );
1827 csr = pMWin->csrApp;
danc782a812019-03-15 20:46:19 +00001828 nPeer = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);
1829
1830 lblNext = sqlite3VdbeMakeLabel(pParse);
1831 lblBrk = sqlite3VdbeMakeLabel(pParse);
1832
1833 regCRowid = sqlite3GetTempReg(pParse);
1834 regRowid = sqlite3GetTempReg(pParse);
1835 if( nPeer ){
1836 regCPeer = sqlite3GetTempRange(pParse, nPeer);
1837 regPeer = sqlite3GetTempRange(pParse, nPeer);
1838 }
1839
1840 sqlite3VdbeAddOp2(v, OP_Rowid, pMWin->iEphCsr, regCRowid);
1841 windowReadPeerValues(p, pMWin->iEphCsr, regCPeer);
1842
1843 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1844 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
1845 }
1846
1847 sqlite3VdbeAddOp3(v, OP_SeekGE, csr, lblBrk, pMWin->regStartRowid);
dan1d4b25f2019-03-19 16:49:15 +00001848 VdbeCoverage(v);
danc782a812019-03-15 20:46:19 +00001849 addrNext = sqlite3VdbeCurrentAddr(v);
1850 sqlite3VdbeAddOp2(v, OP_Rowid, csr, regRowid);
1851 sqlite3VdbeAddOp3(v, OP_Gt, pMWin->regEndRowid, lblBrk, regRowid);
dan1d4b25f2019-03-19 16:49:15 +00001852 VdbeCoverageNeverNull(v);
dan108e6b22019-03-18 18:55:35 +00001853
danc782a812019-03-15 20:46:19 +00001854 if( pMWin->eExclude==TK_CURRENT ){
1855 sqlite3VdbeAddOp3(v, OP_Eq, regCRowid, lblNext, regRowid);
drh83c5bb92019-04-01 15:55:38 +00001856 VdbeCoverageNeverNull(v);
danc782a812019-03-15 20:46:19 +00001857 }else if( pMWin->eExclude!=TK_NO ){
1858 int addr;
dan108e6b22019-03-18 18:55:35 +00001859 int addrEq = 0;
dan66033422019-03-19 19:19:53 +00001860 KeyInfo *pKeyInfo = 0;
dan108e6b22019-03-18 18:55:35 +00001861
dan66033422019-03-19 19:19:53 +00001862 if( pMWin->pOrderBy ){
1863 pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pMWin->pOrderBy, 0, 0);
danc782a812019-03-15 20:46:19 +00001864 }
dan66033422019-03-19 19:19:53 +00001865 if( pMWin->eExclude==TK_TIES ){
1866 addrEq = sqlite3VdbeAddOp3(v, OP_Eq, regCRowid, 0, regRowid);
drh83c5bb92019-04-01 15:55:38 +00001867 VdbeCoverageNeverNull(v);
dan66033422019-03-19 19:19:53 +00001868 }
1869 if( pKeyInfo ){
1870 windowReadPeerValues(p, csr, regPeer);
1871 sqlite3VdbeAddOp3(v, OP_Compare, regPeer, regCPeer, nPeer);
1872 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
1873 addr = sqlite3VdbeCurrentAddr(v)+1;
1874 sqlite3VdbeAddOp3(v, OP_Jump, addr, lblNext, addr);
1875 VdbeCoverageEqNe(v);
1876 }else{
1877 sqlite3VdbeAddOp2(v, OP_Goto, 0, lblNext);
1878 }
danc782a812019-03-15 20:46:19 +00001879 if( addrEq ) sqlite3VdbeJumpHere(v, addrEq);
1880 }
1881
dan37d296a2019-09-24 20:20:05 +00001882 windowAggStep(p, pMWin, csr, 0, p->regArg);
danc782a812019-03-15 20:46:19 +00001883
1884 sqlite3VdbeResolveLabel(v, lblNext);
1885 sqlite3VdbeAddOp2(v, OP_Next, csr, addrNext);
dan1d4b25f2019-03-19 16:49:15 +00001886 VdbeCoverage(v);
danc782a812019-03-15 20:46:19 +00001887 sqlite3VdbeJumpHere(v, addrNext-1);
1888 sqlite3VdbeJumpHere(v, addrNext+1);
1889 sqlite3ReleaseTempReg(pParse, regRowid);
1890 sqlite3ReleaseTempReg(pParse, regCRowid);
1891 if( nPeer ){
1892 sqlite3ReleaseTempRange(pParse, regPeer, nPeer);
1893 sqlite3ReleaseTempRange(pParse, regCPeer, nPeer);
1894 }
1895
1896 windowAggFinal(p, 1);
dan37d296a2019-09-24 20:20:05 +00001897 VdbeModuleComment((v, "windowFullScan end"));
danc782a812019-03-15 20:46:19 +00001898}
1899
dan13078ca2018-06-13 20:29:38 +00001900/*
dan13078ca2018-06-13 20:29:38 +00001901** Invoke the sub-routine at regGosub (generated by code in select.c) to
1902** return the current row of Window.iEphCsr. If all window functions are
1903** aggregate window functions that use the standard API, a single
1904** OP_Gosub instruction is all that this routine generates. Extra VM code
1905** for per-row processing is only generated for the following built-in window
1906** functions:
1907**
1908** nth_value()
1909** first_value()
1910** lag()
1911** lead()
1912*/
danc782a812019-03-15 20:46:19 +00001913static void windowReturnOneRow(WindowCodeArg *p){
1914 Window *pMWin = p->pMWin;
1915 Vdbe *v = p->pVdbe;
dan7095c002018-06-07 17:45:22 +00001916
danc782a812019-03-15 20:46:19 +00001917 if( pMWin->regStartRowid ){
1918 windowFullScan(p);
1919 }else{
1920 Parse *pParse = p->pParse;
1921 Window *pWin;
1922
1923 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
drh105dcaa2022-03-10 16:01:14 +00001924 FuncDef *pFunc = pWin->pWFunc;
drha4eeccd2021-10-07 17:43:30 +00001925 assert( ExprUseXList(pWin->pOwner) );
danc782a812019-03-15 20:46:19 +00001926 if( pFunc->zName==nth_valueName
1927 || pFunc->zName==first_valueName
1928 ){
dana0f6b832019-03-14 16:36:20 +00001929 int csr = pWin->csrApp;
danc782a812019-03-15 20:46:19 +00001930 int lbl = sqlite3VdbeMakeLabel(pParse);
1931 int tmpReg = sqlite3GetTempReg(pParse);
1932 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
1933
1934 if( pFunc->zName==nth_valueName ){
1935 sqlite3VdbeAddOp3(v, OP_Column,pMWin->iEphCsr,pWin->iArgCol+1,tmpReg);
1936 windowCheckValue(pParse, tmpReg, 2);
1937 }else{
1938 sqlite3VdbeAddOp2(v, OP_Integer, 1, tmpReg);
1939 }
dana0f6b832019-03-14 16:36:20 +00001940 sqlite3VdbeAddOp3(v, OP_Add, tmpReg, pWin->regApp, tmpReg);
1941 sqlite3VdbeAddOp3(v, OP_Gt, pWin->regApp+1, lbl, tmpReg);
1942 VdbeCoverageNeverNull(v);
1943 sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, 0, tmpReg);
1944 VdbeCoverageNeverTaken(v);
1945 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
danc782a812019-03-15 20:46:19 +00001946 sqlite3VdbeResolveLabel(v, lbl);
1947 sqlite3ReleaseTempReg(pParse, tmpReg);
dana0f6b832019-03-14 16:36:20 +00001948 }
danc782a812019-03-15 20:46:19 +00001949 else if( pFunc->zName==leadName || pFunc->zName==lagName ){
1950 int nArg = pWin->pOwner->x.pList->nExpr;
1951 int csr = pWin->csrApp;
1952 int lbl = sqlite3VdbeMakeLabel(pParse);
1953 int tmpReg = sqlite3GetTempReg(pParse);
1954 int iEph = pMWin->iEphCsr;
1955
1956 if( nArg<3 ){
1957 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
1958 }else{
1959 sqlite3VdbeAddOp3(v, OP_Column, iEph,pWin->iArgCol+2,pWin->regResult);
1960 }
1961 sqlite3VdbeAddOp2(v, OP_Rowid, iEph, tmpReg);
1962 if( nArg<2 ){
1963 int val = (pFunc->zName==leadName ? 1 : -1);
1964 sqlite3VdbeAddOp2(v, OP_AddImm, tmpReg, val);
1965 }else{
1966 int op = (pFunc->zName==leadName ? OP_Add : OP_Subtract);
1967 int tmpReg2 = sqlite3GetTempReg(pParse);
1968 sqlite3VdbeAddOp3(v, OP_Column, iEph, pWin->iArgCol+1, tmpReg2);
1969 sqlite3VdbeAddOp3(v, op, tmpReg2, tmpReg, tmpReg);
1970 sqlite3ReleaseTempReg(pParse, tmpReg2);
1971 }
1972
1973 sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, lbl, tmpReg);
1974 VdbeCoverage(v);
1975 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
1976 sqlite3VdbeResolveLabel(v, lbl);
1977 sqlite3ReleaseTempReg(pParse, tmpReg);
danfe4e25a2018-06-07 20:08:59 +00001978 }
danfe4e25a2018-06-07 20:08:59 +00001979 }
danec891fd2018-06-06 20:51:02 +00001980 }
danc782a812019-03-15 20:46:19 +00001981 sqlite3VdbeAddOp2(v, OP_Gosub, p->regGosub, p->addrGosub);
danec891fd2018-06-06 20:51:02 +00001982}
1983
dan13078ca2018-06-13 20:29:38 +00001984/*
dan54a9ab32018-06-14 14:27:05 +00001985** Generate code to set the accumulator register for each window function
1986** in the linked list passed as the second argument to NULL. And perform
1987** any equivalent initialization required by any built-in window functions
1988** in the list.
1989*/
dan2e605682018-06-07 15:54:26 +00001990static int windowInitAccum(Parse *pParse, Window *pMWin){
1991 Vdbe *v = sqlite3GetVdbe(pParse);
1992 int regArg;
1993 int nArg = 0;
1994 Window *pWin;
1995 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
drh105dcaa2022-03-10 16:01:14 +00001996 FuncDef *pFunc = pWin->pWFunc;
dan0a21ea92020-02-29 17:19:42 +00001997 assert( pWin->regAccum );
dan2e605682018-06-07 15:54:26 +00001998 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
dan2a11bb22018-06-11 20:50:25 +00001999 nArg = MAX(nArg, windowArgCount(pWin));
dan108e6b22019-03-18 18:55:35 +00002000 if( pMWin->regStartRowid==0 ){
dana0f6b832019-03-14 16:36:20 +00002001 if( pFunc->zName==nth_valueName || pFunc->zName==first_valueName ){
2002 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp);
2003 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
2004 }
dan9a947222018-06-14 19:06:36 +00002005
dana0f6b832019-03-14 16:36:20 +00002006 if( (pFunc->funcFlags & SQLITE_FUNC_MINMAX) && pWin->csrApp ){
2007 assert( pWin->eStart!=TK_UNBOUNDED );
2008 sqlite3VdbeAddOp1(v, OP_ResetSorter, pWin->csrApp);
2009 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
2010 }
dan9a947222018-06-14 19:06:36 +00002011 }
dan2e605682018-06-07 15:54:26 +00002012 }
2013 regArg = pParse->nMem+1;
2014 pParse->nMem += nArg;
2015 return regArg;
2016}
2017
danb33487b2019-03-06 17:12:32 +00002018/*
dancc7a8502019-03-11 19:50:54 +00002019** Return true if the current frame should be cached in the ephemeral table,
2020** even if there are no xInverse() calls required.
danb33487b2019-03-06 17:12:32 +00002021*/
dancc7a8502019-03-11 19:50:54 +00002022static int windowCacheFrame(Window *pMWin){
danb33487b2019-03-06 17:12:32 +00002023 Window *pWin;
dana0f6b832019-03-14 16:36:20 +00002024 if( pMWin->regStartRowid ) return 1;
danb33487b2019-03-06 17:12:32 +00002025 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
drh105dcaa2022-03-10 16:01:14 +00002026 FuncDef *pFunc = pWin->pWFunc;
dancc7a8502019-03-11 19:50:54 +00002027 if( (pFunc->zName==nth_valueName)
danb33487b2019-03-06 17:12:32 +00002028 || (pFunc->zName==first_valueName)
danb560a712019-03-13 15:29:14 +00002029 || (pFunc->zName==leadName)
danb33487b2019-03-06 17:12:32 +00002030 || (pFunc->zName==lagName)
2031 ){
2032 return 1;
2033 }
2034 }
2035 return 0;
2036}
2037
dan6c75b392019-03-08 20:02:52 +00002038/*
2039** regOld and regNew are each the first register in an array of size
2040** pOrderBy->nExpr. This function generates code to compare the two
2041** arrays of registers using the collation sequences and other comparison
2042** parameters specified by pOrderBy.
2043**
2044** If the two arrays are not equal, the contents of regNew is copied to
2045** regOld and control falls through. Otherwise, if the contents of the arrays
2046** are equal, an OP_Goto is executed. The address of the OP_Goto is returned.
2047*/
dan935d9d82019-03-12 15:21:51 +00002048static void windowIfNewPeer(
dan6c75b392019-03-08 20:02:52 +00002049 Parse *pParse,
2050 ExprList *pOrderBy,
2051 int regNew, /* First in array of new values */
dan935d9d82019-03-12 15:21:51 +00002052 int regOld, /* First in array of old values */
2053 int addr /* Jump here */
dan6c75b392019-03-08 20:02:52 +00002054){
2055 Vdbe *v = sqlite3GetVdbe(pParse);
dan6c75b392019-03-08 20:02:52 +00002056 if( pOrderBy ){
2057 int nVal = pOrderBy->nExpr;
2058 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pOrderBy, 0, 0);
2059 sqlite3VdbeAddOp3(v, OP_Compare, regOld, regNew, nVal);
2060 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
dan935d9d82019-03-12 15:21:51 +00002061 sqlite3VdbeAddOp3(v, OP_Jump,
2062 sqlite3VdbeCurrentAddr(v)+1, addr, sqlite3VdbeCurrentAddr(v)+1
dan72b9fdc2019-03-09 20:49:17 +00002063 );
dan6c75b392019-03-08 20:02:52 +00002064 VdbeCoverageEqNe(v);
2065 sqlite3VdbeAddOp3(v, OP_Copy, regNew, regOld, nVal-1);
2066 }else{
dan935d9d82019-03-12 15:21:51 +00002067 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
dan6c75b392019-03-08 20:02:52 +00002068 }
dan6c75b392019-03-08 20:02:52 +00002069}
2070
dan72b9fdc2019-03-09 20:49:17 +00002071/*
2072** This function is called as part of generating VM programs for RANGE
dan1e7cb192019-03-16 20:29:54 +00002073** offset PRECEDING/FOLLOWING frame boundaries. Assuming "ASC" order for
dan8b47f522019-08-30 16:14:58 +00002074** the ORDER BY term in the window, and that argument op is OP_Ge, it generates
2075** code equivalent to:
dan72b9fdc2019-03-09 20:49:17 +00002076**
2077** if( csr1.peerVal + regVal >= csr2.peerVal ) goto lbl;
dan1e7cb192019-03-16 20:29:54 +00002078**
dan8b47f522019-08-30 16:14:58 +00002079** The value of parameter op may also be OP_Gt or OP_Le. In these cases the
2080** operator in the above pseudo-code is replaced with ">" or "<=", respectively.
2081**
2082** If the sort-order for the ORDER BY term in the window is DESC, then the
2083** comparison is reversed. Instead of adding regVal to csr1.peerVal, it is
2084** subtracted. And the comparison operator is inverted to - ">=" becomes "<=",
2085** ">" becomes "<", and so on. So, with DESC sort order, if the argument op
2086** is OP_Ge, the generated code is equivalent to:
2087**
2088** if( csr1.peerVal - regVal <= csr2.peerVal ) goto lbl;
2089**
2090** A special type of arithmetic is used such that if csr1.peerVal is not
dan6b6ec402021-04-05 19:05:18 +00002091** a numeric type (real or integer), then the result of the addition
dan8b47f522019-08-30 16:14:58 +00002092** or subtraction is a a copy of csr1.peerVal.
dan72b9fdc2019-03-09 20:49:17 +00002093*/
2094static void windowCodeRangeTest(
2095 WindowCodeArg *p,
dan1cac1762019-08-30 17:28:55 +00002096 int op, /* OP_Ge, OP_Gt, or OP_Le */
2097 int csr1, /* Cursor number for cursor 1 */
2098 int regVal, /* Register containing non-negative number */
2099 int csr2, /* Cursor number for cursor 2 */
2100 int lbl /* Jump destination if condition is true */
dan72b9fdc2019-03-09 20:49:17 +00002101){
2102 Parse *pParse = p->pParse;
2103 Vdbe *v = sqlite3GetVdbe(pParse);
dan1cac1762019-08-30 17:28:55 +00002104 ExprList *pOrderBy = p->pMWin->pOrderBy; /* ORDER BY clause for window */
2105 int reg1 = sqlite3GetTempReg(pParse); /* Reg. for csr1.peerVal+regVal */
2106 int reg2 = sqlite3GetTempReg(pParse); /* Reg. for csr2.peerVal */
2107 int regString = ++pParse->nMem; /* Reg. for constant value '' */
dan8b47f522019-08-30 16:14:58 +00002108 int arith = OP_Add; /* OP_Add or OP_Subtract */
2109 int addrGe; /* Jump destination */
dan6b6ec402021-04-05 19:05:18 +00002110 int addrDone = sqlite3VdbeMakeLabel(pParse); /* Address past OP_Ge */
dan7f8653a2021-03-06 14:46:24 +00002111 CollSeq *pColl;
dan71fddaf2019-03-11 11:12:34 +00002112
dan6b6ec402021-04-05 19:05:18 +00002113 /* Read the peer-value from each cursor into a register */
2114 windowReadPeerValues(p, csr1, reg1);
2115 windowReadPeerValues(p, csr2, reg2);
2116
dan71fddaf2019-03-11 11:12:34 +00002117 assert( op==OP_Ge || op==OP_Gt || op==OP_Le );
danae8e45c2019-08-19 19:59:50 +00002118 assert( pOrderBy && pOrderBy->nExpr==1 );
drhd88fd532022-05-02 20:49:30 +00002119 if( pOrderBy->a[0].fg.sortFlags & KEYINFO_ORDER_DESC ){
dan71fddaf2019-03-11 11:12:34 +00002120 switch( op ){
2121 case OP_Ge: op = OP_Le; break;
2122 case OP_Gt: op = OP_Lt; break;
2123 default: assert( op==OP_Le ); op = OP_Ge; break;
2124 }
2125 arith = OP_Subtract;
2126 }
2127
dan8b47f522019-08-30 16:14:58 +00002128 VdbeModuleComment((v, "CodeRangeTest: if( R%d %s R%d %s R%d ) goto lbl",
2129 reg1, (arith==OP_Add ? "+" : "-"), regVal,
2130 ((op==OP_Ge) ? ">=" : (op==OP_Le) ? "<=" : (op==OP_Gt) ? ">" : "<"), reg2
2131 ));
2132
dan8b47f522019-08-30 16:14:58 +00002133 /* If the BIGNULL flag is set for the ORDER BY, then it is required to
2134 ** consider NULL values to be larger than all other values, instead of
2135 ** the usual smaller. The VDBE opcodes OP_Ge and so on do not handle this
2136 ** (and adding that capability causes a performance regression), so
2137 ** instead if the BIGNULL flag is set then cases where either reg1 or
2138 ** reg2 are NULL are handled separately in the following block. The code
2139 ** generated is equivalent to:
2140 **
2141 ** if( reg1 IS NULL ){
dan9889ede2019-08-30 19:45:03 +00002142 ** if( op==OP_Ge ) goto lbl;
2143 ** if( op==OP_Gt && reg2 IS NOT NULL ) goto lbl;
dan8b47f522019-08-30 16:14:58 +00002144 ** if( op==OP_Le && reg2 IS NULL ) goto lbl;
2145 ** }else if( reg2 IS NULL ){
2146 ** if( op==OP_Le ) goto lbl;
2147 ** }
2148 **
2149 ** Additionally, if either reg1 or reg2 are NULL but the jump to lbl is
2150 ** not taken, control jumps over the comparison operator coded below this
2151 ** block. */
drhd88fd532022-05-02 20:49:30 +00002152 if( pOrderBy->a[0].fg.sortFlags & KEYINFO_ORDER_BIGNULL ){
dan8b47f522019-08-30 16:14:58 +00002153 /* This block runs if reg1 contains a NULL. */
2154 int addr = sqlite3VdbeAddOp1(v, OP_NotNull, reg1); VdbeCoverage(v);
danae8e45c2019-08-19 19:59:50 +00002155 switch( op ){
dan8b47f522019-08-30 16:14:58 +00002156 case OP_Ge:
2157 sqlite3VdbeAddOp2(v, OP_Goto, 0, lbl);
2158 break;
danf236b212019-08-21 19:58:11 +00002159 case OP_Gt:
drhdb3a32e2019-08-30 18:02:49 +00002160 sqlite3VdbeAddOp2(v, OP_NotNull, reg2, lbl);
2161 VdbeCoverage(v);
danf236b212019-08-21 19:58:11 +00002162 break;
drhdb3a32e2019-08-30 18:02:49 +00002163 case OP_Le:
2164 sqlite3VdbeAddOp2(v, OP_IsNull, reg2, lbl);
2165 VdbeCoverage(v);
danf236b212019-08-21 19:58:11 +00002166 break;
drhdb3a32e2019-08-30 18:02:49 +00002167 default: assert( op==OP_Lt ); /* no-op */ break;
danae8e45c2019-08-19 19:59:50 +00002168 }
dan6b6ec402021-04-05 19:05:18 +00002169 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrDone);
dan8b47f522019-08-30 16:14:58 +00002170
2171 /* This block runs if reg1 is not NULL, but reg2 is. */
danae8e45c2019-08-19 19:59:50 +00002172 sqlite3VdbeJumpHere(v, addr);
drh058e9952022-07-25 19:05:24 +00002173 sqlite3VdbeAddOp2(v, OP_IsNull, reg2,
2174 (op==OP_Gt || op==OP_Ge) ? addrDone : lbl);
drh3b01dd02022-07-26 19:10:13 +00002175 VdbeCoverage(v);
danae8e45c2019-08-19 19:59:50 +00002176 }
dan8b47f522019-08-30 16:14:58 +00002177
dan6b6ec402021-04-05 19:05:18 +00002178 /* Register reg1 currently contains csr1.peerVal (the peer-value from csr1).
2179 ** This block adds (or subtracts for DESC) the numeric value in regVal
2180 ** from it. Or, if reg1 is not numeric (it is a NULL, a text value or a blob),
2181 ** then leave reg1 as it is. In pseudo-code, this is implemented as:
2182 **
2183 ** if( reg1>='' ) goto addrGe;
2184 ** reg1 = reg1 +/- regVal
2185 ** addrGe:
2186 **
2187 ** Since all strings and blobs are greater-than-or-equal-to an empty string,
2188 ** the add/subtract is skipped for these, as required. If reg1 is a NULL,
2189 ** then the arithmetic is performed, but since adding or subtracting from
2190 ** NULL is always NULL anyway, this case is handled as required too. */
2191 sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC);
2192 addrGe = sqlite3VdbeAddOp3(v, OP_Ge, regString, 0, reg1);
2193 VdbeCoverage(v);
2194 if( (op==OP_Ge && arith==OP_Add) || (op==OP_Le && arith==OP_Subtract) ){
2195 sqlite3VdbeAddOp3(v, op, reg2, lbl, reg1); VdbeCoverage(v);
2196 }
2197 sqlite3VdbeAddOp3(v, arith, regVal, reg1, reg1);
2198 sqlite3VdbeJumpHere(v, addrGe);
2199
dan8b47f522019-08-30 16:14:58 +00002200 /* Compare registers reg2 and reg1, taking the jump if required. Note that
2201 ** control skips over this test if the BIGNULL flag is set and either
2202 ** reg1 or reg2 contain a NULL value. */
drh6f883592019-03-30 20:37:04 +00002203 sqlite3VdbeAddOp3(v, op, reg2, lbl, reg1); VdbeCoverage(v);
dan7f8653a2021-03-06 14:46:24 +00002204 pColl = sqlite3ExprNNCollSeq(pParse, pOrderBy->a[0].pExpr);
2205 sqlite3VdbeAppendP4(v, (void*)pColl, P4_COLLSEQ);
danbdabe742019-03-18 16:51:24 +00002206 sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
dan6b6ec402021-04-05 19:05:18 +00002207 sqlite3VdbeResolveLabel(v, addrDone);
dan8b47f522019-08-30 16:14:58 +00002208
drh6f883592019-03-30 20:37:04 +00002209 assert( op==OP_Ge || op==OP_Gt || op==OP_Lt || op==OP_Le );
2210 testcase(op==OP_Ge); VdbeCoverageIf(v, op==OP_Ge);
2211 testcase(op==OP_Lt); VdbeCoverageIf(v, op==OP_Lt);
2212 testcase(op==OP_Le); VdbeCoverageIf(v, op==OP_Le);
2213 testcase(op==OP_Gt); VdbeCoverageIf(v, op==OP_Gt);
dan72b9fdc2019-03-09 20:49:17 +00002214 sqlite3ReleaseTempReg(pParse, reg1);
2215 sqlite3ReleaseTempReg(pParse, reg2);
dan8b47f522019-08-30 16:14:58 +00002216
2217 VdbeModuleComment((v, "CodeRangeTest: end"));
dan72b9fdc2019-03-09 20:49:17 +00002218}
2219
dan0525b6f2019-03-18 21:19:40 +00002220/*
2221** Helper function for sqlite3WindowCodeStep(). Each call to this function
2222** generates VM code for a single RETURN_ROW, AGGSTEP or AGGINVERSE
2223** operation. Refer to the header comment for sqlite3WindowCodeStep() for
2224** details.
2225*/
dan00267b82019-03-06 21:04:11 +00002226static int windowCodeOp(
dan0525b6f2019-03-18 21:19:40 +00002227 WindowCodeArg *p, /* Context object */
2228 int op, /* WINDOW_RETURN_ROW, AGGSTEP or AGGINVERSE */
2229 int regCountdown, /* Register for OP_IfPos countdown */
2230 int jumpOnEof /* Jump here if stepped cursor reaches EOF */
dan00267b82019-03-06 21:04:11 +00002231){
dan6c75b392019-03-08 20:02:52 +00002232 int csr, reg;
2233 Parse *pParse = p->pParse;
dan54975cd2019-03-07 20:47:46 +00002234 Window *pMWin = p->pMWin;
dan00267b82019-03-06 21:04:11 +00002235 int ret = 0;
2236 Vdbe *v = p->pVdbe;
dan6c75b392019-03-08 20:02:52 +00002237 int addrContinue = 0;
drhfc15f4c2019-03-28 13:03:41 +00002238 int bPeer = (pMWin->eFrmType!=TK_ROWS);
dan00267b82019-03-06 21:04:11 +00002239
dan72b9fdc2019-03-09 20:49:17 +00002240 int lblDone = sqlite3VdbeMakeLabel(pParse);
2241 int addrNextRange = 0;
2242
dan54975cd2019-03-07 20:47:46 +00002243 /* Special case - WINDOW_AGGINVERSE is always a no-op if the frame
2244 ** starts with UNBOUNDED PRECEDING. */
2245 if( op==WINDOW_AGGINVERSE && pMWin->eStart==TK_UNBOUNDED ){
2246 assert( regCountdown==0 && jumpOnEof==0 );
2247 return 0;
2248 }
2249
dan00267b82019-03-06 21:04:11 +00002250 if( regCountdown>0 ){
drhfc15f4c2019-03-28 13:03:41 +00002251 if( pMWin->eFrmType==TK_RANGE ){
dan72b9fdc2019-03-09 20:49:17 +00002252 addrNextRange = sqlite3VdbeCurrentAddr(v);
dan0525b6f2019-03-18 21:19:40 +00002253 assert( op==WINDOW_AGGINVERSE || op==WINDOW_AGGSTEP );
2254 if( op==WINDOW_AGGINVERSE ){
2255 if( pMWin->eStart==TK_FOLLOWING ){
dan72b9fdc2019-03-09 20:49:17 +00002256 windowCodeRangeTest(
dan0525b6f2019-03-18 21:19:40 +00002257 p, OP_Le, p->current.csr, regCountdown, p->start.csr, lblDone
dan72b9fdc2019-03-09 20:49:17 +00002258 );
dan0525b6f2019-03-18 21:19:40 +00002259 }else{
2260 windowCodeRangeTest(
2261 p, OP_Ge, p->start.csr, regCountdown, p->current.csr, lblDone
2262 );
dan72b9fdc2019-03-09 20:49:17 +00002263 }
dan0525b6f2019-03-18 21:19:40 +00002264 }else{
2265 windowCodeRangeTest(
2266 p, OP_Gt, p->end.csr, regCountdown, p->current.csr, lblDone
2267 );
dan72b9fdc2019-03-09 20:49:17 +00002268 }
dan72b9fdc2019-03-09 20:49:17 +00002269 }else{
dan37d296a2019-09-24 20:20:05 +00002270 sqlite3VdbeAddOp3(v, OP_IfPos, regCountdown, lblDone, 1);
dan1d4b25f2019-03-19 16:49:15 +00002271 VdbeCoverage(v);
dan72b9fdc2019-03-09 20:49:17 +00002272 }
dan00267b82019-03-06 21:04:11 +00002273 }
2274
dan0525b6f2019-03-18 21:19:40 +00002275 if( op==WINDOW_RETURN_ROW && pMWin->regStartRowid==0 ){
danc782a812019-03-15 20:46:19 +00002276 windowAggFinal(p, 0);
dan6c75b392019-03-08 20:02:52 +00002277 }
2278 addrContinue = sqlite3VdbeCurrentAddr(v);
dane7579a52019-09-25 16:41:44 +00002279
2280 /* If this is a (RANGE BETWEEN a FOLLOWING AND b FOLLOWING) or
2281 ** (RANGE BETWEEN b PRECEDING AND a PRECEDING) frame, ensure the
2282 ** start cursor does not advance past the end cursor within the
drh113a33c2021-04-24 23:40:05 +00002283 ** temporary table. It otherwise might, if (a>b). Also ensure that,
2284 ** if the input cursor is still finding new rows, that the end
2285 ** cursor does not go past it to EOF. */
dane7579a52019-09-25 16:41:44 +00002286 if( pMWin->eStart==pMWin->eEnd && regCountdown
drh113a33c2021-04-24 23:40:05 +00002287 && pMWin->eFrmType==TK_RANGE
dane7579a52019-09-25 16:41:44 +00002288 ){
2289 int regRowid1 = sqlite3GetTempReg(pParse);
2290 int regRowid2 = sqlite3GetTempReg(pParse);
drh113a33c2021-04-24 23:40:05 +00002291 if( op==WINDOW_AGGINVERSE ){
2292 sqlite3VdbeAddOp2(v, OP_Rowid, p->start.csr, regRowid1);
2293 sqlite3VdbeAddOp2(v, OP_Rowid, p->end.csr, regRowid2);
2294 sqlite3VdbeAddOp3(v, OP_Ge, regRowid2, lblDone, regRowid1);
2295 VdbeCoverage(v);
2296 }else if( p->regRowid ){
2297 sqlite3VdbeAddOp2(v, OP_Rowid, p->end.csr, regRowid1);
2298 sqlite3VdbeAddOp3(v, OP_Ge, p->regRowid, lblDone, regRowid1);
drh79f313f2021-04-28 15:43:36 +00002299 VdbeCoverageNeverNull(v);
drh113a33c2021-04-24 23:40:05 +00002300 }
dane7579a52019-09-25 16:41:44 +00002301 sqlite3ReleaseTempReg(pParse, regRowid1);
2302 sqlite3ReleaseTempReg(pParse, regRowid2);
2303 assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_FOLLOWING );
2304 }
2305
dan00267b82019-03-06 21:04:11 +00002306 switch( op ){
2307 case WINDOW_RETURN_ROW:
dan6c75b392019-03-08 20:02:52 +00002308 csr = p->current.csr;
2309 reg = p->current.reg;
danc782a812019-03-15 20:46:19 +00002310 windowReturnOneRow(p);
dan00267b82019-03-06 21:04:11 +00002311 break;
2312
2313 case WINDOW_AGGINVERSE:
dan6c75b392019-03-08 20:02:52 +00002314 csr = p->start.csr;
2315 reg = p->start.reg;
dana0f6b832019-03-14 16:36:20 +00002316 if( pMWin->regStartRowid ){
2317 assert( pMWin->regEndRowid );
2318 sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regStartRowid, 1);
2319 }else{
dan37d296a2019-09-24 20:20:05 +00002320 windowAggStep(p, pMWin, csr, 1, p->regArg);
dana0f6b832019-03-14 16:36:20 +00002321 }
dan00267b82019-03-06 21:04:11 +00002322 break;
2323
dan0525b6f2019-03-18 21:19:40 +00002324 default:
2325 assert( op==WINDOW_AGGSTEP );
dan6c75b392019-03-08 20:02:52 +00002326 csr = p->end.csr;
2327 reg = p->end.reg;
dana0f6b832019-03-14 16:36:20 +00002328 if( pMWin->regStartRowid ){
2329 assert( pMWin->regEndRowid );
2330 sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regEndRowid, 1);
2331 }else{
dan37d296a2019-09-24 20:20:05 +00002332 windowAggStep(p, pMWin, csr, 0, p->regArg);
dana0f6b832019-03-14 16:36:20 +00002333 }
dan00267b82019-03-06 21:04:11 +00002334 break;
2335 }
2336
danb560a712019-03-13 15:29:14 +00002337 if( op==p->eDelete ){
2338 sqlite3VdbeAddOp1(v, OP_Delete, csr);
2339 sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
2340 }
2341
danc8137502019-03-07 19:26:17 +00002342 if( jumpOnEof ){
2343 sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+2);
dan1d4b25f2019-03-19 16:49:15 +00002344 VdbeCoverage(v);
danc8137502019-03-07 19:26:17 +00002345 ret = sqlite3VdbeAddOp0(v, OP_Goto);
2346 }else{
dan6c75b392019-03-08 20:02:52 +00002347 sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+1+bPeer);
dan1d4b25f2019-03-19 16:49:15 +00002348 VdbeCoverage(v);
dan6c75b392019-03-08 20:02:52 +00002349 if( bPeer ){
dan37d296a2019-09-24 20:20:05 +00002350 sqlite3VdbeAddOp2(v, OP_Goto, 0, lblDone);
dan6c75b392019-03-08 20:02:52 +00002351 }
dan00267b82019-03-06 21:04:11 +00002352 }
danc8137502019-03-07 19:26:17 +00002353
dan6c75b392019-03-08 20:02:52 +00002354 if( bPeer ){
dan6c75b392019-03-08 20:02:52 +00002355 int nReg = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);
dane7579a52019-09-25 16:41:44 +00002356 int regTmp = (nReg ? sqlite3GetTempRange(pParse, nReg) : 0);
dan6c75b392019-03-08 20:02:52 +00002357 windowReadPeerValues(p, csr, regTmp);
dan935d9d82019-03-12 15:21:51 +00002358 windowIfNewPeer(pParse, pMWin->pOrderBy, regTmp, reg, addrContinue);
dan6c75b392019-03-08 20:02:52 +00002359 sqlite3ReleaseTempRange(pParse, regTmp, nReg);
dan00267b82019-03-06 21:04:11 +00002360 }
dan6c75b392019-03-08 20:02:52 +00002361
dan72b9fdc2019-03-09 20:49:17 +00002362 if( addrNextRange ){
2363 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNextRange);
2364 }
2365 sqlite3VdbeResolveLabel(v, lblDone);
dan00267b82019-03-06 21:04:11 +00002366 return ret;
2367}
2368
dana786e452019-03-11 18:17:04 +00002369
dan00267b82019-03-06 21:04:11 +00002370/*
dana786e452019-03-11 18:17:04 +00002371** Allocate and return a duplicate of the Window object indicated by the
2372** third argument. Set the Window.pOwner field of the new object to
2373** pOwner.
2374*/
2375Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p){
2376 Window *pNew = 0;
2377 if( ALWAYS(p) ){
2378 pNew = sqlite3DbMallocZero(db, sizeof(Window));
2379 if( pNew ){
2380 pNew->zName = sqlite3DbStrDup(db, p->zName);
danb42eb352019-09-16 05:34:08 +00002381 pNew->zBase = sqlite3DbStrDup(db, p->zBase);
dana786e452019-03-11 18:17:04 +00002382 pNew->pFilter = sqlite3ExprDup(db, p->pFilter, 0);
drh105dcaa2022-03-10 16:01:14 +00002383 pNew->pWFunc = p->pWFunc;
dana786e452019-03-11 18:17:04 +00002384 pNew->pPartition = sqlite3ExprListDup(db, p->pPartition, 0);
2385 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, 0);
drhfc15f4c2019-03-28 13:03:41 +00002386 pNew->eFrmType = p->eFrmType;
dana786e452019-03-11 18:17:04 +00002387 pNew->eEnd = p->eEnd;
2388 pNew->eStart = p->eStart;
danc782a812019-03-15 20:46:19 +00002389 pNew->eExclude = p->eExclude;
drhb555b082019-07-19 01:11:27 +00002390 pNew->regResult = p->regResult;
dan0a21ea92020-02-29 17:19:42 +00002391 pNew->regAccum = p->regAccum;
2392 pNew->iArgCol = p->iArgCol;
2393 pNew->iEphCsr = p->iEphCsr;
2394 pNew->bExprArgs = p->bExprArgs;
dana786e452019-03-11 18:17:04 +00002395 pNew->pStart = sqlite3ExprDup(db, p->pStart, 0);
2396 pNew->pEnd = sqlite3ExprDup(db, p->pEnd, 0);
2397 pNew->pOwner = pOwner;
danb42eb352019-09-16 05:34:08 +00002398 pNew->bImplicitFrame = p->bImplicitFrame;
dana786e452019-03-11 18:17:04 +00002399 }
2400 }
2401 return pNew;
2402}
2403
2404/*
2405** Return a copy of the linked list of Window objects passed as the
2406** second argument.
2407*/
2408Window *sqlite3WindowListDup(sqlite3 *db, Window *p){
2409 Window *pWin;
2410 Window *pRet = 0;
2411 Window **pp = &pRet;
2412
2413 for(pWin=p; pWin; pWin=pWin->pNextWin){
2414 *pp = sqlite3WindowDup(db, 0, pWin);
2415 if( *pp==0 ) break;
2416 pp = &((*pp)->pNextWin);
2417 }
2418
2419 return pRet;
2420}
2421
2422/*
dan725b1cf2019-03-26 16:47:17 +00002423** Return true if it can be determined at compile time that expression
2424** pExpr evaluates to a value that, when cast to an integer, is greater
2425** than zero. False otherwise.
2426**
2427** If an OOM error occurs, this function sets the Parse.db.mallocFailed
2428** flag and returns zero.
2429*/
2430static int windowExprGtZero(Parse *pParse, Expr *pExpr){
2431 int ret = 0;
2432 sqlite3 *db = pParse->db;
2433 sqlite3_value *pVal = 0;
2434 sqlite3ValueFromExpr(db, pExpr, db->enc, SQLITE_AFF_NUMERIC, &pVal);
2435 if( pVal && sqlite3_value_int(pVal)>0 ){
2436 ret = 1;
2437 }
2438 sqlite3ValueFree(pVal);
2439 return ret;
2440}
2441
2442/*
dana786e452019-03-11 18:17:04 +00002443** sqlite3WhereBegin() has already been called for the SELECT statement
2444** passed as the second argument when this function is invoked. It generates
2445** code to populate the Window.regResult register for each window function
2446** and invoke the sub-routine at instruction addrGosub once for each row.
2447** sqlite3WhereEnd() is always called before returning.
dan00267b82019-03-06 21:04:11 +00002448**
dana786e452019-03-11 18:17:04 +00002449** This function handles several different types of window frames, which
2450** require slightly different processing. The following pseudo code is
2451** used to implement window frames of the form:
dan00267b82019-03-06 21:04:11 +00002452**
dana786e452019-03-11 18:17:04 +00002453** ROWS BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
dan00267b82019-03-06 21:04:11 +00002454**
dana786e452019-03-11 18:17:04 +00002455** Other window frame types use variants of the following:
2456**
2457** ... loop started by sqlite3WhereBegin() ...
dan00267b82019-03-06 21:04:11 +00002458** if( new partition ){
2459** Gosub flush
dana786e452019-03-11 18:17:04 +00002460** }
dan00267b82019-03-06 21:04:11 +00002461** Insert new row into eph table.
dana786e452019-03-11 18:17:04 +00002462**
dan00267b82019-03-06 21:04:11 +00002463** if( first row of partition ){
dana786e452019-03-11 18:17:04 +00002464** // Rewind three cursors, all open on the eph table.
2465** Rewind(csrEnd);
2466** Rewind(csrStart);
2467** Rewind(csrCurrent);
2468**
dan00267b82019-03-06 21:04:11 +00002469** regEnd = <expr2> // FOLLOWING expression
2470** regStart = <expr1> // PRECEDING expression
2471** }else{
dana786e452019-03-11 18:17:04 +00002472** // First time this branch is taken, the eph table contains two
2473** // rows. The first row in the partition, which all three cursors
2474** // currently point to, and the following row.
2475** AGGSTEP
dan00267b82019-03-06 21:04:11 +00002476** if( (regEnd--)<=0 ){
dana786e452019-03-11 18:17:04 +00002477** RETURN_ROW
2478** if( (regStart--)<=0 ){
2479** AGGINVERSE
dan00267b82019-03-06 21:04:11 +00002480** }
2481** }
dana786e452019-03-11 18:17:04 +00002482** }
2483** }
dan00267b82019-03-06 21:04:11 +00002484** flush:
dana786e452019-03-11 18:17:04 +00002485** AGGSTEP
2486** while( 1 ){
2487** RETURN ROW
2488** if( csrCurrent is EOF ) break;
2489** if( (regStart--)<=0 ){
2490** AggInverse(csrStart)
2491** Next(csrStart)
dan00267b82019-03-06 21:04:11 +00002492** }
dana786e452019-03-11 18:17:04 +00002493** }
dan00267b82019-03-06 21:04:11 +00002494**
dana786e452019-03-11 18:17:04 +00002495** The pseudo-code above uses the following shorthand:
dan00267b82019-03-06 21:04:11 +00002496**
dana786e452019-03-11 18:17:04 +00002497** AGGSTEP: invoke the aggregate xStep() function for each window function
2498** with arguments read from the current row of cursor csrEnd, then
2499** step cursor csrEnd forward one row (i.e. sqlite3BtreeNext()).
2500**
2501** RETURN_ROW: return a row to the caller based on the contents of the
2502** current row of csrCurrent and the current state of all
2503** aggregates. Then step cursor csrCurrent forward one row.
2504**
2505** AGGINVERSE: invoke the aggregate xInverse() function for each window
2506** functions with arguments read from the current row of cursor
2507** csrStart. Then step csrStart forward one row.
2508**
2509** There are two other ROWS window frames that are handled significantly
2510** differently from the above - "BETWEEN <expr> PRECEDING AND <expr> PRECEDING"
2511** and "BETWEEN <expr> FOLLOWING AND <expr> FOLLOWING". These are special
2512** cases because they change the order in which the three cursors (csrStart,
2513** csrCurrent and csrEnd) iterate through the ephemeral table. Cases that
2514** use UNBOUNDED or CURRENT ROW are much simpler variations on one of these
2515** three.
2516**
2517** ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
2518**
2519** ... loop started by sqlite3WhereBegin() ...
dan00267b82019-03-06 21:04:11 +00002520** if( new partition ){
2521** Gosub flush
dana786e452019-03-11 18:17:04 +00002522** }
dan00267b82019-03-06 21:04:11 +00002523** Insert new row into eph table.
2524** if( first row of partition ){
dan935d9d82019-03-12 15:21:51 +00002525** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
dana786e452019-03-11 18:17:04 +00002526** regEnd = <expr2>
2527** regStart = <expr1>
dan00267b82019-03-06 21:04:11 +00002528** }else{
dana786e452019-03-11 18:17:04 +00002529** if( (regEnd--)<=0 ){
2530** AGGSTEP
2531** }
2532** RETURN_ROW
2533** if( (regStart--)<=0 ){
2534** AGGINVERSE
2535** }
2536** }
2537** }
dan00267b82019-03-06 21:04:11 +00002538** flush:
dana786e452019-03-11 18:17:04 +00002539** if( (regEnd--)<=0 ){
2540** AGGSTEP
2541** }
2542** RETURN_ROW
2543**
2544**
2545** ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
2546**
2547** ... loop started by sqlite3WhereBegin() ...
2548** if( new partition ){
2549** Gosub flush
2550** }
2551** Insert new row into eph table.
2552** if( first row of partition ){
dan935d9d82019-03-12 15:21:51 +00002553** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
dana786e452019-03-11 18:17:04 +00002554** regEnd = <expr2>
2555** regStart = regEnd - <expr1>
2556** }else{
2557** AGGSTEP
2558** if( (regEnd--)<=0 ){
2559** RETURN_ROW
2560** }
2561** if( (regStart--)<=0 ){
2562** AGGINVERSE
2563** }
2564** }
2565** }
2566** flush:
2567** AGGSTEP
2568** while( 1 ){
2569** if( (regEnd--)<=0 ){
2570** RETURN_ROW
2571** if( eof ) break;
2572** }
2573** if( (regStart--)<=0 ){
2574** AGGINVERSE
2575** if( eof ) break
2576** }
2577** }
2578** while( !eof csrCurrent ){
2579** RETURN_ROW
2580** }
2581**
2582** For the most part, the patterns above are adapted to support UNBOUNDED by
2583** assuming that it is equivalent to "infinity PRECEDING/FOLLOWING" and
2584** CURRENT ROW by assuming that it is equivilent to "0 PRECEDING/FOLLOWING".
2585** This is optimized of course - branches that will never be taken and
2586** conditions that are always true are omitted from the VM code. The only
2587** exceptional case is:
2588**
2589** ROWS BETWEEN <expr1> FOLLOWING AND UNBOUNDED FOLLOWING
2590**
2591** ... loop started by sqlite3WhereBegin() ...
2592** if( new partition ){
2593** Gosub flush
2594** }
2595** Insert new row into eph table.
2596** if( first row of partition ){
dan935d9d82019-03-12 15:21:51 +00002597** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
dana786e452019-03-11 18:17:04 +00002598** regStart = <expr1>
2599** }else{
2600** AGGSTEP
2601** }
2602** }
2603** flush:
2604** AGGSTEP
2605** while( 1 ){
2606** if( (regStart--)<=0 ){
2607** AGGINVERSE
2608** if( eof ) break
2609** }
2610** RETURN_ROW
2611** }
2612** while( !eof csrCurrent ){
2613** RETURN_ROW
2614** }
dan935d9d82019-03-12 15:21:51 +00002615**
2616** Also requiring special handling are the cases:
2617**
2618** ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
2619** ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
2620**
2621** when (expr1 < expr2). This is detected at runtime, not by this function.
2622** To handle this case, the pseudo-code programs depicted above are modified
2623** slightly to be:
2624**
2625** ... loop started by sqlite3WhereBegin() ...
2626** if( new partition ){
2627** Gosub flush
2628** }
2629** Insert new row into eph table.
2630** if( first row of partition ){
2631** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2632** regEnd = <expr2>
2633** regStart = <expr1>
2634** if( regEnd < regStart ){
2635** RETURN_ROW
2636** delete eph table contents
2637** continue
2638** }
2639** ...
2640**
2641** The new "continue" statement in the above jumps to the next iteration
2642** of the outer loop - the one started by sqlite3WhereBegin().
2643**
2644** The various GROUPS cases are implemented using the same patterns as
2645** ROWS. The VM code is modified slightly so that:
2646**
2647** 1. The else branch in the main loop is only taken if the row just
2648** added to the ephemeral table is the start of a new group. In
2649** other words, it becomes:
2650**
2651** ... loop started by sqlite3WhereBegin() ...
2652** if( new partition ){
2653** Gosub flush
2654** }
2655** Insert new row into eph table.
2656** if( first row of partition ){
2657** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2658** regEnd = <expr2>
2659** regStart = <expr1>
2660** }else if( new group ){
2661** ...
2662** }
2663** }
2664**
2665** 2. Instead of processing a single row, each RETURN_ROW, AGGSTEP or
2666** AGGINVERSE step processes the current row of the relevant cursor and
2667** all subsequent rows belonging to the same group.
2668**
2669** RANGE window frames are a little different again. As for GROUPS, the
2670** main loop runs once per group only. And RETURN_ROW, AGGSTEP and AGGINVERSE
2671** deal in groups instead of rows. As for ROWS and GROUPS, there are three
2672** basic cases:
2673**
2674** RANGE BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
2675**
2676** ... loop started by sqlite3WhereBegin() ...
2677** if( new partition ){
2678** Gosub flush
2679** }
2680** Insert new row into eph table.
2681** if( first row of partition ){
2682** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2683** regEnd = <expr2>
2684** regStart = <expr1>
2685** }else{
2686** AGGSTEP
2687** while( (csrCurrent.key + regEnd) < csrEnd.key ){
2688** RETURN_ROW
2689** while( csrStart.key + regStart) < csrCurrent.key ){
2690** AGGINVERSE
2691** }
2692** }
2693** }
2694** }
2695** flush:
2696** AGGSTEP
2697** while( 1 ){
2698** RETURN ROW
2699** if( csrCurrent is EOF ) break;
2700** while( csrStart.key + regStart) < csrCurrent.key ){
2701** AGGINVERSE
2702** }
2703** }
2704** }
2705**
2706** In the above notation, "csr.key" means the current value of the ORDER BY
2707** expression (there is only ever 1 for a RANGE that uses an <expr> FOLLOWING
2708** or <expr PRECEDING) read from cursor csr.
2709**
2710** RANGE BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
2711**
2712** ... loop started by sqlite3WhereBegin() ...
2713** if( new partition ){
2714** Gosub flush
2715** }
2716** Insert new row into eph table.
2717** if( first row of partition ){
2718** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2719** regEnd = <expr2>
2720** regStart = <expr1>
2721** }else{
dan37d296a2019-09-24 20:20:05 +00002722** while( (csrEnd.key + regEnd) <= csrCurrent.key ){
dan935d9d82019-03-12 15:21:51 +00002723** AGGSTEP
2724** }
dan935d9d82019-03-12 15:21:51 +00002725** while( (csrStart.key + regStart) < csrCurrent.key ){
2726** AGGINVERSE
2727** }
dane7579a52019-09-25 16:41:44 +00002728** RETURN_ROW
dan935d9d82019-03-12 15:21:51 +00002729** }
2730** }
2731** flush:
2732** while( (csrEnd.key + regEnd) <= csrCurrent.key ){
2733** AGGSTEP
2734** }
dan3f49c322019-04-03 16:27:44 +00002735** while( (csrStart.key + regStart) < csrCurrent.key ){
2736** AGGINVERSE
2737** }
dane7579a52019-09-25 16:41:44 +00002738** RETURN_ROW
dan935d9d82019-03-12 15:21:51 +00002739**
2740** RANGE BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
2741**
2742** ... loop started by sqlite3WhereBegin() ...
2743** if( new partition ){
2744** Gosub flush
2745** }
2746** Insert new row into eph table.
2747** if( first row of partition ){
2748** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2749** regEnd = <expr2>
2750** regStart = <expr1>
2751** }else{
2752** AGGSTEP
2753** while( (csrCurrent.key + regEnd) < csrEnd.key ){
2754** while( (csrCurrent.key + regStart) > csrStart.key ){
2755** AGGINVERSE
2756** }
2757** RETURN_ROW
2758** }
2759** }
2760** }
2761** flush:
2762** AGGSTEP
2763** while( 1 ){
2764** while( (csrCurrent.key + regStart) > csrStart.key ){
2765** AGGINVERSE
2766** if( eof ) break "while( 1 )" loop.
2767** }
2768** RETURN_ROW
2769** }
2770** while( !eof csrCurrent ){
2771** RETURN_ROW
2772** }
2773**
danb6f2dea2019-03-13 17:20:27 +00002774** The text above leaves out many details. Refer to the code and comments
2775** below for a more complete picture.
dan00267b82019-03-06 21:04:11 +00002776*/
dana786e452019-03-11 18:17:04 +00002777void sqlite3WindowCodeStep(
dancc7a8502019-03-11 19:50:54 +00002778 Parse *pParse, /* Parse context */
dana786e452019-03-11 18:17:04 +00002779 Select *p, /* Rewritten SELECT statement */
2780 WhereInfo *pWInfo, /* Context returned by sqlite3WhereBegin() */
2781 int regGosub, /* Register for OP_Gosub */
2782 int addrGosub /* OP_Gosub here to return each row */
dan680f6e82019-03-04 21:07:11 +00002783){
2784 Window *pMWin = p->pWin;
dan6c75b392019-03-08 20:02:52 +00002785 ExprList *pOrderBy = pMWin->pOrderBy;
dan680f6e82019-03-04 21:07:11 +00002786 Vdbe *v = sqlite3GetVdbe(pParse);
dana786e452019-03-11 18:17:04 +00002787 int csrWrite; /* Cursor used to write to eph. table */
2788 int csrInput = p->pSrc->a[0].iCursor; /* Cursor of sub-select */
2789 int nInput = p->pSrc->a[0].pTab->nCol; /* Number of cols returned by sub */
2790 int iInput; /* To iterate through sub cols */
danbf845152019-03-16 10:15:24 +00002791 int addrNe; /* Address of OP_Ne */
drhd4a591d2019-03-26 16:21:11 +00002792 int addrGosubFlush = 0; /* Address of OP_Gosub to flush: */
2793 int addrInteger = 0; /* Address of OP_Integer */
dand4461652019-03-13 08:28:51 +00002794 int addrEmpty; /* Address of OP_Rewind in flush: */
dana786e452019-03-11 18:17:04 +00002795 int regNew; /* Array of registers holding new input row */
2796 int regRecord; /* regNew array in record form */
dana786e452019-03-11 18:17:04 +00002797 int regNewPeer = 0; /* Peer values for new row (part of regNew) */
2798 int regPeer = 0; /* Peer values for current row */
dand4461652019-03-13 08:28:51 +00002799 int regFlushPart = 0; /* Register for "Gosub flush_partition" */
dana786e452019-03-11 18:17:04 +00002800 WindowCodeArg s; /* Context object for sub-routines */
dan935d9d82019-03-12 15:21:51 +00002801 int lblWhereEnd; /* Label just before sqlite3WhereEnd() code */
dane7579a52019-09-25 16:41:44 +00002802 int regStart = 0; /* Value of <expr> PRECEDING */
2803 int regEnd = 0; /* Value of <expr> FOLLOWING */
dan680f6e82019-03-04 21:07:11 +00002804
dan72b9fdc2019-03-09 20:49:17 +00002805 assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_CURRENT
2806 || pMWin->eStart==TK_FOLLOWING || pMWin->eStart==TK_UNBOUNDED
2807 );
2808 assert( pMWin->eEnd==TK_FOLLOWING || pMWin->eEnd==TK_CURRENT
2809 || pMWin->eEnd==TK_UNBOUNDED || pMWin->eEnd==TK_PRECEDING
2810 );
dan108e6b22019-03-18 18:55:35 +00002811 assert( pMWin->eExclude==0 || pMWin->eExclude==TK_CURRENT
2812 || pMWin->eExclude==TK_GROUP || pMWin->eExclude==TK_TIES
2813 || pMWin->eExclude==TK_NO
2814 );
dan72b9fdc2019-03-09 20:49:17 +00002815
dan935d9d82019-03-12 15:21:51 +00002816 lblWhereEnd = sqlite3VdbeMakeLabel(pParse);
dana786e452019-03-11 18:17:04 +00002817
2818 /* Fill in the context object */
dan00267b82019-03-06 21:04:11 +00002819 memset(&s, 0, sizeof(WindowCodeArg));
2820 s.pParse = pParse;
2821 s.pMWin = pMWin;
2822 s.pVdbe = v;
2823 s.regGosub = regGosub;
2824 s.addrGosub = addrGosub;
dan6c75b392019-03-08 20:02:52 +00002825 s.current.csr = pMWin->iEphCsr;
dana786e452019-03-11 18:17:04 +00002826 csrWrite = s.current.csr+1;
dan6c75b392019-03-08 20:02:52 +00002827 s.start.csr = s.current.csr+2;
2828 s.end.csr = s.current.csr+3;
danb33487b2019-03-06 17:12:32 +00002829
danb560a712019-03-13 15:29:14 +00002830 /* Figure out when rows may be deleted from the ephemeral table. There
2831 ** are four options - they may never be deleted (eDelete==0), they may
2832 ** be deleted as soon as they are no longer part of the window frame
2833 ** (eDelete==WINDOW_AGGINVERSE), they may be deleted as after the row
2834 ** has been returned to the caller (WINDOW_RETURN_ROW), or they may
2835 ** be deleted after they enter the frame (WINDOW_AGGSTEP). */
2836 switch( pMWin->eStart ){
dan725b1cf2019-03-26 16:47:17 +00002837 case TK_FOLLOWING:
drhfc15f4c2019-03-28 13:03:41 +00002838 if( pMWin->eFrmType!=TK_RANGE
2839 && windowExprGtZero(pParse, pMWin->pStart)
2840 ){
dan725b1cf2019-03-26 16:47:17 +00002841 s.eDelete = WINDOW_RETURN_ROW;
danb560a712019-03-13 15:29:14 +00002842 }
danb560a712019-03-13 15:29:14 +00002843 break;
danb560a712019-03-13 15:29:14 +00002844 case TK_UNBOUNDED:
2845 if( windowCacheFrame(pMWin)==0 ){
2846 if( pMWin->eEnd==TK_PRECEDING ){
drhfc15f4c2019-03-28 13:03:41 +00002847 if( pMWin->eFrmType!=TK_RANGE
2848 && windowExprGtZero(pParse, pMWin->pEnd)
2849 ){
dan725b1cf2019-03-26 16:47:17 +00002850 s.eDelete = WINDOW_AGGSTEP;
2851 }
danb560a712019-03-13 15:29:14 +00002852 }else{
2853 s.eDelete = WINDOW_RETURN_ROW;
2854 }
2855 }
2856 break;
2857 default:
2858 s.eDelete = WINDOW_AGGINVERSE;
2859 break;
2860 }
2861
dand4461652019-03-13 08:28:51 +00002862 /* Allocate registers for the array of values from the sub-query, the
2863 ** samve values in record form, and the rowid used to insert said record
2864 ** into the ephemeral table. */
dana786e452019-03-11 18:17:04 +00002865 regNew = pParse->nMem+1;
2866 pParse->nMem += nInput;
2867 regRecord = ++pParse->nMem;
drh113a33c2021-04-24 23:40:05 +00002868 s.regRowid = ++pParse->nMem;
dan54975cd2019-03-07 20:47:46 +00002869
dana786e452019-03-11 18:17:04 +00002870 /* If the window frame contains an "<expr> PRECEDING" or "<expr> FOLLOWING"
2871 ** clause, allocate registers to store the results of evaluating each
2872 ** <expr>. */
dan54975cd2019-03-07 20:47:46 +00002873 if( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_FOLLOWING ){
dane7579a52019-09-25 16:41:44 +00002874 regStart = ++pParse->nMem;
dan54975cd2019-03-07 20:47:46 +00002875 }
2876 if( pMWin->eEnd==TK_PRECEDING || pMWin->eEnd==TK_FOLLOWING ){
dane7579a52019-09-25 16:41:44 +00002877 regEnd = ++pParse->nMem;
dan54975cd2019-03-07 20:47:46 +00002878 }
dan680f6e82019-03-04 21:07:11 +00002879
dan72b9fdc2019-03-09 20:49:17 +00002880 /* If this is not a "ROWS BETWEEN ..." frame, then allocate arrays of
dana786e452019-03-11 18:17:04 +00002881 ** registers to store copies of the ORDER BY expressions (peer values)
2882 ** for the main loop, and for each cursor (start, current and end). */
drhfc15f4c2019-03-28 13:03:41 +00002883 if( pMWin->eFrmType!=TK_ROWS ){
dan6c75b392019-03-08 20:02:52 +00002884 int nPeer = (pOrderBy ? pOrderBy->nExpr : 0);
dana786e452019-03-11 18:17:04 +00002885 regNewPeer = regNew + pMWin->nBufferCol;
dan6c75b392019-03-08 20:02:52 +00002886 if( pMWin->pPartition ) regNewPeer += pMWin->pPartition->nExpr;
dan6c75b392019-03-08 20:02:52 +00002887 regPeer = pParse->nMem+1; pParse->nMem += nPeer;
2888 s.start.reg = pParse->nMem+1; pParse->nMem += nPeer;
2889 s.current.reg = pParse->nMem+1; pParse->nMem += nPeer;
2890 s.end.reg = pParse->nMem+1; pParse->nMem += nPeer;
2891 }
2892
dan680f6e82019-03-04 21:07:11 +00002893 /* Load the column values for the row returned by the sub-select
dana786e452019-03-11 18:17:04 +00002894 ** into an array of registers starting at regNew. Assemble them into
2895 ** a record in register regRecord. */
2896 for(iInput=0; iInput<nInput; iInput++){
2897 sqlite3VdbeAddOp3(v, OP_Column, csrInput, iInput, regNew+iInput);
dan680f6e82019-03-04 21:07:11 +00002898 }
dana786e452019-03-11 18:17:04 +00002899 sqlite3VdbeAddOp3(v, OP_MakeRecord, regNew, nInput, regRecord);
dan680f6e82019-03-04 21:07:11 +00002900
danb33487b2019-03-06 17:12:32 +00002901 /* An input row has just been read into an array of registers starting
dana786e452019-03-11 18:17:04 +00002902 ** at regNew. If the window has a PARTITION clause, this block generates
danb33487b2019-03-06 17:12:32 +00002903 ** VM code to check if the input row is the start of a new partition.
2904 ** If so, it does an OP_Gosub to an address to be filled in later. The
dana786e452019-03-11 18:17:04 +00002905 ** address of the OP_Gosub is stored in local variable addrGosubFlush. */
dan680f6e82019-03-04 21:07:11 +00002906 if( pMWin->pPartition ){
2907 int addr;
2908 ExprList *pPart = pMWin->pPartition;
2909 int nPart = pPart->nExpr;
dana786e452019-03-11 18:17:04 +00002910 int regNewPart = regNew + pMWin->nBufferCol;
dan680f6e82019-03-04 21:07:11 +00002911 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pPart, 0, 0);
2912
dand4461652019-03-13 08:28:51 +00002913 regFlushPart = ++pParse->nMem;
dan680f6e82019-03-04 21:07:11 +00002914 addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPart, pMWin->regPart, nPart);
2915 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
danb33487b2019-03-06 17:12:32 +00002916 sqlite3VdbeAddOp3(v, OP_Jump, addr+2, addr+4, addr+2);
dan680f6e82019-03-04 21:07:11 +00002917 VdbeCoverageEqNe(v);
2918 addrGosubFlush = sqlite3VdbeAddOp1(v, OP_Gosub, regFlushPart);
2919 VdbeComment((v, "call flush_partition"));
danb33487b2019-03-06 17:12:32 +00002920 sqlite3VdbeAddOp3(v, OP_Copy, regNewPart, pMWin->regPart, nPart-1);
dan680f6e82019-03-04 21:07:11 +00002921 }
2922
2923 /* Insert the new row into the ephemeral table */
drh113a33c2021-04-24 23:40:05 +00002924 sqlite3VdbeAddOp2(v, OP_NewRowid, csrWrite, s.regRowid);
2925 sqlite3VdbeAddOp3(v, OP_Insert, csrWrite, regRecord, s.regRowid);
2926 addrNe = sqlite3VdbeAddOp3(v, OP_Ne, pMWin->regOne, 0, s.regRowid);
drh83c5bb92019-04-01 15:55:38 +00002927 VdbeCoverageNeverNull(v);
danb25a2142019-03-05 19:29:36 +00002928
danb33487b2019-03-06 17:12:32 +00002929 /* This block is run for the first row of each partition */
dana786e452019-03-11 18:17:04 +00002930 s.regArg = windowInitAccum(pParse, pMWin);
dan680f6e82019-03-04 21:07:11 +00002931
dane7579a52019-09-25 16:41:44 +00002932 if( regStart ){
2933 sqlite3ExprCode(pParse, pMWin->pStart, regStart);
2934 windowCheckValue(pParse, regStart, 0 + (pMWin->eFrmType==TK_RANGE?3:0));
dan54975cd2019-03-07 20:47:46 +00002935 }
dane7579a52019-09-25 16:41:44 +00002936 if( regEnd ){
2937 sqlite3ExprCode(pParse, pMWin->pEnd, regEnd);
2938 windowCheckValue(pParse, regEnd, 1 + (pMWin->eFrmType==TK_RANGE?3:0));
dan54975cd2019-03-07 20:47:46 +00002939 }
danb25a2142019-03-05 19:29:36 +00002940
dane7579a52019-09-25 16:41:44 +00002941 if( pMWin->eFrmType!=TK_RANGE && pMWin->eStart==pMWin->eEnd && regStart ){
danb25a2142019-03-05 19:29:36 +00002942 int op = ((pMWin->eStart==TK_FOLLOWING) ? OP_Ge : OP_Le);
dane7579a52019-09-25 16:41:44 +00002943 int addrGe = sqlite3VdbeAddOp3(v, op, regStart, 0, regEnd);
drh495ed622019-04-01 16:23:21 +00002944 VdbeCoverageNeverNullIf(v, op==OP_Ge); /* NeverNull because bound <expr> */
2945 VdbeCoverageNeverNullIf(v, op==OP_Le); /* values previously checked */
danc782a812019-03-15 20:46:19 +00002946 windowAggFinal(&s, 0);
dancc7a8502019-03-11 19:50:54 +00002947 sqlite3VdbeAddOp2(v, OP_Rewind, s.current.csr, 1);
dan1d4b25f2019-03-19 16:49:15 +00002948 VdbeCoverageNeverTaken(v);
danc782a812019-03-15 20:46:19 +00002949 windowReturnOneRow(&s);
dancc7a8502019-03-11 19:50:54 +00002950 sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr);
dan935d9d82019-03-12 15:21:51 +00002951 sqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd);
danb25a2142019-03-05 19:29:36 +00002952 sqlite3VdbeJumpHere(v, addrGe);
2953 }
dane7579a52019-09-25 16:41:44 +00002954 if( pMWin->eStart==TK_FOLLOWING && pMWin->eFrmType!=TK_RANGE && regEnd ){
dan54975cd2019-03-07 20:47:46 +00002955 assert( pMWin->eEnd==TK_FOLLOWING );
dane7579a52019-09-25 16:41:44 +00002956 sqlite3VdbeAddOp3(v, OP_Subtract, regStart, regEnd, regStart);
danb25a2142019-03-05 19:29:36 +00002957 }
2958
dan54975cd2019-03-07 20:47:46 +00002959 if( pMWin->eStart!=TK_UNBOUNDED ){
dan6c75b392019-03-08 20:02:52 +00002960 sqlite3VdbeAddOp2(v, OP_Rewind, s.start.csr, 1);
dan1d4b25f2019-03-19 16:49:15 +00002961 VdbeCoverageNeverTaken(v);
dan54975cd2019-03-07 20:47:46 +00002962 }
dan6c75b392019-03-08 20:02:52 +00002963 sqlite3VdbeAddOp2(v, OP_Rewind, s.current.csr, 1);
dan1d4b25f2019-03-19 16:49:15 +00002964 VdbeCoverageNeverTaken(v);
dan6c75b392019-03-08 20:02:52 +00002965 sqlite3VdbeAddOp2(v, OP_Rewind, s.end.csr, 1);
dan1d4b25f2019-03-19 16:49:15 +00002966 VdbeCoverageNeverTaken(v);
dan6c75b392019-03-08 20:02:52 +00002967 if( regPeer && pOrderBy ){
dancc7a8502019-03-11 19:50:54 +00002968 sqlite3VdbeAddOp3(v, OP_Copy, regNewPeer, regPeer, pOrderBy->nExpr-1);
dan6c75b392019-03-08 20:02:52 +00002969 sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.start.reg, pOrderBy->nExpr-1);
2970 sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.current.reg, pOrderBy->nExpr-1);
2971 sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.end.reg, pOrderBy->nExpr-1);
2972 }
danb25a2142019-03-05 19:29:36 +00002973
dan935d9d82019-03-12 15:21:51 +00002974 sqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd);
dan680f6e82019-03-04 21:07:11 +00002975
danbf845152019-03-16 10:15:24 +00002976 sqlite3VdbeJumpHere(v, addrNe);
dan3f49c322019-04-03 16:27:44 +00002977
2978 /* Beginning of the block executed for the second and subsequent rows. */
dan6c75b392019-03-08 20:02:52 +00002979 if( regPeer ){
dan935d9d82019-03-12 15:21:51 +00002980 windowIfNewPeer(pParse, pOrderBy, regNewPeer, regPeer, lblWhereEnd);
dan6c75b392019-03-08 20:02:52 +00002981 }
danb25a2142019-03-05 19:29:36 +00002982 if( pMWin->eStart==TK_FOLLOWING ){
dan6c75b392019-03-08 20:02:52 +00002983 windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
dan54975cd2019-03-07 20:47:46 +00002984 if( pMWin->eEnd!=TK_UNBOUNDED ){
drhfc15f4c2019-03-28 13:03:41 +00002985 if( pMWin->eFrmType==TK_RANGE ){
dan72b9fdc2019-03-09 20:49:17 +00002986 int lbl = sqlite3VdbeMakeLabel(pParse);
2987 int addrNext = sqlite3VdbeCurrentAddr(v);
dane7579a52019-09-25 16:41:44 +00002988 windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl);
2989 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
dan72b9fdc2019-03-09 20:49:17 +00002990 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
2991 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNext);
2992 sqlite3VdbeResolveLabel(v, lbl);
2993 }else{
dane7579a52019-09-25 16:41:44 +00002994 windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 0);
2995 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
dan72b9fdc2019-03-09 20:49:17 +00002996 }
dan54975cd2019-03-07 20:47:46 +00002997 }
danb25a2142019-03-05 19:29:36 +00002998 }else
2999 if( pMWin->eEnd==TK_PRECEDING ){
dan3f49c322019-04-03 16:27:44 +00003000 int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE);
dane7579a52019-09-25 16:41:44 +00003001 windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0);
3002 if( bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
dan6c75b392019-03-08 20:02:52 +00003003 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
dane7579a52019-09-25 16:41:44 +00003004 if( !bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
danb25a2142019-03-05 19:29:36 +00003005 }else{
mistachkinba9ee092019-03-27 14:58:18 +00003006 int addr = 0;
dan6c75b392019-03-08 20:02:52 +00003007 windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
dan54975cd2019-03-07 20:47:46 +00003008 if( pMWin->eEnd!=TK_UNBOUNDED ){
drhfc15f4c2019-03-28 13:03:41 +00003009 if( pMWin->eFrmType==TK_RANGE ){
mistachkinba9ee092019-03-27 14:58:18 +00003010 int lbl = 0;
dan72b9fdc2019-03-09 20:49:17 +00003011 addr = sqlite3VdbeCurrentAddr(v);
dane7579a52019-09-25 16:41:44 +00003012 if( regEnd ){
dan72b9fdc2019-03-09 20:49:17 +00003013 lbl = sqlite3VdbeMakeLabel(pParse);
dane7579a52019-09-25 16:41:44 +00003014 windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl);
dan72b9fdc2019-03-09 20:49:17 +00003015 }
3016 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
dane7579a52019-09-25 16:41:44 +00003017 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
3018 if( regEnd ){
dan72b9fdc2019-03-09 20:49:17 +00003019 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
3020 sqlite3VdbeResolveLabel(v, lbl);
3021 }
3022 }else{
dane7579a52019-09-25 16:41:44 +00003023 if( regEnd ){
3024 addr = sqlite3VdbeAddOp3(v, OP_IfPos, regEnd, 0, 1);
dan1d4b25f2019-03-19 16:49:15 +00003025 VdbeCoverage(v);
3026 }
dan72b9fdc2019-03-09 20:49:17 +00003027 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
dane7579a52019-09-25 16:41:44 +00003028 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
3029 if( regEnd ) sqlite3VdbeJumpHere(v, addr);
dan72b9fdc2019-03-09 20:49:17 +00003030 }
dan54975cd2019-03-07 20:47:46 +00003031 }
danb25a2142019-03-05 19:29:36 +00003032 }
dan680f6e82019-03-04 21:07:11 +00003033
dan680f6e82019-03-04 21:07:11 +00003034 /* End of the main input loop */
dan935d9d82019-03-12 15:21:51 +00003035 sqlite3VdbeResolveLabel(v, lblWhereEnd);
dancc7a8502019-03-11 19:50:54 +00003036 sqlite3WhereEnd(pWInfo);
dan680f6e82019-03-04 21:07:11 +00003037
3038 /* Fall through */
dancc7a8502019-03-11 19:50:54 +00003039 if( pMWin->pPartition ){
dan680f6e82019-03-04 21:07:11 +00003040 addrInteger = sqlite3VdbeAddOp2(v, OP_Integer, 0, regFlushPart);
3041 sqlite3VdbeJumpHere(v, addrGosubFlush);
3042 }
3043
drh113a33c2021-04-24 23:40:05 +00003044 s.regRowid = 0;
danc8137502019-03-07 19:26:17 +00003045 addrEmpty = sqlite3VdbeAddOp1(v, OP_Rewind, csrWrite);
dan1d4b25f2019-03-19 16:49:15 +00003046 VdbeCoverage(v);
dan00267b82019-03-06 21:04:11 +00003047 if( pMWin->eEnd==TK_PRECEDING ){
dan3f49c322019-04-03 16:27:44 +00003048 int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE);
dane7579a52019-09-25 16:41:44 +00003049 windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0);
3050 if( bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
dan6c75b392019-03-08 20:02:52 +00003051 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
danc8137502019-03-07 19:26:17 +00003052 }else if( pMWin->eStart==TK_FOLLOWING ){
3053 int addrStart;
3054 int addrBreak1;
3055 int addrBreak2;
3056 int addrBreak3;
dan6c75b392019-03-08 20:02:52 +00003057 windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
drhfc15f4c2019-03-28 13:03:41 +00003058 if( pMWin->eFrmType==TK_RANGE ){
dan72b9fdc2019-03-09 20:49:17 +00003059 addrStart = sqlite3VdbeCurrentAddr(v);
dane7579a52019-09-25 16:41:44 +00003060 addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1);
dan72b9fdc2019-03-09 20:49:17 +00003061 addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
3062 }else
dan54975cd2019-03-07 20:47:46 +00003063 if( pMWin->eEnd==TK_UNBOUNDED ){
3064 addrStart = sqlite3VdbeCurrentAddr(v);
dane7579a52019-09-25 16:41:44 +00003065 addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regStart, 1);
dan6c75b392019-03-08 20:02:52 +00003066 addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, 0, 1);
dan54975cd2019-03-07 20:47:46 +00003067 }else{
3068 assert( pMWin->eEnd==TK_FOLLOWING );
3069 addrStart = sqlite3VdbeCurrentAddr(v);
dane7579a52019-09-25 16:41:44 +00003070 addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 1);
3071 addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1);
dan54975cd2019-03-07 20:47:46 +00003072 }
danc8137502019-03-07 19:26:17 +00003073 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
3074 sqlite3VdbeJumpHere(v, addrBreak2);
3075 addrStart = sqlite3VdbeCurrentAddr(v);
dan6c75b392019-03-08 20:02:52 +00003076 addrBreak3 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
danc8137502019-03-07 19:26:17 +00003077 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
3078 sqlite3VdbeJumpHere(v, addrBreak1);
3079 sqlite3VdbeJumpHere(v, addrBreak3);
danb25a2142019-03-05 19:29:36 +00003080 }else{
dan00267b82019-03-06 21:04:11 +00003081 int addrBreak;
danc8137502019-03-07 19:26:17 +00003082 int addrStart;
dan6c75b392019-03-08 20:02:52 +00003083 windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
danc8137502019-03-07 19:26:17 +00003084 addrStart = sqlite3VdbeCurrentAddr(v);
dan6c75b392019-03-08 20:02:52 +00003085 addrBreak = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
dane7579a52019-09-25 16:41:44 +00003086 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
dan00267b82019-03-06 21:04:11 +00003087 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
3088 sqlite3VdbeJumpHere(v, addrBreak);
danb25a2142019-03-05 19:29:36 +00003089 }
danc8137502019-03-07 19:26:17 +00003090 sqlite3VdbeJumpHere(v, addrEmpty);
3091
dan6c75b392019-03-08 20:02:52 +00003092 sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr);
dan680f6e82019-03-04 21:07:11 +00003093 if( pMWin->pPartition ){
dana0f6b832019-03-14 16:36:20 +00003094 if( pMWin->regStartRowid ){
3095 sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid);
3096 sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid);
3097 }
dan680f6e82019-03-04 21:07:11 +00003098 sqlite3VdbeChangeP1(v, addrInteger, sqlite3VdbeCurrentAddr(v));
3099 sqlite3VdbeAddOp1(v, OP_Return, regFlushPart);
3100 }
3101}
3102
dan67a9b8e2018-06-22 20:51:35 +00003103#endif /* SQLITE_OMIT_WINDOWFUNC */