Thanks to visit codestin.com
Credit goes to chromium.googlesource.com

blob: 948b0728afed09ad91bab69291f8fb7debee92cd [file] [log] [blame]
dan86fb6e12018-05-16 20:58:071/*
dan26522d12018-06-11 18:16:512** 2018 May 08
dan86fb6e12018-05-16 20:58:073**
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:3515#ifndef SQLITE_OMIT_WINDOWFUNC
16
dandfa552f2018-06-02 21:04:2817/*
dan73925692018-06-12 18:40:1718** 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**
larrybrbc917382023-06-07 08:40:3143** * FROM, WHERE, GROUP BY and HAVING clauses are all moved to
dan73925692018-06-12 18:40:1744** the sub-query.
45**
46** * ORDER BY, LIMIT and OFFSET remain part of the parent query.
47**
larrybrbc917382023-06-07 08:40:3148** * Terminals from each of the expression trees that make up the
dan73925692018-06-12 18:40:1749** 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**
larrybrbc917382023-06-07 08:40:3157** SELECT max(b) OVER (PARTITION BY c ORDER BY d),
58** min(e) OVER (PARTITION BY c ORDER BY d)
dan73925692018-06-12 18:40:1759** FROM t1;
60**
61** is transformed in the same way as the example above. However:
62**
larrybrbc917382023-06-07 08:40:3163** SELECT max(b) OVER (PARTITION BY c ORDER BY d),
64** min(e) OVER (PARTITION BY a ORDER BY b)
dan73925692018-06-12 18:40:1765** 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)
larrybrbc917382023-06-07 08:40:31117**
118** These are the same built-in window functions supported by Postgres.
dan73925692018-06-12 18:40:17119** Although the behaviour of aggregate window functions (functions that
larrybrbc917382023-06-07 08:40:31120** can be used as either aggregates or window functions) allows them to
dan73925692018-06-12 18:40:17121** be implemented using an API, built-in window functions are much more
larrybrbc917382023-06-07 08:40:31122** esoteric. Additionally, some window functions (e.g. nth_value())
dan73925692018-06-12 18:40:17123** 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
larrybrbc917382023-06-07 08:40:31125** window functions and some are implemented directly using VDBE
dan73925692018-06-12 18:40:17126** 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:38134**
135** As well as some of the built-in window functions, aggregate window
136** functions min() and max() are implemented using VDBE instructions if
larrybrbc917382023-06-07 08:40:31137** the start of the window frame is declared as anything other than
danc0bb4452018-06-12 20:53:38138** UNBOUNDED PRECEDING.
dan73925692018-06-12 18:40:17139*/
140
141/*
dandfa552f2018-06-02 21:04:28142** 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(
larrybrbc917382023-06-07 08:40:31148 sqlite3_context *pCtx,
dandfa552f2018-06-02 21:04:28149 int nArg,
150 sqlite3_value **apArg
151){
152 i64 *p = (i64*)sqlite3_aggregate_context(pCtx, sizeof(*p));
drh5d6374f2018-07-10 23:31:17153 if( p ) (*p)++;
drhc7bf5712018-07-09 22:49:01154 UNUSED_PARAMETER(nArg);
155 UNUSED_PARAMETER(apArg);
dandfa552f2018-06-02 21:04:28156}
dandfa552f2018-06-02 21:04:28157static 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:25163** Context object type used by rank(), dense_rank(), percent_rank() and
164** cume_dist().
dandfa552f2018-06-02 21:04:28165*/
166struct CallCount {
167 i64 nValue;
168 i64 nStep;
169 i64 nTotal;
170};
171
172/*
dan9c277582018-06-20 09:23:49173** Implementation of built-in window function dense_rank(). Assumes that
174** the window frame has been set to:
175**
larrybrbc917382023-06-07 08:40:31176** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
dandfa552f2018-06-02 21:04:28177*/
178static void dense_rankStepFunc(
larrybrbc917382023-06-07 08:40:31179 sqlite3_context *pCtx,
dandfa552f2018-06-02 21:04:28180 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:17185 if( p ) p->nStep = 1;
drhc7bf5712018-07-09 22:49:01186 UNUSED_PARAMETER(nArg);
187 UNUSED_PARAMETER(apArg);
dandfa552f2018-06-02 21:04:28188}
dandfa552f2018-06-02 21:04:28189static 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:20202** 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(
larrybrbc917382023-06-07 08:40:31211 sqlite3_context *pCtx,
dana0f6b832019-03-14 16:36:20212 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:35218 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:20234 p->nStep++;
235 if( iVal==p->nStep ){
236 p->pValue = sqlite3_value_dup(apArg[0]);
dan108e6b22019-03-18 18:55:35237 if( !p->pValue ){
238 sqlite3_result_error_nomem(pCtx);
239 }
dana0f6b832019-03-14 16:36:20240 }
241 }
242 UNUSED_PARAMETER(nArg);
243 UNUSED_PARAMETER(apArg);
dan108e6b22019-03-18 18:55:35244 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:20250}
dana0f6b832019-03-14 16:36:20251static void nth_valueFinalizeFunc(sqlite3_context *pCtx){
252 struct NthValueCtx *p;
dan0525b6f2019-03-18 21:19:40253 p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, 0);
dana0f6b832019-03-14 16:36:20254 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:40261#define nth_valueValueFunc noopValueFunc
dana0f6b832019-03-14 16:36:20262
danc782a812019-03-15 20:46:19263static void first_valueStepFunc(
larrybrbc917382023-06-07 08:40:31264 sqlite3_context *pCtx,
danc782a812019-03-15 20:46:19265 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:35272 if( !p->pValue ){
273 sqlite3_result_error_nomem(pCtx);
274 }
danc782a812019-03-15 20:46:19275 }
276 UNUSED_PARAMETER(nArg);
277 UNUSED_PARAMETER(apArg);
278}
danc782a812019-03-15 20:46:19279static 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:40289#define first_valueValueFunc noopValueFunc
danc782a812019-03-15 20:46:19290
dana0f6b832019-03-14 16:36:20291/*
dan9c277582018-06-20 09:23:49292** Implementation of built-in window function rank(). Assumes that
293** the window frame has been set to:
294**
larrybrbc917382023-06-07 08:40:31295** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
dandfa552f2018-06-02 21:04:28296*/
297static void rankStepFunc(
larrybrbc917382023-06-07 08:40:31298 sqlite3_context *pCtx,
dandfa552f2018-06-02 21:04:28299 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:17304 if( p ){
dandfa552f2018-06-02 21:04:28305 p->nStep++;
306 if( p->nValue==0 ){
307 p->nValue = p->nStep;
308 }
309 }
drhc7bf5712018-07-09 22:49:01310 UNUSED_PARAMETER(nArg);
311 UNUSED_PARAMETER(apArg);
dandfa552f2018-06-02 21:04:28312}
dandfa552f2018-06-02 21:04:28313static 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:49323** Implementation of built-in window function percent_rank(). Assumes that
324** the window frame has been set to:
325**
dancc7a8502019-03-11 19:50:54326** GROUPS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
dandfa552f2018-06-02 21:04:28327*/
328static void percent_rankStepFunc(
larrybrbc917382023-06-07 08:40:31329 sqlite3_context *pCtx,
dandfa552f2018-06-02 21:04:28330 int nArg,
331 sqlite3_value **apArg
332){
333 struct CallCount *p;
dancc7a8502019-03-11 19:50:54334 UNUSED_PARAMETER(nArg); assert( nArg==0 );
drhd4a591d2019-03-26 16:21:11335 UNUSED_PARAMETER(apArg);
dandfa552f2018-06-02 21:04:28336 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
drh5d6374f2018-07-10 23:31:17337 if( p ){
dancc7a8502019-03-11 19:50:54338 p->nTotal++;
dandfa552f2018-06-02 21:04:28339 }
340}
dancc7a8502019-03-11 19:50:54341static void percent_rankInvFunc(
larrybrbc917382023-06-07 08:40:31342 sqlite3_context *pCtx,
dancc7a8502019-03-11 19:50:54343 int nArg,
344 sqlite3_value **apArg
345){
346 struct CallCount *p;
347 UNUSED_PARAMETER(nArg); assert( nArg==0 );
drhd4a591d2019-03-26 16:21:11348 UNUSED_PARAMETER(apArg);
dancc7a8502019-03-11 19:50:54349 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
350 p->nStep++;
351}
dandfa552f2018-06-02 21:04:28352static 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:54356 p->nValue = p->nStep;
dandfa552f2018-06-02 21:04:28357 if( p->nTotal>1 ){
dancc7a8502019-03-11 19:50:54358 double r = (double)p->nValue / (double)(p->nTotal-1);
dandfa552f2018-06-02 21:04:28359 sqlite3_result_double(pCtx, r);
360 }else{
danb7306f62018-06-21 19:20:39361 sqlite3_result_double(pCtx, 0.0);
dandfa552f2018-06-02 21:04:28362 }
dandfa552f2018-06-02 21:04:28363 }
364}
dancc7a8502019-03-11 19:50:54365#define percent_rankFinalizeFunc percent_rankValueFunc
dandfa552f2018-06-02 21:04:28366
dan9c277582018-06-20 09:23:49367/*
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:54371** GROUPS BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING
dan9c277582018-06-20 09:23:49372*/
danf1abe362018-06-04 08:22:09373static void cume_distStepFunc(
larrybrbc917382023-06-07 08:40:31374 sqlite3_context *pCtx,
danf1abe362018-06-04 08:22:09375 int nArg,
376 sqlite3_value **apArg
377){
378 struct CallCount *p;
dancc7a8502019-03-11 19:50:54379 UNUSED_PARAMETER(nArg); assert( nArg==0 );
drhd4a591d2019-03-26 16:21:11380 UNUSED_PARAMETER(apArg);
danf1abe362018-06-04 08:22:09381 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
drh5d6374f2018-07-10 23:31:17382 if( p ){
dancc7a8502019-03-11 19:50:54383 p->nTotal++;
danf1abe362018-06-04 08:22:09384 }
385}
dancc7a8502019-03-11 19:50:54386static void cume_distInvFunc(
larrybrbc917382023-06-07 08:40:31387 sqlite3_context *pCtx,
dancc7a8502019-03-11 19:50:54388 int nArg,
389 sqlite3_value **apArg
390){
391 struct CallCount *p;
392 UNUSED_PARAMETER(nArg); assert( nArg==0 );
drhd4a591d2019-03-26 16:21:11393 UNUSED_PARAMETER(apArg);
dancc7a8502019-03-11 19:50:54394 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
395 p->nStep++;
396}
danf1abe362018-06-04 08:22:09397static void cume_distValueFunc(sqlite3_context *pCtx){
398 struct CallCount *p;
dan0525b6f2019-03-18 21:19:40399 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, 0);
400 if( p ){
danf1abe362018-06-04 08:22:09401 double r = (double)(p->nStep) / (double)(p->nTotal);
402 sqlite3_result_double(pCtx, r);
403 }
404}
dancc7a8502019-03-11 19:50:54405#define cume_distFinalizeFunc cume_distValueFunc
danf1abe362018-06-04 08:22:09406
dan2a11bb22018-06-11 20:50:25407/*
408** Context object for ntile() window function.
409*/
dan6bc5c9e2018-06-04 18:55:11410struct 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:54420** ROWS CURRENT ROW AND UNBOUNDED FOLLOWING
dan6bc5c9e2018-06-04 18:55:11421*/
422static void ntileStepFunc(
larrybrbc917382023-06-07 08:40:31423 sqlite3_context *pCtx,
dan6bc5c9e2018-06-04 18:55:11424 int nArg,
425 sqlite3_value **apArg
426){
427 struct NtileCtx *p;
dancc7a8502019-03-11 19:50:54428 assert( nArg==1 ); UNUSED_PARAMETER(nArg);
dan6bc5c9e2018-06-04 18:55:11429 p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
drh5d6374f2018-07-10 23:31:17430 if( p ){
dan6bc5c9e2018-06-04 18:55:11431 if( p->nTotal==0 ){
432 p->nParam = sqlite3_value_int64(apArg[0]);
dan6bc5c9e2018-06-04 18:55:11433 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:54439 p->nTotal++;
dan6bc5c9e2018-06-04 18:55:11440 }
441}
dancc7a8502019-03-11 19:50:54442static void ntileInvFunc(
larrybrbc917382023-06-07 08:40:31443 sqlite3_context *pCtx,
dancc7a8502019-03-11 19:50:54444 int nArg,
445 sqlite3_value **apArg
446){
447 struct NtileCtx *p;
448 assert( nArg==1 ); UNUSED_PARAMETER(nArg);
drhd4a591d2019-03-26 16:21:11449 UNUSED_PARAMETER(apArg);
dancc7a8502019-03-11 19:50:54450 p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
451 p->iRow++;
452}
dan6bc5c9e2018-06-04 18:55:11453static 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:54459 sqlite3_result_int64(pCtx, p->iRow+1);
dan6bc5c9e2018-06-04 18:55:11460 }else{
461 i64 nLarge = p->nTotal - p->nParam*nSize;
462 i64 iSmall = nLarge*(nSize+1);
dancc7a8502019-03-11 19:50:54463 i64 iRow = p->iRow;
dan6bc5c9e2018-06-04 18:55:11464
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:54475#define ntileFinalizeFunc ntileValueFunc
dan6bc5c9e2018-06-04 18:55:11476
dan2a11bb22018-06-11 20:50:25477/*
478** Context object for last_value() window function.
479*/
dan1c5ed622018-06-05 16:16:17480struct LastValueCtx {
481 sqlite3_value *pVal;
482 int nVal;
483};
484
485/*
486** Implementation of last_value().
487*/
488static void last_valueStepFunc(
larrybrbc917382023-06-07 08:40:31489 sqlite3_context *pCtx,
dan1c5ed622018-06-05 16:16:17490 int nArg,
491 sqlite3_value **apArg
492){
493 struct LastValueCtx *p;
drhc7bf5712018-07-09 22:49:01494 UNUSED_PARAMETER(nArg);
dan9c277582018-06-20 09:23:49495 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
dan1c5ed622018-06-05 16:16:17496 if( p ){
497 sqlite3_value_free(p->pVal);
498 p->pVal = sqlite3_value_dup(apArg[0]);
dan6fde1792018-06-15 19:01:35499 if( p->pVal==0 ){
500 sqlite3_result_error_nomem(pCtx);
501 }else{
502 p->nVal++;
503 }
dan1c5ed622018-06-05 16:16:17504 }
505}
dan2a11bb22018-06-11 20:50:25506static void last_valueInvFunc(
larrybrbc917382023-06-07 08:40:31507 sqlite3_context *pCtx,
dan1c5ed622018-06-05 16:16:17508 int nArg,
509 sqlite3_value **apArg
510){
511 struct LastValueCtx *p;
drhc7bf5712018-07-09 22:49:01512 UNUSED_PARAMETER(nArg);
513 UNUSED_PARAMETER(apArg);
dan9c277582018-06-20 09:23:49514 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
515 if( ALWAYS(p) ){
dan1c5ed622018-06-05 16:16:17516 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:40525 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, 0);
dan1c5ed622018-06-05 16:16:17526 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:49532 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
dan1c5ed622018-06-05 16:16:17533 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:25540/*
drh19dc4d42018-07-08 01:02:26541** 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:25547*/
drh19dc4d42018-07-08 01:02:26548static 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:59559
drh19dc4d42018-07-08 01:02:26560/*
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:01574 UNUSED_PARAMETER(p); /*NO_TEST*/
575 UNUSED_PARAMETER(n); /*NO_TEST*/
576 UNUSED_PARAMETER(a); /*NO_TEST*/
drh19dc4d42018-07-08 01:02:26577 assert(0); /*NO_TEST*/
578} /*NO_TEST*/
drhc7bf5712018-07-09 22:49:01579static void noopValueFunc(sqlite3_context *p){ UNUSED_PARAMETER(p); /*no-op*/ }
dandfa552f2018-06-02 21:04:28580
drh19dc4d42018-07-08 01:02:26581/* Window functions that use all window interfaces: xStep, xFinal,
582** xValue, and xInverse */
583#define WINDOWFUNCALL(name,nArg,extra) { \
drhf9751072021-10-07 13:40:29584 nArg, (SQLITE_FUNC_BUILTIN|SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
dan1c5ed622018-06-05 16:16:17585 name ## StepFunc, name ## FinalizeFunc, name ## ValueFunc, \
drhc7bf5712018-07-09 22:49:01586 name ## InvFunc, name ## Name, {0} \
dan1c5ed622018-06-05 16:16:17587}
588
drh19dc4d42018-07-08 01:02:26589/* 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:29592 nArg, (SQLITE_FUNC_BUILTIN|SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
drh19dc4d42018-07-08 01:02:26593 noopStepFunc, noopValueFunc, noopValueFunc, \
drhc7bf5712018-07-09 22:49:01594 noopStepFunc, name ## Name, {0} \
drh19dc4d42018-07-08 01:02:26595}
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:29601 nArg, (SQLITE_FUNC_BUILTIN|SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
drh19dc4d42018-07-08 01:02:26602 name ## StepFunc, name ## ValueFunc, name ## ValueFunc, \
drhc7bf5712018-07-09 22:49:01603 noopStepFunc, name ## Name, {0} \
drh19dc4d42018-07-08 01:02:26604}
605
606
dandfa552f2018-06-02 21:04:28607/*
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:26612 WINDOWFUNCX(row_number, 0, 0),
613 WINDOWFUNCX(dense_rank, 0, 0),
614 WINDOWFUNCX(rank, 0, 0),
dancc7a8502019-03-11 19:50:54615 WINDOWFUNCALL(percent_rank, 0, 0),
616 WINDOWFUNCALL(cume_dist, 0, 0),
617 WINDOWFUNCALL(ntile, 1, 0),
drh19dc4d42018-07-08 01:02:26618 WINDOWFUNCALL(last_value, 1, 0),
dana0f6b832019-03-14 16:36:20619 WINDOWFUNCALL(nth_value, 2, 0),
danc782a812019-03-15 20:46:19620 WINDOWFUNCALL(first_value, 1, 0),
drh19dc4d42018-07-08 01:02:26621 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:28627 };
628 sqlite3InsertBuiltinFuncs(aWindowFuncs, ArraySize(aWindowFuncs));
629}
630
dane7c9ca42019-02-16 17:27:51631static 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:38642/*
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**
larrybrbc917382023-06-07 08:40:31650** * If the OVER clause referred to a named window (as in "max(x) OVER win"),
danc0bb4452018-06-12 20:53:38651** 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:27659void sqlite3WindowUpdate(
larrybrbc917382023-06-07 08:40:31660 Parse *pParse,
danc0bb4452018-06-12 20:53:38661 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:27664){
drhfc15f4c2019-03-28 13:03:41665 if( pWin->zName && pWin->eFrmType==0 ){
dane7c9ca42019-02-16 17:27:51666 Window *p = windowFind(pParse, pList, pWin->zName);
667 if( p==0 ) return;
dane3bf6322018-06-08 20:58:27668 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:41674 pWin->eFrmType = p->eFrmType;
danc782a812019-03-15 20:46:19675 pWin->eExclude = p->eExclude;
dane7c9ca42019-02-16 17:27:51676 }else{
677 sqlite3WindowChain(pParse, pWin, pList);
dane3bf6322018-06-08 20:58:27678 }
drhfc15f4c2019-03-28 13:03:41679 if( (pWin->eFrmType==TK_RANGE)
larrybrbc917382023-06-07 08:40:31680 && (pWin->pStart || pWin->pEnd)
dan72b9fdc2019-03-09 20:49:17681 && (pWin->pOrderBy==0 || pWin->pOrderBy->nExpr!=1)
682 ){
larrybrbc917382023-06-07 08:40:31683 sqlite3ErrorMsg(pParse,
dan72b9fdc2019-03-09 20:49:17684 "RANGE with offset PRECEDING/FOLLOWING requires one ORDER BY expression"
685 );
686 }else
dandfa552f2018-06-02 21:04:28687 if( pFunc->funcFlags & SQLITE_FUNC_WINDOW ){
688 sqlite3 *db = pParse->db;
dan8b985602018-06-09 17:43:45689 if( pWin->pFilter ){
larrybrbc917382023-06-07 08:40:31690 sqlite3ErrorMsg(pParse,
dan8b985602018-06-09 17:43:45691 "FILTER clause may only be used with aggregate window functions"
692 );
dancc7a8502019-03-11 19:50:54693 }else{
694 struct WindowUpdate {
695 const char *zFunc;
drhfc15f4c2019-03-28 13:03:41696 int eFrmType;
dancc7a8502019-03-11 19:50:54697 int eStart;
698 int eEnd;
699 } aUp[] = {
larrybrbc917382023-06-07 08:40:31700 { 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 },
707 { lagName, TK_ROWS, TK_UNBOUNDED, TK_CURRENT },
dancc7a8502019-03-11 19:50:54708 };
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:41715 pWin->eFrmType = aUp[i].eFrmType;
dancc7a8502019-03-11 19:50:54716 pWin->eStart = aUp[i].eStart;
717 pWin->eEnd = aUp[i].eEnd;
dana0f6b832019-03-14 16:36:20718 pWin->eExclude = 0;
dancc7a8502019-03-11 19:50:54719 if( pWin->eStart==TK_FOLLOWING ){
720 pWin->pStart = sqlite3Expr(db, TK_INTEGER, "1");
721 }
722 break;
723 }
724 }
dandfa552f2018-06-02 21:04:28725 }
726 }
drh105dcaa2022-03-10 16:01:14727 pWin->pWFunc = pFunc;
dandfa552f2018-06-02 21:04:28728}
729
danc0bb4452018-06-12 20:53:38730/*
731** Context object passed through sqlite3WalkExprList() to
732** selectWindowRewriteExprCb() by selectWindowRewriteEList().
733*/
dandfa552f2018-06-02 21:04:28734typedef struct WindowRewrite WindowRewrite;
735struct WindowRewrite {
736 Window *pWin;
danb556f262018-07-10 17:26:12737 SrcList *pSrc;
dandfa552f2018-06-02 21:04:28738 ExprList *pSub;
dan62742fd2019-07-08 12:01:39739 Table *pTab;
danb556f262018-07-10 17:26:12740 Select *pSubSelect; /* Current sub-select, if any */
dandfa552f2018-06-02 21:04:28741};
742
danc0bb4452018-06-12 20:53:38743/*
744** Callback function used by selectWindowRewriteEList(). If necessary,
larrybrbc917382023-06-07 08:40:31745** this function appends to the output expression-list and updates
danc0bb4452018-06-12 20:53:38746** expression (*ppExpr) in place.
747*/
dandfa552f2018-06-02 21:04:28748static int selectWindowRewriteExprCb(Walker *pWalker, Expr *pExpr){
749 struct WindowRewrite *p = pWalker->u.pRewrite;
750 Parse *pParse = pWalker->pParse;
drh55f66b32019-07-16 19:44:32751 assert( p!=0 );
752 assert( p->pWin!=0 );
dandfa552f2018-06-02 21:04:28753
danb556f262018-07-10 17:26:12754 /* 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:28772 switch( pExpr->op ){
773
774 case TK_FUNCTION:
drheda079c2018-09-20 19:02:15775 if( !ExprHasProperty(pExpr, EP_WinFunc) ){
dandfa552f2018-06-02 21:04:28776 break;
777 }else{
778 Window *pWin;
779 for(pWin=p->pWin; pWin; pWin=pWin->pNextWin){
drheda079c2018-09-20 19:02:15780 if( pExpr->y.pWin==pWin ){
dan2a11bb22018-06-11 20:50:25781 assert( pWin->pOwner==pExpr );
dandfa552f2018-06-02 21:04:28782 return WRC_Prune;
783 }
784 }
785 }
drh08b92082020-08-10 14:18:00786 /* no break */ deliberate_fall_through
dandfa552f2018-06-02 21:04:28787
drh017bdf72023-04-13 14:50:50788 case TK_IF_NULL_ROW:
dan73925692018-06-12 18:40:17789 case TK_AGG_FUNCTION:
dandfa552f2018-06-02 21:04:28790 case TK_COLUMN: {
dan62be2dc2019-11-23 15:10:28791 int iCol = -1;
drhd22ecfd2021-04-06 13:56:46792 if( pParse->db->mallocFailed ) return WRC_Abort;
dan62be2dc2019-11-23 15:10:28793 if( p->pSub ){
794 int i;
795 for(i=0; i<p->pSub->nExpr; i++){
796 if( 0==sqlite3ExprCompare(0, p->pSub->a[i].pExpr, pExpr, -1) ){
797 iCol = i;
798 break;
799 }
800 }
801 }
802 if( iCol<0 ){
803 Expr *pDup = sqlite3ExprDup(pParse->db, pExpr, 0);
dan43170432019-12-27 16:25:56804 if( pDup && pDup->op==TK_AGG_FUNCTION ) pDup->op = TK_FUNCTION;
dan62be2dc2019-11-23 15:10:28805 p->pSub = sqlite3ExprListAppend(pParse, p->pSub, pDup);
806 }
dandfa552f2018-06-02 21:04:28807 if( p->pSub ){
dan27da9072020-07-13 15:20:27808 int f = pExpr->flags & EP_Collate;
dandfa552f2018-06-02 21:04:28809 assert( ExprHasProperty(pExpr, EP_Static)==0 );
810 ExprSetProperty(pExpr, EP_Static);
811 sqlite3ExprDelete(pParse->db, pExpr);
812 ExprClearProperty(pExpr, EP_Static);
813 memset(pExpr, 0, sizeof(Expr));
814
815 pExpr->op = TK_COLUMN;
dan62be2dc2019-11-23 15:10:28816 pExpr->iColumn = (iCol<0 ? p->pSub->nExpr-1: iCol);
dandfa552f2018-06-02 21:04:28817 pExpr->iTable = p->pWin->iEphCsr;
dan62742fd2019-07-08 12:01:39818 pExpr->y.pTab = p->pTab;
dan27da9072020-07-13 15:20:27819 pExpr->flags = f;
dandfa552f2018-06-02 21:04:28820 }
drha2f142d2019-11-23 16:34:40821 if( pParse->db->mallocFailed ) return WRC_Abort;
dandfa552f2018-06-02 21:04:28822 break;
823 }
824
825 default: /* no-op */
826 break;
827 }
828
829 return WRC_Continue;
830}
danc0bb4452018-06-12 20:53:38831static int selectWindowRewriteSelectCb(Walker *pWalker, Select *pSelect){
danb556f262018-07-10 17:26:12832 struct WindowRewrite *p = pWalker->u.pRewrite;
833 Select *pSave = p->pSubSelect;
834 if( pSave==pSelect ){
835 return WRC_Continue;
836 }else{
837 p->pSubSelect = pSelect;
838 sqlite3WalkSelect(pWalker, pSelect);
839 p->pSubSelect = pSave;
840 }
danc0bb4452018-06-12 20:53:38841 return WRC_Prune;
842}
dandfa552f2018-06-02 21:04:28843
danc0bb4452018-06-12 20:53:38844
845/*
846** Iterate through each expression in expression-list pEList. For each:
847**
848** * TK_COLUMN,
849** * aggregate function, or
larrybrbc917382023-06-07 08:40:31850** * window function with a Window object that is not a member of the
danb556f262018-07-10 17:26:12851** Window list passed as the second argument (pWin).
danc0bb4452018-06-12 20:53:38852**
853** Append the node to output expression-list (*ppSub). And replace it
larrybrbc917382023-06-07 08:40:31854** with a TK_COLUMN that reads the (N-1)th element of table
danc0bb4452018-06-12 20:53:38855** pWin->iEphCsr, where N is the number of elements in (*ppSub) after
856** appending the new one.
857*/
dan13b08bb2018-06-15 20:46:12858static void selectWindowRewriteEList(
larrybrbc917382023-06-07 08:40:31859 Parse *pParse,
dandfa552f2018-06-02 21:04:28860 Window *pWin,
danb556f262018-07-10 17:26:12861 SrcList *pSrc,
dandfa552f2018-06-02 21:04:28862 ExprList *pEList, /* Rewrite expressions in this list */
dan62742fd2019-07-08 12:01:39863 Table *pTab,
dandfa552f2018-06-02 21:04:28864 ExprList **ppSub /* IN/OUT: Sub-select expression-list */
865){
866 Walker sWalker;
867 WindowRewrite sRewrite;
dandfa552f2018-06-02 21:04:28868
drh55f66b32019-07-16 19:44:32869 assert( pWin!=0 );
dandfa552f2018-06-02 21:04:28870 memset(&sWalker, 0, sizeof(Walker));
871 memset(&sRewrite, 0, sizeof(WindowRewrite));
872
873 sRewrite.pSub = *ppSub;
874 sRewrite.pWin = pWin;
danb556f262018-07-10 17:26:12875 sRewrite.pSrc = pSrc;
dan62742fd2019-07-08 12:01:39876 sRewrite.pTab = pTab;
dandfa552f2018-06-02 21:04:28877
878 sWalker.pParse = pParse;
879 sWalker.xExprCallback = selectWindowRewriteExprCb;
880 sWalker.xSelectCallback = selectWindowRewriteSelectCb;
881 sWalker.u.pRewrite = &sRewrite;
882
dan13b08bb2018-06-15 20:46:12883 (void)sqlite3WalkExprList(&sWalker, pEList);
dandfa552f2018-06-02 21:04:28884
885 *ppSub = sRewrite.pSub;
dandfa552f2018-06-02 21:04:28886}
887
danc0bb4452018-06-12 20:53:38888/*
889** Append a copy of each expression in expression-list pAppend to
890** expression list pList. Return a pointer to the result list.
891*/
dandfa552f2018-06-02 21:04:28892static ExprList *exprListAppendList(
893 Parse *pParse, /* Parsing context */
894 ExprList *pList, /* List to which to append. Might be NULL */
dan08f6de72019-05-10 14:26:32895 ExprList *pAppend, /* List of values to append. Might be NULL */
896 int bIntToNull
dandfa552f2018-06-02 21:04:28897){
898 if( pAppend ){
899 int i;
900 int nInit = pList ? pList->nExpr : 0;
901 for(i=0; i<pAppend->nExpr; i++){
drh57f90182021-04-03 23:30:33902 sqlite3 *db = pParse->db;
903 Expr *pDup = sqlite3ExprDup(db, pAppend->a[i].pExpr, 0);
drh4c4a2572021-04-06 12:50:24904 if( db->mallocFailed ){
905 sqlite3ExprDelete(db, pDup);
906 break;
907 }
908 if( bIntToNull ){
danefa78882020-05-11 10:55:24909 int iDummy;
910 Expr *pSub;
dana261c022021-06-23 11:12:48911 pSub = sqlite3ExprSkipCollateAndLikely(pDup);
drh4703b7d2024-06-06 15:03:16912 if( sqlite3ExprIsInteger(pSub, &iDummy, 0) ){
danefa78882020-05-11 10:55:24913 pSub->op = TK_NULL;
914 pSub->flags &= ~(EP_IntValue|EP_IsTrue|EP_IsFalse);
915 pSub->u.zToken = 0;
916 }
dan08f6de72019-05-10 14:26:32917 }
dandfa552f2018-06-02 21:04:28918 pList = sqlite3ExprListAppend(pParse, pList, pDup);
drhd88fd532022-05-02 20:49:30919 if( pList ) pList->a[nInit+i].fg.sortFlags = pAppend->a[i].fg.sortFlags;
dandfa552f2018-06-02 21:04:28920 }
921 }
922 return pList;
923}
924
925/*
drhc37577b2020-05-24 03:38:37926** When rewriting a query, if the new subquery in the FROM clause
927** contains TK_AGG_FUNCTION nodes that refer to an outer query,
928** then we have to increase the Expr->op2 values of those nodes
929** due to the extra subquery layer that was added.
930**
931** See also the incrAggDepth() routine in resolve.c
932*/
933static int sqlite3WindowExtraAggFuncDepth(Walker *pWalker, Expr *pExpr){
934 if( pExpr->op==TK_AGG_FUNCTION
935 && pExpr->op2>=pWalker->walkerDepth
936 ){
937 pExpr->op2++;
938 }
939 return WRC_Continue;
940}
941
drh4752bbd2021-05-07 15:46:36942static int disallowAggregatesInOrderByCb(Walker *pWalker, Expr *pExpr){
943 if( pExpr->op==TK_AGG_FUNCTION && pExpr->pAggInfo==0 ){
drhf9751072021-10-07 13:40:29944 assert( !ExprHasProperty(pExpr, EP_IntValue) );
945 sqlite3ErrorMsg(pWalker->pParse,
drh4752bbd2021-05-07 15:46:36946 "misuse of aggregate: %s()", pExpr->u.zToken);
947 }
948 return WRC_Continue;
949}
950
drhc37577b2020-05-24 03:38:37951/*
dandfa552f2018-06-02 21:04:28952** If the SELECT statement passed as the second argument does not invoke
larrybrbc917382023-06-07 08:40:31953** any SQL window functions, this function is a no-op. Otherwise, it
dandfa552f2018-06-02 21:04:28954** rewrites the SELECT statement so that window function xStep functions
danc0bb4452018-06-12 20:53:38955** are invoked in the correct order as described under "SELECT REWRITING"
956** at the top of this file.
dandfa552f2018-06-02 21:04:28957*/
958int sqlite3WindowRewrite(Parse *pParse, Select *p){
959 int rc = SQLITE_OK;
drh5e121a52022-03-10 16:26:00960 if( p->pWin
961 && p->pPrior==0
962 && ALWAYS((p->selFlags & SF_WinRewrite)==0)
drhfde30432022-03-10 21:04:49963 && ALWAYS(!IN_RENAME_OBJECT)
drh5e121a52022-03-10 16:26:00964 ){
dandfa552f2018-06-02 21:04:28965 Vdbe *v = sqlite3GetVdbe(pParse);
dandfa552f2018-06-02 21:04:28966 sqlite3 *db = pParse->db;
967 Select *pSub = 0; /* The subquery */
968 SrcList *pSrc = p->pSrc;
969 Expr *pWhere = p->pWhere;
970 ExprList *pGroupBy = p->pGroupBy;
971 Expr *pHaving = p->pHaving;
972 ExprList *pSort = 0;
973
974 ExprList *pSublist = 0; /* Expression list for sub-query */
drh067b92b2020-06-19 15:24:12975 Window *pMWin = p->pWin; /* Main window object */
dandfa552f2018-06-02 21:04:28976 Window *pWin; /* Window object iterator */
dan62742fd2019-07-08 12:01:39977 Table *pTab;
drh89636622020-06-07 17:33:18978 Walker w;
979
dan553948e2020-03-16 18:52:53980 u32 selFlags = p->selFlags;
dan62742fd2019-07-08 12:01:39981
982 pTab = sqlite3DbMallocZero(db, sizeof(Table));
983 if( pTab==0 ){
drh86541862019-12-19 20:37:32984 return sqlite3ErrorToParser(db, SQLITE_NOMEM);
dan62742fd2019-07-08 12:01:39985 }
drh89636622020-06-07 17:33:18986 sqlite3AggInfoPersistWalkerInit(&w, pParse);
987 sqlite3WalkSelect(&w, p);
drh4752bbd2021-05-07 15:46:36988 if( (p->selFlags & SF_Aggregate)==0 ){
989 w.xExprCallback = disallowAggregatesInOrderByCb;
dan3d691fd2021-05-19 14:49:51990 w.xSelectCallback = 0;
drh4752bbd2021-05-07 15:46:36991 sqlite3WalkExprList(&w, p->pOrderBy);
992 }
dandfa552f2018-06-02 21:04:28993
994 p->pSrc = 0;
995 p->pWhere = 0;
996 p->pGroupBy = 0;
997 p->pHaving = 0;
drhce250072025-02-21 17:03:22998 p->selFlags &= ~(u32)SF_Aggregate;
drhba016342019-11-14 13:24:04999 p->selFlags |= SF_WinRewrite;
dandfa552f2018-06-02 21:04:281000
danf02cdd32018-06-27 19:48:501001 /* Create the ORDER BY clause for the sub-select. This is the concatenation
1002 ** of the window PARTITION and ORDER BY clauses. Then, if this makes it
1003 ** redundant, remove the ORDER BY from the parent SELECT. */
dand8d2fb92019-12-27 15:31:471004 pSort = exprListAppendList(pParse, 0, pMWin->pPartition, 1);
dan08f6de72019-05-10 14:26:321005 pSort = exprListAppendList(pParse, pSort, pMWin->pOrderBy, 1);
dan0e3c50c2019-08-07 17:45:371006 if( pSort && p->pOrderBy && p->pOrderBy->nExpr<=pSort->nExpr ){
1007 int nSave = pSort->nExpr;
1008 pSort->nExpr = p->pOrderBy->nExpr;
danf02cdd32018-06-27 19:48:501009 if( sqlite3ExprListCompare(pSort, p->pOrderBy, -1)==0 ){
1010 sqlite3ExprListDelete(db, p->pOrderBy);
1011 p->pOrderBy = 0;
1012 }
dan0e3c50c2019-08-07 17:45:371013 pSort->nExpr = nSave;
danf02cdd32018-06-27 19:48:501014 }
1015
dandfa552f2018-06-02 21:04:281016 /* Assign a cursor number for the ephemeral table used to buffer rows.
1017 ** The OpenEphemeral instruction is coded later, after it is known how
1018 ** many columns the table will have. */
1019 pMWin->iEphCsr = pParse->nTab++;
dan680f6e82019-03-04 21:07:111020 pParse->nTab += 3;
dandfa552f2018-06-02 21:04:281021
dan62742fd2019-07-08 12:01:391022 selectWindowRewriteEList(pParse, pMWin, pSrc, p->pEList, pTab, &pSublist);
1023 selectWindowRewriteEList(pParse, pMWin, pSrc, p->pOrderBy, pTab, &pSublist);
dandfa552f2018-06-02 21:04:281024 pMWin->nBufferCol = (pSublist ? pSublist->nExpr : 0);
1025
larrybrbc917382023-06-07 08:40:311026 /* Append the PARTITION BY and ORDER BY expressions to the to the
1027 ** sub-select expression list. They are required to figure out where
danf02cdd32018-06-27 19:48:501028 ** boundaries for partitions and sets of peer rows lie. */
dan08f6de72019-05-10 14:26:321029 pSublist = exprListAppendList(pParse, pSublist, pMWin->pPartition, 0);
1030 pSublist = exprListAppendList(pParse, pSublist, pMWin->pOrderBy, 0);
dandfa552f2018-06-02 21:04:281031
1032 /* Append the arguments passed to each window function to the
1033 ** sub-select expression list. Also allocate two registers for each
1034 ** window function - one for the accumulator, another for interim
1035 ** results. */
1036 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
drha4eeccd2021-10-07 17:43:301037 ExprList *pArgs;
1038 assert( ExprUseXList(pWin->pOwner) );
drh5e121a52022-03-10 16:26:001039 assert( pWin->pWFunc!=0 );
drha4eeccd2021-10-07 17:43:301040 pArgs = pWin->pOwner->x.pList;
drh194b8d52023-11-09 12:08:161041 if( pWin->pWFunc->funcFlags & SQLITE_SUBTYPE ){
dane2ba6df2019-09-07 18:20:431042 selectWindowRewriteEList(pParse, pMWin, pSrc, pArgs, pTab, &pSublist);
1043 pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);
1044 pWin->bExprArgs = 1;
1045 }else{
1046 pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);
1047 pSublist = exprListAppendList(pParse, pSublist, pArgs, 0);
1048 }
dan8b985602018-06-09 17:43:451049 if( pWin->pFilter ){
1050 Expr *pFilter = sqlite3ExprDup(db, pWin->pFilter, 0);
1051 pSublist = sqlite3ExprListAppend(pParse, pSublist, pFilter);
1052 }
dandfa552f2018-06-02 21:04:281053 pWin->regAccum = ++pParse->nMem;
1054 pWin->regResult = ++pParse->nMem;
1055 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
1056 }
1057
dan9c277582018-06-20 09:23:491058 /* If there is no ORDER BY or PARTITION BY clause, and the window
1059 ** function accepts zero arguments, and there are no other columns
1060 ** selected (e.g. "SELECT row_number() OVER () FROM t1"), it is possible
larrybrbc917382023-06-07 08:40:311061 ** that pSublist is still NULL here. Add a constant expression here to
1062 ** keep everything legal in this case.
dan9c277582018-06-20 09:23:491063 */
1064 if( pSublist==0 ){
larrybrbc917382023-06-07 08:40:311065 pSublist = sqlite3ExprListAppend(pParse, 0,
drh5776ee52019-09-23 12:38:101066 sqlite3Expr(db, TK_INTEGER, "0")
dan9c277582018-06-20 09:23:491067 );
1068 }
1069
dandfa552f2018-06-02 21:04:281070 pSub = sqlite3SelectNew(
1071 pParse, pSublist, pSrc, pWhere, pGroupBy, pHaving, pSort, 0, 0
1072 );
drh5d7aef12022-11-22 19:49:161073 TREETRACE(0x40,pParse,pSub,
drh9216de82020-06-11 00:57:091074 ("New window-function subquery in FROM clause of (%u/%p)\n",
1075 p->selId, p));
drh29c992c2019-01-17 15:40:411076 p->pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
drh82456a62021-09-13 18:16:151077 assert( pSub!=0 || p->pSrc==0 ); /* Due to db->mallocFailed test inside
1078 ** of sqlite3DbMallocRawNN() called from
1079 ** sqlite3SrcListAppend() */
drh1521ca42024-08-19 22:48:301080 if( p->pSrc==0 ){
1081 sqlite3SelectDelete(db, pSub);
1082 }else if( sqlite3SrcItemAttachSubquery(pParse, &p->pSrc->a[0], pSub, 0) ){
dan62742fd2019-07-08 12:01:391083 Table *pTab2;
dan05a377f2023-01-28 21:06:151084 p->pSrc->a[0].fg.isCorrelated = 1;
dandfa552f2018-06-02 21:04:281085 sqlite3SrcListAssignCursors(pParse, p->pSrc);
drhbb301232021-07-15 19:29:431086 pSub->selFlags |= SF_Expanded|SF_OrderByReqd;
drh96fb16e2019-08-06 14:37:241087 pTab2 = sqlite3ResultSetOfSelect(pParse, pSub, SQLITE_AFF_NONE);
dan553948e2020-03-16 18:52:531088 pSub->selFlags |= (selFlags & SF_Aggregate);
dan62742fd2019-07-08 12:01:391089 if( pTab2==0 ){
drha9ebfe22019-12-25 23:54:211090 /* Might actually be some other kind of error, but in that case
1091 ** pParse->nErr will be set, so if SQLITE_NOMEM is set, we will get
1092 ** the correct error message regardless. */
dandfa552f2018-06-02 21:04:281093 rc = SQLITE_NOMEM;
1094 }else{
dan62742fd2019-07-08 12:01:391095 memcpy(pTab, pTab2, sizeof(Table));
1096 pTab->tabFlags |= TF_Ephemeral;
drhb204b6a2024-08-17 23:23:231097 p->pSrc->a[0].pSTab = pTab;
dan62742fd2019-07-08 12:01:391098 pTab = pTab2;
drhc37577b2020-05-24 03:38:371099 memset(&w, 0, sizeof(w));
1100 w.xExprCallback = sqlite3WindowExtraAggFuncDepth;
1101 w.xSelectCallback = sqlite3WalkerDepthIncrease;
1102 w.xSelectCallback2 = sqlite3WalkerDepthDecrease;
1103 sqlite3WalkSelect(&w, pSub);
dandfa552f2018-06-02 21:04:281104 }
dan6fde1792018-06-15 19:01:351105 }
1106 if( db->mallocFailed ) rc = SQLITE_NOMEM;
drh6d64b4a2021-11-07 23:33:011107
1108 /* Defer deleting the temporary table pTab because if an error occurred,
1109 ** there could still be references to that table embedded in the
1110 ** result-set or ORDER BY clause of the SELECT statement p. */
1111 sqlite3ParserAddCleanup(pParse, sqlite3DbFree, pTab);
dandfa552f2018-06-02 21:04:281112 }
1113
drh1da88b52022-01-24 19:38:561114 assert( rc==SQLITE_OK || pParse->nErr!=0 );
dandfa552f2018-06-02 21:04:281115 return rc;
1116}
1117
danc0bb4452018-06-12 20:53:381118/*
drhe2094572019-07-22 19:01:381119** Unlink the Window object from the Select to which it is attached,
1120** if it is attached.
1121*/
1122void sqlite3WindowUnlinkFromSelect(Window *p){
1123 if( p->ppThis ){
1124 *p->ppThis = p->pNextWin;
1125 if( p->pNextWin ) p->pNextWin->ppThis = p->ppThis;
1126 p->ppThis = 0;
1127 }
1128}
1129
1130/*
danc0bb4452018-06-12 20:53:381131** Free the Window object passed as the second argument.
1132*/
dan86fb6e12018-05-16 20:58:071133void sqlite3WindowDelete(sqlite3 *db, Window *p){
1134 if( p ){
drhe2094572019-07-22 19:01:381135 sqlite3WindowUnlinkFromSelect(p);
dan86fb6e12018-05-16 20:58:071136 sqlite3ExprDelete(db, p->pFilter);
1137 sqlite3ExprListDelete(db, p->pPartition);
1138 sqlite3ExprListDelete(db, p->pOrderBy);
1139 sqlite3ExprDelete(db, p->pEnd);
1140 sqlite3ExprDelete(db, p->pStart);
dane3bf6322018-06-08 20:58:271141 sqlite3DbFree(db, p->zName);
dane7c9ca42019-02-16 17:27:511142 sqlite3DbFree(db, p->zBase);
dan86fb6e12018-05-16 20:58:071143 sqlite3DbFree(db, p);
1144 }
1145}
1146
danc0bb4452018-06-12 20:53:381147/*
1148** Free the linked list of Window objects starting at the second argument.
1149*/
dane3bf6322018-06-08 20:58:271150void sqlite3WindowListDelete(sqlite3 *db, Window *p){
1151 while( p ){
1152 Window *pNext = p->pNextWin;
1153 sqlite3WindowDelete(db, p);
1154 p = pNext;
1155 }
1156}
1157
danc0bb4452018-06-12 20:53:381158/*
drhe4984a22018-07-06 17:19:201159** The argument expression is an PRECEDING or FOLLOWING offset. The
1160** value should be a non-negative integer. If the value is not a
1161** constant, change it to NULL. The fact that it is then a non-negative
1162** integer will be caught later. But it is important not to leave
1163** variable values in the expression tree.
1164*/
1165static Expr *sqlite3WindowOffsetExpr(Parse *pParse, Expr *pExpr){
drhf6965912024-03-16 13:18:481166 if( 0==sqlite3ExprIsConstant(0,pExpr) ){
danfb8ac322019-01-16 12:05:221167 if( IN_RENAME_OBJECT ) sqlite3RenameExprUnmap(pParse, pExpr);
drhe4984a22018-07-06 17:19:201168 sqlite3ExprDelete(pParse->db, pExpr);
1169 pExpr = sqlite3ExprAlloc(pParse->db, TK_NULL, 0, 0);
1170 }
1171 return pExpr;
1172}
1173
1174/*
1175** Allocate and return a new Window object describing a Window Definition.
danc0bb4452018-06-12 20:53:381176*/
dan86fb6e12018-05-16 20:58:071177Window *sqlite3WindowAlloc(
drhe4984a22018-07-06 17:19:201178 Parse *pParse, /* Parsing context */
drhfc15f4c2019-03-28 13:03:411179 int eType, /* Frame type. TK_RANGE, TK_ROWS, TK_GROUPS, or 0 */
drhe4984a22018-07-06 17:19:201180 int eStart, /* Start type: CURRENT, PRECEDING, FOLLOWING, UNBOUNDED */
1181 Expr *pStart, /* Start window size if TK_PRECEDING or FOLLOWING */
1182 int eEnd, /* End type: CURRENT, FOLLOWING, TK_UNBOUNDED, PRECEDING */
dand35300f2019-03-14 20:53:211183 Expr *pEnd, /* End window size if TK_FOLLOWING or PRECEDING */
1184 u8 eExclude /* EXCLUDE clause */
dan86fb6e12018-05-16 20:58:071185){
dan7a606e12018-07-05 18:34:531186 Window *pWin = 0;
dane7c9ca42019-02-16 17:27:511187 int bImplicitFrame = 0;
dan7a606e12018-07-05 18:34:531188
drhe4984a22018-07-06 17:19:201189 /* Parser assures the following: */
dan6c75b392019-03-08 20:02:521190 assert( eType==0 || eType==TK_RANGE || eType==TK_ROWS || eType==TK_GROUPS );
drhe4984a22018-07-06 17:19:201191 assert( eStart==TK_CURRENT || eStart==TK_PRECEDING
1192 || eStart==TK_UNBOUNDED || eStart==TK_FOLLOWING );
1193 assert( eEnd==TK_CURRENT || eEnd==TK_FOLLOWING
1194 || eEnd==TK_UNBOUNDED || eEnd==TK_PRECEDING );
1195 assert( (eStart==TK_PRECEDING || eStart==TK_FOLLOWING)==(pStart!=0) );
1196 assert( (eEnd==TK_FOLLOWING || eEnd==TK_PRECEDING)==(pEnd!=0) );
1197
dane7c9ca42019-02-16 17:27:511198 if( eType==0 ){
1199 bImplicitFrame = 1;
1200 eType = TK_RANGE;
1201 }
drhe4984a22018-07-06 17:19:201202
drhe4984a22018-07-06 17:19:201203 /* Additionally, the
dan5d764ac2018-07-06 14:15:491204 ** starting boundary type may not occur earlier in the following list than
1205 ** the ending boundary type:
1206 **
1207 ** UNBOUNDED PRECEDING
1208 ** <expr> PRECEDING
1209 ** CURRENT ROW
1210 ** <expr> FOLLOWING
1211 ** UNBOUNDED FOLLOWING
1212 **
1213 ** The parser ensures that "UNBOUNDED PRECEDING" cannot be used as an ending
1214 ** boundary, and than "UNBOUNDED FOLLOWING" cannot be used as a starting
1215 ** frame boundary.
1216 */
drhe4984a22018-07-06 17:19:201217 if( (eStart==TK_CURRENT && eEnd==TK_PRECEDING)
dan5d764ac2018-07-06 14:15:491218 || (eStart==TK_FOLLOWING && (eEnd==TK_PRECEDING || eEnd==TK_CURRENT))
1219 ){
dan72b9fdc2019-03-09 20:49:171220 sqlite3ErrorMsg(pParse, "unsupported frame specification");
drhe4984a22018-07-06 17:19:201221 goto windowAllocErr;
dan7a606e12018-07-05 18:34:531222 }
dan86fb6e12018-05-16 20:58:071223
drhe4984a22018-07-06 17:19:201224 pWin = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
1225 if( pWin==0 ) goto windowAllocErr;
drhfc15f4c2019-03-28 13:03:411226 pWin->eFrmType = eType;
drhe4984a22018-07-06 17:19:201227 pWin->eStart = eStart;
1228 pWin->eEnd = eEnd;
drh94809082019-04-02 17:45:561229 if( eExclude==0 && OptimizationDisabled(pParse->db, SQLITE_WindowFunc) ){
dan108e6b22019-03-18 18:55:351230 eExclude = TK_NO;
1231 }
dand35300f2019-03-14 20:53:211232 pWin->eExclude = eExclude;
dane7c9ca42019-02-16 17:27:511233 pWin->bImplicitFrame = bImplicitFrame;
drhe4984a22018-07-06 17:19:201234 pWin->pEnd = sqlite3WindowOffsetExpr(pParse, pEnd);
1235 pWin->pStart = sqlite3WindowOffsetExpr(pParse, pStart);
dan86fb6e12018-05-16 20:58:071236 return pWin;
drhe4984a22018-07-06 17:19:201237
1238windowAllocErr:
1239 sqlite3ExprDelete(pParse->db, pEnd);
1240 sqlite3ExprDelete(pParse->db, pStart);
1241 return 0;
dan86fb6e12018-05-16 20:58:071242}
1243
danc0bb4452018-06-12 20:53:381244/*
dane7c9ca42019-02-16 17:27:511245** Attach PARTITION and ORDER BY clauses pPartition and pOrderBy to window
1246** pWin. Also, if parameter pBase is not NULL, set pWin->zBase to the
1247** equivalent nul-terminated string.
1248*/
1249Window *sqlite3WindowAssemble(
larrybrbc917382023-06-07 08:40:311250 Parse *pParse,
1251 Window *pWin,
1252 ExprList *pPartition,
1253 ExprList *pOrderBy,
dane7c9ca42019-02-16 17:27:511254 Token *pBase
1255){
1256 if( pWin ){
1257 pWin->pPartition = pPartition;
1258 pWin->pOrderBy = pOrderBy;
1259 if( pBase ){
1260 pWin->zBase = sqlite3DbStrNDup(pParse->db, pBase->z, pBase->n);
1261 }
1262 }else{
1263 sqlite3ExprListDelete(pParse->db, pPartition);
1264 sqlite3ExprListDelete(pParse->db, pOrderBy);
1265 }
1266 return pWin;
1267}
1268
1269/*
larrybrbc917382023-06-07 08:40:311270** Window *pWin has just been created from a WINDOW clause. Token pBase
dane7c9ca42019-02-16 17:27:511271** is the base window. Earlier windows from the same WINDOW clause are
1272** stored in the linked list starting at pWin->pNextWin. This function
1273** either updates *pWin according to the base specification, or else
1274** leaves an error in pParse.
1275*/
1276void sqlite3WindowChain(Parse *pParse, Window *pWin, Window *pList){
1277 if( pWin->zBase ){
1278 sqlite3 *db = pParse->db;
1279 Window *pExist = windowFind(pParse, pList, pWin->zBase);
1280 if( pExist ){
1281 const char *zErr = 0;
1282 /* Check for errors */
1283 if( pWin->pPartition ){
1284 zErr = "PARTITION clause";
1285 }else if( pExist->pOrderBy && pWin->pOrderBy ){
1286 zErr = "ORDER BY clause";
1287 }else if( pExist->bImplicitFrame==0 ){
1288 zErr = "frame specification";
1289 }
1290 if( zErr ){
larrybrbc917382023-06-07 08:40:311291 sqlite3ErrorMsg(pParse,
dane7c9ca42019-02-16 17:27:511292 "cannot override %s of window: %s", zErr, pWin->zBase
1293 );
1294 }else{
1295 pWin->pPartition = sqlite3ExprListDup(db, pExist->pPartition, 0);
1296 if( pExist->pOrderBy ){
1297 assert( pWin->pOrderBy==0 );
1298 pWin->pOrderBy = sqlite3ExprListDup(db, pExist->pOrderBy, 0);
1299 }
1300 sqlite3DbFree(db, pWin->zBase);
1301 pWin->zBase = 0;
1302 }
1303 }
1304 }
1305}
1306
1307/*
danc0bb4452018-06-12 20:53:381308** Attach window object pWin to expression p.
1309*/
dan4f9adee2019-07-13 16:22:501310void sqlite3WindowAttach(Parse *pParse, Expr *p, Window *pWin){
dan86fb6e12018-05-16 20:58:071311 if( p ){
drheda079c2018-09-20 19:02:151312 assert( p->op==TK_FUNCTION );
dan4f9adee2019-07-13 16:22:501313 assert( pWin );
drh4e254642023-10-19 18:07:581314 assert( ExprIsFullSize(p) );
dan4f9adee2019-07-13 16:22:501315 p->y.pWin = pWin;
drh4e254642023-10-19 18:07:581316 ExprSetProperty(p, EP_WinFunc|EP_FullSize);
dan4f9adee2019-07-13 16:22:501317 pWin->pOwner = p;
1318 if( (p->flags & EP_Distinct) && pWin->eFrmType!=TK_FILTER ){
1319 sqlite3ErrorMsg(pParse,
1320 "DISTINCT is not supported for window functions"
1321 );
dane33f6e72018-07-06 07:42:421322 }
dan86fb6e12018-05-16 20:58:071323 }else{
1324 sqlite3WindowDelete(pParse->db, pWin);
1325 }
1326}
dane2f781b2018-05-17 19:24:081327
1328/*
dana3fcc002019-08-15 13:53:221329** Possibly link window pWin into the list at pSel->pWin (window functions
1330** to be processed as part of SELECT statement pSel). The window is linked
1331** in if either (a) there are no other windows already linked to this
1332** SELECT, or (b) the windows already linked use a compatible window frame.
1333*/
1334void sqlite3WindowLink(Select *pSel, Window *pWin){
dan903fdd42021-02-22 20:56:131335 if( pSel ){
1336 if( 0==pSel->pWin || 0==sqlite3WindowCompare(0, pSel->pWin, pWin, 0) ){
1337 pWin->pNextWin = pSel->pWin;
1338 if( pSel->pWin ){
1339 pSel->pWin->ppThis = &pWin->pNextWin;
1340 }
1341 pSel->pWin = pWin;
1342 pWin->ppThis = &pSel->pWin;
1343 }else{
1344 if( sqlite3ExprListCompare(pWin->pPartition, pSel->pWin->pPartition,-1) ){
1345 pSel->selFlags |= SF_MultiPart;
1346 }
dana3fcc002019-08-15 13:53:221347 }
dana3fcc002019-08-15 13:53:221348 }
1349}
1350
1351/*
danfbb6e9f2020-01-09 20:11:291352** Return 0 if the two window objects are identical, 1 if they are
1353** different, or 2 if it cannot be determined if the objects are identical
1354** or not. Identical window objects can be processed in a single scan.
dane2f781b2018-05-17 19:24:081355*/
drh1580d502021-09-25 17:07:571356int sqlite3WindowCompare(
1357 const Parse *pParse,
1358 const Window *p1,
1359 const Window *p2,
1360 int bFilter
1361){
danfbb6e9f2020-01-09 20:11:291362 int res;
drha2f142d2019-11-23 16:34:401363 if( NEVER(p1==0) || NEVER(p2==0) ) return 1;
drhfc15f4c2019-03-28 13:03:411364 if( p1->eFrmType!=p2->eFrmType ) return 1;
dane2f781b2018-05-17 19:24:081365 if( p1->eStart!=p2->eStart ) return 1;
1366 if( p1->eEnd!=p2->eEnd ) return 1;
dana0f6b832019-03-14 16:36:201367 if( p1->eExclude!=p2->eExclude ) return 1;
dane2f781b2018-05-17 19:24:081368 if( sqlite3ExprCompare(pParse, p1->pStart, p2->pStart, -1) ) return 1;
1369 if( sqlite3ExprCompare(pParse, p1->pEnd, p2->pEnd, -1) ) return 1;
danfbb6e9f2020-01-09 20:11:291370 if( (res = sqlite3ExprListCompare(p1->pPartition, p2->pPartition, -1)) ){
1371 return res;
1372 }
1373 if( (res = sqlite3ExprListCompare(p1->pOrderBy, p2->pOrderBy, -1)) ){
1374 return res;
1375 }
dan4f9adee2019-07-13 16:22:501376 if( bFilter ){
danfbb6e9f2020-01-09 20:11:291377 if( (res = sqlite3ExprCompare(pParse, p1->pFilter, p2->pFilter, -1)) ){
1378 return res;
1379 }
dan4f9adee2019-07-13 16:22:501380 }
dane2f781b2018-05-17 19:24:081381 return 0;
1382}
1383
dan13078ca2018-06-13 20:29:381384
1385/*
1386** This is called by code in select.c before it calls sqlite3WhereBegin()
1387** to begin iterating through the sub-query results. It is used to allocate
1388** and initialize registers and cursors used by sqlite3WindowCodeStep().
1389*/
dan4ea562e2020-01-01 20:17:151390void sqlite3WindowCodeInit(Parse *pParse, Select *pSelect){
danc9a86682018-05-30 20:44:581391 Window *pWin;
drh1521ca42024-08-19 22:48:301392 int nEphExpr;
1393 Window *pMWin;
1394 Vdbe *v;
1395
1396 assert( pSelect->pSrc->a[0].fg.isSubquery );
1397 nEphExpr = pSelect->pSrc->a[0].u4.pSubq->pSelect->pEList->nExpr;
1398 pMWin = pSelect->pWin;
1399 v = sqlite3GetVdbe(pParse);
danb6f2dea2019-03-13 17:20:271400
dan4ea562e2020-01-01 20:17:151401 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pMWin->iEphCsr, nEphExpr);
1402 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+1, pMWin->iEphCsr);
1403 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+2, pMWin->iEphCsr);
1404 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+3, pMWin->iEphCsr);
1405
danb6f2dea2019-03-13 17:20:271406 /* Allocate registers to use for PARTITION BY values, if any. Initialize
1407 ** said registers to NULL. */
1408 if( pMWin->pPartition ){
1409 int nExpr = pMWin->pPartition->nExpr;
dan13078ca2018-06-13 20:29:381410 pMWin->regPart = pParse->nMem+1;
danb6f2dea2019-03-13 17:20:271411 pParse->nMem += nExpr;
1412 sqlite3VdbeAddOp3(v, OP_Null, 0, pMWin->regPart, pMWin->regPart+nExpr-1);
dan13078ca2018-06-13 20:29:381413 }
1414
danbf845152019-03-16 10:15:241415 pMWin->regOne = ++pParse->nMem;
1416 sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regOne);
dan680f6e82019-03-04 21:07:111417
dana0f6b832019-03-14 16:36:201418 if( pMWin->eExclude ){
1419 pMWin->regStartRowid = ++pParse->nMem;
1420 pMWin->regEndRowid = ++pParse->nMem;
1421 pMWin->csrApp = pParse->nTab++;
1422 sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid);
1423 sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid);
1424 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->csrApp, pMWin->iEphCsr);
1425 return;
1426 }
1427
danc9a86682018-05-30 20:44:581428 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
drh105dcaa2022-03-10 16:01:141429 FuncDef *p = pWin->pWFunc;
danec891fd2018-06-06 20:51:021430 if( (p->funcFlags & SQLITE_FUNC_MINMAX) && pWin->eStart!=TK_UNBOUNDED ){
dan9a947222018-06-14 19:06:361431 /* The inline versions of min() and max() require a single ephemeral
1432 ** table and 3 registers. The registers are used as follows:
1433 **
1434 ** regApp+0: slot to copy min()/max() argument to for MakeRecord
1435 ** regApp+1: integer value used to ensure keys are unique
1436 ** regApp+2: output of MakeRecord
1437 */
drha4eeccd2021-10-07 17:43:301438 ExprList *pList;
1439 KeyInfo *pKeyInfo;
1440 assert( ExprUseXList(pWin->pOwner) );
1441 pList = pWin->pOwner->x.pList;
1442 pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pList, 0, 0);
danc9a86682018-05-30 20:44:581443 pWin->csrApp = pParse->nTab++;
1444 pWin->regApp = pParse->nMem+1;
1445 pParse->nMem += 3;
drh105dcaa2022-03-10 16:01:141446 if( pKeyInfo && pWin->pWFunc->zName[1]=='i' ){
dan6e118922019-08-12 16:36:381447 assert( pKeyInfo->aSortFlags[0]==0 );
1448 pKeyInfo->aSortFlags[0] = KEYINFO_ORDER_DESC;
danc9a86682018-05-30 20:44:581449 }
1450 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pWin->csrApp, 2);
1451 sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
1452 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
1453 }
drh19dc4d42018-07-08 01:02:261454 else if( p->zName==nth_valueName || p->zName==first_valueName ){
danec891fd2018-06-06 20:51:021455 /* Allocate two registers at pWin->regApp. These will be used to
1456 ** store the start and end index of the current frame. */
danec891fd2018-06-06 20:51:021457 pWin->regApp = pParse->nMem+1;
1458 pWin->csrApp = pParse->nTab++;
1459 pParse->nMem += 2;
danec891fd2018-06-06 20:51:021460 sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
1461 }
drh19dc4d42018-07-08 01:02:261462 else if( p->zName==leadName || p->zName==lagName ){
danfe4e25a2018-06-07 20:08:591463 pWin->csrApp = pParse->nTab++;
1464 sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
1465 }
danc9a86682018-05-30 20:44:581466 }
1467}
1468
danbb407272019-03-12 18:28:511469#define WINDOW_STARTING_INT 0
1470#define WINDOW_ENDING_INT 1
1471#define WINDOW_NTH_VALUE_INT 2
1472#define WINDOW_STARTING_NUM 3
1473#define WINDOW_ENDING_NUM 4
1474
dan13078ca2018-06-13 20:29:381475/*
dana1a7e112018-07-09 13:31:181476** A "PRECEDING <expr>" (eCond==0) or "FOLLOWING <expr>" (eCond==1) or the
1477** value of the second argument to nth_value() (eCond==2) has just been
1478** evaluated and the result left in register reg. This function generates VM
1479** code to check that the value is a non-negative integer and throws an
1480** exception if it is not.
dan13078ca2018-06-13 20:29:381481*/
danbb407272019-03-12 18:28:511482static void windowCheckValue(Parse *pParse, int reg, int eCond){
danc3a20c12018-05-23 20:55:371483 static const char *azErr[] = {
1484 "frame starting offset must be a non-negative integer",
dana1a7e112018-07-09 13:31:181485 "frame ending offset must be a non-negative integer",
danbb407272019-03-12 18:28:511486 "second argument to nth_value must be a positive integer",
1487 "frame starting offset must be a non-negative number",
1488 "frame ending offset must be a non-negative number",
danc3a20c12018-05-23 20:55:371489 };
danbb407272019-03-12 18:28:511490 static int aOp[] = { OP_Ge, OP_Ge, OP_Gt, OP_Ge, OP_Ge };
danc3a20c12018-05-23 20:55:371491 Vdbe *v = sqlite3GetVdbe(pParse);
dan13078ca2018-06-13 20:29:381492 int regZero = sqlite3GetTempReg(pParse);
danbb407272019-03-12 18:28:511493 assert( eCond>=0 && eCond<ArraySize(azErr) );
danc3a20c12018-05-23 20:55:371494 sqlite3VdbeAddOp2(v, OP_Integer, 0, regZero);
dane5166e02019-03-19 11:56:391495 if( eCond>=WINDOW_STARTING_NUM ){
1496 int regString = sqlite3GetTempReg(pParse);
1497 sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC);
1498 sqlite3VdbeAddOp3(v, OP_Ge, regString, sqlite3VdbeCurrentAddr(v)+2, reg);
drh21826f42019-04-01 14:30:301499 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC|SQLITE_JUMPIFNULL);
drh6f883592019-03-30 20:37:041500 VdbeCoverage(v);
1501 assert( eCond==3 || eCond==4 );
1502 VdbeCoverageIf(v, eCond==3);
1503 VdbeCoverageIf(v, eCond==4);
dane5166e02019-03-19 11:56:391504 }else{
1505 sqlite3VdbeAddOp2(v, OP_MustBeInt, reg, sqlite3VdbeCurrentAddr(v)+2);
drh6f883592019-03-30 20:37:041506 VdbeCoverage(v);
1507 assert( eCond==0 || eCond==1 || eCond==2 );
1508 VdbeCoverageIf(v, eCond==0);
1509 VdbeCoverageIf(v, eCond==1);
1510 VdbeCoverageIf(v, eCond==2);
dane5166e02019-03-19 11:56:391511 }
dana1a7e112018-07-09 13:31:181512 sqlite3VdbeAddOp3(v, aOp[eCond], regZero, sqlite3VdbeCurrentAddr(v)+2, reg);
danb03786a2021-03-31 11:31:191513 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC);
drh21826f42019-04-01 14:30:301514 VdbeCoverageNeverNullIf(v, eCond==0); /* NULL case captured by */
1515 VdbeCoverageNeverNullIf(v, eCond==1); /* the OP_MustBeInt */
1516 VdbeCoverageNeverNullIf(v, eCond==2);
1517 VdbeCoverageNeverNullIf(v, eCond==3); /* NULL case caught by */
1518 VdbeCoverageNeverNullIf(v, eCond==4); /* the OP_Ge */
drh211a0852019-01-27 02:41:341519 sqlite3MayAbort(pParse);
danc3a20c12018-05-23 20:55:371520 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_ERROR, OE_Abort);
dana1a7e112018-07-09 13:31:181521 sqlite3VdbeAppendP4(v, (void*)azErr[eCond], P4_STATIC);
dan13078ca2018-06-13 20:29:381522 sqlite3ReleaseTempReg(pParse, regZero);
danc3a20c12018-05-23 20:55:371523}
1524
dan13078ca2018-06-13 20:29:381525/*
1526** Return the number of arguments passed to the window-function associated
1527** with the object passed as the only argument to this function.
1528*/
dan2a11bb22018-06-11 20:50:251529static int windowArgCount(Window *pWin){
drha4eeccd2021-10-07 17:43:301530 const ExprList *pList;
1531 assert( ExprUseXList(pWin->pOwner) );
1532 pList = pWin->pOwner->x.pList;
dan2a11bb22018-06-11 20:50:251533 return (pList ? pList->nExpr : 0);
1534}
1535
danc782a812019-03-15 20:46:191536typedef struct WindowCodeArg WindowCodeArg;
1537typedef struct WindowCsrAndReg WindowCsrAndReg;
dan1cac1762019-08-30 17:28:551538
1539/*
1540** See comments above struct WindowCodeArg.
1541*/
danc782a812019-03-15 20:46:191542struct WindowCsrAndReg {
dan1cac1762019-08-30 17:28:551543 int csr; /* Cursor number */
1544 int reg; /* First in array of peer values */
danc782a812019-03-15 20:46:191545};
1546
dan1cac1762019-08-30 17:28:551547/*
larrybrbc917382023-06-07 08:40:311548** A single instance of this structure is allocated on the stack by
dan1cac1762019-08-30 17:28:551549** sqlite3WindowCodeStep() and a pointer to it passed to the various helper
1550** routines. This is to reduce the number of arguments required by each
1551** helper function.
1552**
1553** regArg:
1554** Each window function requires an accumulator register (just as an
1555** ordinary aggregate function does). This variable is set to the first
1556** in an array of accumulator registers - one for each window function
1557** in the WindowCodeArg.pMWin list.
1558**
1559** eDelete:
1560** The window functions implementation sometimes caches the input rows
1561** that it processes in a temporary table. If it is not zero, this
1562** variable indicates when rows may be removed from the temp table (in
1563** order to reduce memory requirements - it would always be safe just
1564** to leave them there). Possible values for eDelete are:
1565**
1566** WINDOW_RETURN_ROW:
1567** An input row can be discarded after it is returned to the caller.
1568**
1569** WINDOW_AGGINVERSE:
1570** An input row can be discarded after the window functions xInverse()
1571** callbacks have been invoked in it.
1572**
1573** WINDOW_AGGSTEP:
1574** An input row can be discarded after the window functions xStep()
1575** callbacks have been invoked in it.
1576**
1577** start,current,end
1578** Consider a window-frame similar to the following:
1579**
1580** (ORDER BY a, b GROUPS BETWEEN 2 PRECEDING AND 2 FOLLOWING)
1581**
larrybr55be2162023-06-07 17:03:221582** The windows functions implementation caches the input rows in a temp
dan1cac1762019-08-30 17:28:551583** table, sorted by "a, b" (it actually populates the cache lazily, and
1584** aggressively removes rows once they are no longer required, but that's
1585** a mere detail). It keeps three cursors open on the temp table. One
1586** (current) that points to the next row to return to the query engine
1587** once its window function values have been calculated. Another (end)
1588** points to the next row to call the xStep() method of each window function
1589** on (so that it is 2 groups ahead of current). And a third (start) that
1590** points to the next row to call the xInverse() method of each window
1591** function on.
1592**
1593** Each cursor (start, current and end) consists of a VDBE cursor
1594** (WindowCsrAndReg.csr) and an array of registers (starting at
larrybrbc917382023-06-07 08:40:311595** WindowCodeArg.reg) that always contains a copy of the peer values
dan1cac1762019-08-30 17:28:551596** read from the corresponding cursor.
1597**
1598** Depending on the window-frame in question, all three cursors may not
1599** be required. In this case both WindowCodeArg.csr and reg are set to
1600** 0.
1601*/
danc782a812019-03-15 20:46:191602struct WindowCodeArg {
dan1cac1762019-08-30 17:28:551603 Parse *pParse; /* Parse context */
1604 Window *pMWin; /* First in list of functions being processed */
1605 Vdbe *pVdbe; /* VDBE object */
1606 int addrGosub; /* OP_Gosub to this address to return one row */
1607 int regGosub; /* Register used with OP_Gosub(addrGosub) */
1608 int regArg; /* First in array of accumulator registers */
1609 int eDelete; /* See above */
drh113a33c2021-04-24 23:40:051610 int regRowid;
danc782a812019-03-15 20:46:191611
1612 WindowCsrAndReg start;
1613 WindowCsrAndReg current;
1614 WindowCsrAndReg end;
1615};
1616
1617/*
danc782a812019-03-15 20:46:191618** Generate VM code to read the window frames peer values from cursor csr into
1619** an array of registers starting at reg.
1620*/
1621static void windowReadPeerValues(
1622 WindowCodeArg *p,
1623 int csr,
1624 int reg
1625){
1626 Window *pMWin = p->pMWin;
1627 ExprList *pOrderBy = pMWin->pOrderBy;
1628 if( pOrderBy ){
1629 Vdbe *v = sqlite3GetVdbe(p->pParse);
1630 ExprList *pPart = pMWin->pPartition;
1631 int iColOff = pMWin->nBufferCol + (pPart ? pPart->nExpr : 0);
1632 int i;
1633 for(i=0; i<pOrderBy->nExpr; i++){
1634 sqlite3VdbeAddOp3(v, OP_Column, csr, iColOff+i, reg+i);
1635 }
1636 }
1637}
1638
dan13078ca2018-06-13 20:29:381639/*
larrybrbc917382023-06-07 08:40:311640** Generate VM code to invoke either xStep() (if bInverse is 0) or
1641** xInverse (if bInverse is non-zero) for each window function in the
dan37d296a2019-09-24 20:20:051642** linked list starting at pMWin. Or, for built-in window functions
1643** that do not use the standard function API, generate the required
1644** inline VM code.
1645**
1646** If argument csr is greater than or equal to 0, then argument reg is
1647** the first register in an array of registers guaranteed to be large
1648** enough to hold the array of arguments for each function. In this case
1649** the arguments are extracted from the current row of csr into the
1650** array of registers before invoking OP_AggStep or OP_AggInverse
1651**
1652** Or, if csr is less than zero, then the array of registers at reg is
1653** already populated with all columns from the current row of the sub-query.
1654**
1655** If argument regPartSize is non-zero, then it is a register containing the
1656** number of rows in the current partition.
1657*/
1658static void windowAggStep(
1659 WindowCodeArg *p,
1660 Window *pMWin, /* Linked list of window functions */
1661 int csr, /* Read arguments from this cursor */
1662 int bInverse, /* True to invoke xInverse instead of xStep */
1663 int reg /* Array of registers */
1664){
1665 Parse *pParse = p->pParse;
1666 Vdbe *v = sqlite3GetVdbe(pParse);
1667 Window *pWin;
1668 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
drh105dcaa2022-03-10 16:01:141669 FuncDef *pFunc = pWin->pWFunc;
dan37d296a2019-09-24 20:20:051670 int regArg;
1671 int nArg = pWin->bExprArgs ? 0 : windowArgCount(pWin);
1672 int i;
danc87d7be2024-11-14 14:38:161673 int addrIf = 0;
dan37d296a2019-09-24 20:20:051674
1675 assert( bInverse==0 || pWin->eStart!=TK_UNBOUNDED );
1676
drhc5b35ae2019-09-25 02:07:501677 /* All OVER clauses in the same window function aggregate step must
1678 ** be the same. */
danfbb6e9f2020-01-09 20:11:291679 assert( pWin==pMWin || sqlite3WindowCompare(pParse,pWin,pMWin,0)!=1 );
drhc5b35ae2019-09-25 02:07:501680
dan37d296a2019-09-24 20:20:051681 for(i=0; i<nArg; i++){
1682 if( i!=1 || pFunc->zName!=nth_valueName ){
1683 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+i, reg+i);
1684 }else{
1685 sqlite3VdbeAddOp3(v, OP_Column, pMWin->iEphCsr, pWin->iArgCol+i, reg+i);
1686 }
1687 }
1688 regArg = reg;
1689
danc87d7be2024-11-14 14:38:161690 if( pWin->pFilter ){
1691 int regTmp;
1692 assert( ExprUseXList(pWin->pOwner) );
1693 assert( pWin->bExprArgs || !nArg ||nArg==pWin->pOwner->x.pList->nExpr );
1694 assert( pWin->bExprArgs || nArg ||pWin->pOwner->x.pList==0 );
1695 regTmp = sqlite3GetTempReg(pParse);
1696 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+nArg,regTmp);
1697 addrIf = sqlite3VdbeAddOp3(v, OP_IfNot, regTmp, 0, 1);
1698 VdbeCoverage(v);
1699 sqlite3ReleaseTempReg(pParse, regTmp);
1700 }
1701
dan37d296a2019-09-24 20:20:051702 if( pMWin->regStartRowid==0
larrybrbc917382023-06-07 08:40:311703 && (pFunc->funcFlags & SQLITE_FUNC_MINMAX)
dan37d296a2019-09-24 20:20:051704 && (pWin->eStart!=TK_UNBOUNDED)
1705 ){
1706 int addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regArg);
1707 VdbeCoverage(v);
1708 if( bInverse==0 ){
1709 sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1, 1);
1710 sqlite3VdbeAddOp2(v, OP_SCopy, regArg, pWin->regApp);
1711 sqlite3VdbeAddOp3(v, OP_MakeRecord, pWin->regApp, 2, pWin->regApp+2);
1712 sqlite3VdbeAddOp2(v, OP_IdxInsert, pWin->csrApp, pWin->regApp+2);
1713 }else{
1714 sqlite3VdbeAddOp4Int(v, OP_SeekGE, pWin->csrApp, 0, regArg, 1);
1715 VdbeCoverageNeverTaken(v);
1716 sqlite3VdbeAddOp1(v, OP_Delete, pWin->csrApp);
1717 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
1718 }
1719 sqlite3VdbeJumpHere(v, addrIsNull);
1720 }else if( pWin->regApp ){
danc87d7be2024-11-14 14:38:161721 assert( pWin->pFilter==0 );
dan37d296a2019-09-24 20:20:051722 assert( pFunc->zName==nth_valueName
1723 || pFunc->zName==first_valueName
1724 );
1725 assert( bInverse==0 || bInverse==1 );
1726 sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1-bInverse, 1);
1727 }else if( pFunc->xSFunc!=noopStepFunc ){
dan37d296a2019-09-24 20:20:051728 if( pWin->bExprArgs ){
dan5a9fd232021-04-06 18:40:271729 int iOp = sqlite3VdbeCurrentAddr(v);
1730 int iEnd;
dan37d296a2019-09-24 20:20:051731
drha4eeccd2021-10-07 17:43:301732 assert( ExprUseXList(pWin->pOwner) );
dan37d296a2019-09-24 20:20:051733 nArg = pWin->pOwner->x.pList->nExpr;
1734 regArg = sqlite3GetTempRange(pParse, nArg);
1735 sqlite3ExprCodeExprList(pParse, pWin->pOwner->x.pList, regArg, 0, 0);
1736
dan5a9fd232021-04-06 18:40:271737 for(iEnd=sqlite3VdbeCurrentAddr(v); iOp<iEnd; iOp++){
1738 VdbeOp *pOp = sqlite3VdbeGetOp(v, iOp);
dan41150bf2022-04-20 16:42:571739 if( pOp->opcode==OP_Column && pOp->p1==pMWin->iEphCsr ){
dan37d296a2019-09-24 20:20:051740 pOp->p1 = csr;
1741 }
1742 }
1743 }
1744 if( pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
1745 CollSeq *pColl;
1746 assert( nArg>0 );
drha4eeccd2021-10-07 17:43:301747 assert( ExprUseXList(pWin->pOwner) );
dan37d296a2019-09-24 20:20:051748 pColl = sqlite3ExprNNCollSeq(pParse, pWin->pOwner->x.pList->a[0].pExpr);
1749 sqlite3VdbeAddOp4(v, OP_CollSeq, 0,0,0, (const char*)pColl, P4_COLLSEQ);
1750 }
larrybrbc917382023-06-07 08:40:311751 sqlite3VdbeAddOp3(v, bInverse? OP_AggInverse : OP_AggStep,
dan37d296a2019-09-24 20:20:051752 bInverse, regArg, pWin->regAccum);
1753 sqlite3VdbeAppendP4(v, pFunc, P4_FUNCDEF);
drh35d302c2024-12-12 15:11:271754 sqlite3VdbeChangeP5(v, (u16)nArg);
dan37d296a2019-09-24 20:20:051755 if( pWin->bExprArgs ){
1756 sqlite3ReleaseTempRange(pParse, regArg, nArg);
1757 }
dan37d296a2019-09-24 20:20:051758 }
danc87d7be2024-11-14 14:38:161759
1760 if( addrIf ) sqlite3VdbeJumpHere(v, addrIf);
dan37d296a2019-09-24 20:20:051761 }
1762}
1763
1764/*
1765** Values that may be passed as the second argument to windowCodeOp().
1766*/
1767#define WINDOW_RETURN_ROW 1
1768#define WINDOW_AGGINVERSE 2
1769#define WINDOW_AGGSTEP 3
1770
1771/*
dana0f6b832019-03-14 16:36:201772** Generate VM code to invoke either xValue() (bFin==0) or xFinalize()
1773** (bFin==1) for each window function in the linked list starting at
dan13078ca2018-06-13 20:29:381774** pMWin. Or, for built-in window-functions that do not use the standard
1775** API, generate the equivalent VM code.
1776*/
danc782a812019-03-15 20:46:191777static void windowAggFinal(WindowCodeArg *p, int bFin){
1778 Parse *pParse = p->pParse;
1779 Window *pMWin = p->pMWin;
dand6f784e2018-05-28 18:30:451780 Vdbe *v = sqlite3GetVdbe(pParse);
1781 Window *pWin;
1782
1783 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
dana0f6b832019-03-14 16:36:201784 if( pMWin->regStartRowid==0
larrybrbc917382023-06-07 08:40:311785 && (pWin->pWFunc->funcFlags & SQLITE_FUNC_MINMAX)
dana0f6b832019-03-14 16:36:201786 && (pWin->eStart!=TK_UNBOUNDED)
danec891fd2018-06-06 20:51:021787 ){
dand6f784e2018-05-28 18:30:451788 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
danc9a86682018-05-30 20:44:581789 sqlite3VdbeAddOp1(v, OP_Last, pWin->csrApp);
dan01e12292018-06-27 20:24:591790 VdbeCoverage(v);
danc9a86682018-05-30 20:44:581791 sqlite3VdbeAddOp3(v, OP_Column, pWin->csrApp, 0, pWin->regResult);
1792 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
danec891fd2018-06-06 20:51:021793 }else if( pWin->regApp ){
dana0f6b832019-03-14 16:36:201794 assert( pMWin->regStartRowid==0 );
dand6f784e2018-05-28 18:30:451795 }else{
dana0f6b832019-03-14 16:36:201796 int nArg = windowArgCount(pWin);
1797 if( bFin ){
1798 sqlite3VdbeAddOp2(v, OP_AggFinal, pWin->regAccum, nArg);
drh105dcaa2022-03-10 16:01:141799 sqlite3VdbeAppendP4(v, pWin->pWFunc, P4_FUNCDEF);
danc9a86682018-05-30 20:44:581800 sqlite3VdbeAddOp2(v, OP_Copy, pWin->regAccum, pWin->regResult);
dan8b985602018-06-09 17:43:451801 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
danc9a86682018-05-30 20:44:581802 }else{
dana0f6b832019-03-14 16:36:201803 sqlite3VdbeAddOp3(v, OP_AggValue,pWin->regAccum,nArg,pWin->regResult);
drh105dcaa2022-03-10 16:01:141804 sqlite3VdbeAppendP4(v, pWin->pWFunc, P4_FUNCDEF);
danc9a86682018-05-30 20:44:581805 }
dand6f784e2018-05-28 18:30:451806 }
1807 }
1808}
1809
dan0525b6f2019-03-18 21:19:401810/*
1811** Generate code to calculate the current values of all window functions in the
1812** p->pMWin list by doing a full scan of the current window frame. Store the
1813** results in the Window.regResult registers, ready to return the upper
1814** layer.
1815*/
danc782a812019-03-15 20:46:191816static void windowFullScan(WindowCodeArg *p){
1817 Window *pWin;
1818 Parse *pParse = p->pParse;
1819 Window *pMWin = p->pMWin;
1820 Vdbe *v = p->pVdbe;
1821
1822 int regCRowid = 0; /* Current rowid value */
1823 int regCPeer = 0; /* Current peer values */
1824 int regRowid = 0; /* AggStep rowid value */
1825 int regPeer = 0; /* AggStep peer values */
1826
1827 int nPeer;
1828 int lblNext;
1829 int lblBrk;
1830 int addrNext;
drh55f66b32019-07-16 19:44:321831 int csr;
danc782a812019-03-15 20:46:191832
dan37d296a2019-09-24 20:20:051833 VdbeModuleComment((v, "windowFullScan begin"));
1834
drh55f66b32019-07-16 19:44:321835 assert( pMWin!=0 );
1836 csr = pMWin->csrApp;
danc782a812019-03-15 20:46:191837 nPeer = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);
1838
1839 lblNext = sqlite3VdbeMakeLabel(pParse);
1840 lblBrk = sqlite3VdbeMakeLabel(pParse);
1841
1842 regCRowid = sqlite3GetTempReg(pParse);
1843 regRowid = sqlite3GetTempReg(pParse);
1844 if( nPeer ){
1845 regCPeer = sqlite3GetTempRange(pParse, nPeer);
1846 regPeer = sqlite3GetTempRange(pParse, nPeer);
1847 }
1848
1849 sqlite3VdbeAddOp2(v, OP_Rowid, pMWin->iEphCsr, regCRowid);
1850 windowReadPeerValues(p, pMWin->iEphCsr, regCPeer);
1851
1852 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1853 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
1854 }
1855
1856 sqlite3VdbeAddOp3(v, OP_SeekGE, csr, lblBrk, pMWin->regStartRowid);
dan1d4b25f2019-03-19 16:49:151857 VdbeCoverage(v);
danc782a812019-03-15 20:46:191858 addrNext = sqlite3VdbeCurrentAddr(v);
1859 sqlite3VdbeAddOp2(v, OP_Rowid, csr, regRowid);
1860 sqlite3VdbeAddOp3(v, OP_Gt, pMWin->regEndRowid, lblBrk, regRowid);
dan1d4b25f2019-03-19 16:49:151861 VdbeCoverageNeverNull(v);
dan108e6b22019-03-18 18:55:351862
danc782a812019-03-15 20:46:191863 if( pMWin->eExclude==TK_CURRENT ){
1864 sqlite3VdbeAddOp3(v, OP_Eq, regCRowid, lblNext, regRowid);
drh83c5bb92019-04-01 15:55:381865 VdbeCoverageNeverNull(v);
danc782a812019-03-15 20:46:191866 }else if( pMWin->eExclude!=TK_NO ){
1867 int addr;
dan108e6b22019-03-18 18:55:351868 int addrEq = 0;
dan66033422019-03-19 19:19:531869 KeyInfo *pKeyInfo = 0;
dan108e6b22019-03-18 18:55:351870
dan66033422019-03-19 19:19:531871 if( pMWin->pOrderBy ){
1872 pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pMWin->pOrderBy, 0, 0);
danc782a812019-03-15 20:46:191873 }
dan66033422019-03-19 19:19:531874 if( pMWin->eExclude==TK_TIES ){
1875 addrEq = sqlite3VdbeAddOp3(v, OP_Eq, regCRowid, 0, regRowid);
drh83c5bb92019-04-01 15:55:381876 VdbeCoverageNeverNull(v);
dan66033422019-03-19 19:19:531877 }
1878 if( pKeyInfo ){
1879 windowReadPeerValues(p, csr, regPeer);
1880 sqlite3VdbeAddOp3(v, OP_Compare, regPeer, regCPeer, nPeer);
1881 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
1882 addr = sqlite3VdbeCurrentAddr(v)+1;
1883 sqlite3VdbeAddOp3(v, OP_Jump, addr, lblNext, addr);
1884 VdbeCoverageEqNe(v);
1885 }else{
1886 sqlite3VdbeAddOp2(v, OP_Goto, 0, lblNext);
1887 }
danc782a812019-03-15 20:46:191888 if( addrEq ) sqlite3VdbeJumpHere(v, addrEq);
1889 }
1890
dan37d296a2019-09-24 20:20:051891 windowAggStep(p, pMWin, csr, 0, p->regArg);
danc782a812019-03-15 20:46:191892
1893 sqlite3VdbeResolveLabel(v, lblNext);
1894 sqlite3VdbeAddOp2(v, OP_Next, csr, addrNext);
dan1d4b25f2019-03-19 16:49:151895 VdbeCoverage(v);
danc782a812019-03-15 20:46:191896 sqlite3VdbeJumpHere(v, addrNext-1);
1897 sqlite3VdbeJumpHere(v, addrNext+1);
1898 sqlite3ReleaseTempReg(pParse, regRowid);
1899 sqlite3ReleaseTempReg(pParse, regCRowid);
1900 if( nPeer ){
1901 sqlite3ReleaseTempRange(pParse, regPeer, nPeer);
1902 sqlite3ReleaseTempRange(pParse, regCPeer, nPeer);
1903 }
1904
1905 windowAggFinal(p, 1);
dan37d296a2019-09-24 20:20:051906 VdbeModuleComment((v, "windowFullScan end"));
danc782a812019-03-15 20:46:191907}
1908
dan13078ca2018-06-13 20:29:381909/*
dan13078ca2018-06-13 20:29:381910** Invoke the sub-routine at regGosub (generated by code in select.c) to
1911** return the current row of Window.iEphCsr. If all window functions are
1912** aggregate window functions that use the standard API, a single
1913** OP_Gosub instruction is all that this routine generates. Extra VM code
1914** for per-row processing is only generated for the following built-in window
1915** functions:
1916**
1917** nth_value()
1918** first_value()
1919** lag()
1920** lead()
1921*/
danc782a812019-03-15 20:46:191922static void windowReturnOneRow(WindowCodeArg *p){
1923 Window *pMWin = p->pMWin;
1924 Vdbe *v = p->pVdbe;
dan7095c002018-06-07 17:45:221925
danc782a812019-03-15 20:46:191926 if( pMWin->regStartRowid ){
1927 windowFullScan(p);
1928 }else{
1929 Parse *pParse = p->pParse;
1930 Window *pWin;
1931
1932 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
drh105dcaa2022-03-10 16:01:141933 FuncDef *pFunc = pWin->pWFunc;
drha4eeccd2021-10-07 17:43:301934 assert( ExprUseXList(pWin->pOwner) );
danc782a812019-03-15 20:46:191935 if( pFunc->zName==nth_valueName
1936 || pFunc->zName==first_valueName
1937 ){
dana0f6b832019-03-14 16:36:201938 int csr = pWin->csrApp;
danc782a812019-03-15 20:46:191939 int lbl = sqlite3VdbeMakeLabel(pParse);
1940 int tmpReg = sqlite3GetTempReg(pParse);
1941 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
larrybrbc917382023-06-07 08:40:311942
danc782a812019-03-15 20:46:191943 if( pFunc->zName==nth_valueName ){
1944 sqlite3VdbeAddOp3(v, OP_Column,pMWin->iEphCsr,pWin->iArgCol+1,tmpReg);
1945 windowCheckValue(pParse, tmpReg, 2);
1946 }else{
1947 sqlite3VdbeAddOp2(v, OP_Integer, 1, tmpReg);
1948 }
dana0f6b832019-03-14 16:36:201949 sqlite3VdbeAddOp3(v, OP_Add, tmpReg, pWin->regApp, tmpReg);
1950 sqlite3VdbeAddOp3(v, OP_Gt, pWin->regApp+1, lbl, tmpReg);
1951 VdbeCoverageNeverNull(v);
1952 sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, 0, tmpReg);
1953 VdbeCoverageNeverTaken(v);
1954 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
danc782a812019-03-15 20:46:191955 sqlite3VdbeResolveLabel(v, lbl);
1956 sqlite3ReleaseTempReg(pParse, tmpReg);
dana0f6b832019-03-14 16:36:201957 }
danc782a812019-03-15 20:46:191958 else if( pFunc->zName==leadName || pFunc->zName==lagName ){
1959 int nArg = pWin->pOwner->x.pList->nExpr;
1960 int csr = pWin->csrApp;
1961 int lbl = sqlite3VdbeMakeLabel(pParse);
1962 int tmpReg = sqlite3GetTempReg(pParse);
1963 int iEph = pMWin->iEphCsr;
larrybrbc917382023-06-07 08:40:311964
danc782a812019-03-15 20:46:191965 if( nArg<3 ){
1966 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
1967 }else{
1968 sqlite3VdbeAddOp3(v, OP_Column, iEph,pWin->iArgCol+2,pWin->regResult);
1969 }
1970 sqlite3VdbeAddOp2(v, OP_Rowid, iEph, tmpReg);
1971 if( nArg<2 ){
1972 int val = (pFunc->zName==leadName ? 1 : -1);
1973 sqlite3VdbeAddOp2(v, OP_AddImm, tmpReg, val);
1974 }else{
1975 int op = (pFunc->zName==leadName ? OP_Add : OP_Subtract);
1976 int tmpReg2 = sqlite3GetTempReg(pParse);
1977 sqlite3VdbeAddOp3(v, OP_Column, iEph, pWin->iArgCol+1, tmpReg2);
1978 sqlite3VdbeAddOp3(v, op, tmpReg2, tmpReg, tmpReg);
1979 sqlite3ReleaseTempReg(pParse, tmpReg2);
1980 }
larrybrbc917382023-06-07 08:40:311981
danc782a812019-03-15 20:46:191982 sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, lbl, tmpReg);
1983 VdbeCoverage(v);
1984 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
1985 sqlite3VdbeResolveLabel(v, lbl);
1986 sqlite3ReleaseTempReg(pParse, tmpReg);
danfe4e25a2018-06-07 20:08:591987 }
danfe4e25a2018-06-07 20:08:591988 }
danec891fd2018-06-06 20:51:021989 }
danc782a812019-03-15 20:46:191990 sqlite3VdbeAddOp2(v, OP_Gosub, p->regGosub, p->addrGosub);
danec891fd2018-06-06 20:51:021991}
1992
dan13078ca2018-06-13 20:29:381993/*
dan54a9ab32018-06-14 14:27:051994** Generate code to set the accumulator register for each window function
1995** in the linked list passed as the second argument to NULL. And perform
1996** any equivalent initialization required by any built-in window functions
1997** in the list.
1998*/
dan2e605682018-06-07 15:54:261999static int windowInitAccum(Parse *pParse, Window *pMWin){
2000 Vdbe *v = sqlite3GetVdbe(pParse);
2001 int regArg;
2002 int nArg = 0;
2003 Window *pWin;
2004 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
drh105dcaa2022-03-10 16:01:142005 FuncDef *pFunc = pWin->pWFunc;
dan0a21ea92020-02-29 17:19:422006 assert( pWin->regAccum );
dan2e605682018-06-07 15:54:262007 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
dan2a11bb22018-06-11 20:50:252008 nArg = MAX(nArg, windowArgCount(pWin));
dan108e6b22019-03-18 18:55:352009 if( pMWin->regStartRowid==0 ){
dana0f6b832019-03-14 16:36:202010 if( pFunc->zName==nth_valueName || pFunc->zName==first_valueName ){
2011 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp);
2012 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
2013 }
dan9a947222018-06-14 19:06:362014
dana0f6b832019-03-14 16:36:202015 if( (pFunc->funcFlags & SQLITE_FUNC_MINMAX) && pWin->csrApp ){
2016 assert( pWin->eStart!=TK_UNBOUNDED );
2017 sqlite3VdbeAddOp1(v, OP_ResetSorter, pWin->csrApp);
2018 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
2019 }
dan9a947222018-06-14 19:06:362020 }
dan2e605682018-06-07 15:54:262021 }
2022 regArg = pParse->nMem+1;
2023 pParse->nMem += nArg;
2024 return regArg;
2025}
2026
larrybrbc917382023-06-07 08:40:312027/*
dancc7a8502019-03-11 19:50:542028** Return true if the current frame should be cached in the ephemeral table,
2029** even if there are no xInverse() calls required.
danb33487b2019-03-06 17:12:322030*/
dancc7a8502019-03-11 19:50:542031static int windowCacheFrame(Window *pMWin){
danb33487b2019-03-06 17:12:322032 Window *pWin;
dana0f6b832019-03-14 16:36:202033 if( pMWin->regStartRowid ) return 1;
danb33487b2019-03-06 17:12:322034 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
drh105dcaa2022-03-10 16:01:142035 FuncDef *pFunc = pWin->pWFunc;
dancc7a8502019-03-11 19:50:542036 if( (pFunc->zName==nth_valueName)
danb33487b2019-03-06 17:12:322037 || (pFunc->zName==first_valueName)
danb560a712019-03-13 15:29:142038 || (pFunc->zName==leadName)
danb33487b2019-03-06 17:12:322039 || (pFunc->zName==lagName)
2040 ){
2041 return 1;
2042 }
2043 }
2044 return 0;
2045}
2046
dan6c75b392019-03-08 20:02:522047/*
2048** regOld and regNew are each the first register in an array of size
2049** pOrderBy->nExpr. This function generates code to compare the two
2050** arrays of registers using the collation sequences and other comparison
larrybrbc917382023-06-07 08:40:312051** parameters specified by pOrderBy.
dan6c75b392019-03-08 20:02:522052**
larrybrbc917382023-06-07 08:40:312053** If the two arrays are not equal, the contents of regNew is copied to
dan6c75b392019-03-08 20:02:522054** regOld and control falls through. Otherwise, if the contents of the arrays
2055** are equal, an OP_Goto is executed. The address of the OP_Goto is returned.
2056*/
dan935d9d82019-03-12 15:21:512057static void windowIfNewPeer(
dan6c75b392019-03-08 20:02:522058 Parse *pParse,
2059 ExprList *pOrderBy,
2060 int regNew, /* First in array of new values */
dan935d9d82019-03-12 15:21:512061 int regOld, /* First in array of old values */
2062 int addr /* Jump here */
dan6c75b392019-03-08 20:02:522063){
2064 Vdbe *v = sqlite3GetVdbe(pParse);
dan6c75b392019-03-08 20:02:522065 if( pOrderBy ){
2066 int nVal = pOrderBy->nExpr;
2067 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pOrderBy, 0, 0);
2068 sqlite3VdbeAddOp3(v, OP_Compare, regOld, regNew, nVal);
2069 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
larrybrbc917382023-06-07 08:40:312070 sqlite3VdbeAddOp3(v, OP_Jump,
dan935d9d82019-03-12 15:21:512071 sqlite3VdbeCurrentAddr(v)+1, addr, sqlite3VdbeCurrentAddr(v)+1
dan72b9fdc2019-03-09 20:49:172072 );
dan6c75b392019-03-08 20:02:522073 VdbeCoverageEqNe(v);
2074 sqlite3VdbeAddOp3(v, OP_Copy, regNew, regOld, nVal-1);
2075 }else{
dan935d9d82019-03-12 15:21:512076 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
dan6c75b392019-03-08 20:02:522077 }
dan6c75b392019-03-08 20:02:522078}
2079
dan72b9fdc2019-03-09 20:49:172080/*
2081** This function is called as part of generating VM programs for RANGE
dan1e7cb192019-03-16 20:29:542082** offset PRECEDING/FOLLOWING frame boundaries. Assuming "ASC" order for
dan8b47f522019-08-30 16:14:582083** the ORDER BY term in the window, and that argument op is OP_Ge, it generates
2084** code equivalent to:
dan72b9fdc2019-03-09 20:49:172085**
2086** if( csr1.peerVal + regVal >= csr2.peerVal ) goto lbl;
dan1e7cb192019-03-16 20:29:542087**
dan8b47f522019-08-30 16:14:582088** The value of parameter op may also be OP_Gt or OP_Le. In these cases the
2089** operator in the above pseudo-code is replaced with ">" or "<=", respectively.
2090**
2091** If the sort-order for the ORDER BY term in the window is DESC, then the
2092** comparison is reversed. Instead of adding regVal to csr1.peerVal, it is
2093** subtracted. And the comparison operator is inverted to - ">=" becomes "<=",
2094** ">" becomes "<", and so on. So, with DESC sort order, if the argument op
2095** is OP_Ge, the generated code is equivalent to:
2096**
2097** if( csr1.peerVal - regVal <= csr2.peerVal ) goto lbl;
2098**
2099** A special type of arithmetic is used such that if csr1.peerVal is not
dan6b6ec402021-04-05 19:05:182100** a numeric type (real or integer), then the result of the addition
dan8b47f522019-08-30 16:14:582101** or subtraction is a a copy of csr1.peerVal.
dan72b9fdc2019-03-09 20:49:172102*/
2103static void windowCodeRangeTest(
larrybrbc917382023-06-07 08:40:312104 WindowCodeArg *p,
dan1cac1762019-08-30 17:28:552105 int op, /* OP_Ge, OP_Gt, or OP_Le */
2106 int csr1, /* Cursor number for cursor 1 */
2107 int regVal, /* Register containing non-negative number */
2108 int csr2, /* Cursor number for cursor 2 */
2109 int lbl /* Jump destination if condition is true */
dan72b9fdc2019-03-09 20:49:172110){
2111 Parse *pParse = p->pParse;
2112 Vdbe *v = sqlite3GetVdbe(pParse);
dan1cac1762019-08-30 17:28:552113 ExprList *pOrderBy = p->pMWin->pOrderBy; /* ORDER BY clause for window */
2114 int reg1 = sqlite3GetTempReg(pParse); /* Reg. for csr1.peerVal+regVal */
2115 int reg2 = sqlite3GetTempReg(pParse); /* Reg. for csr2.peerVal */
2116 int regString = ++pParse->nMem; /* Reg. for constant value '' */
dan8b47f522019-08-30 16:14:582117 int arith = OP_Add; /* OP_Add or OP_Subtract */
2118 int addrGe; /* Jump destination */
dan6b6ec402021-04-05 19:05:182119 int addrDone = sqlite3VdbeMakeLabel(pParse); /* Address past OP_Ge */
dan7f8653a2021-03-06 14:46:242120 CollSeq *pColl;
dan71fddaf2019-03-11 11:12:342121
dan6b6ec402021-04-05 19:05:182122 /* Read the peer-value from each cursor into a register */
2123 windowReadPeerValues(p, csr1, reg1);
2124 windowReadPeerValues(p, csr2, reg2);
2125
dan71fddaf2019-03-11 11:12:342126 assert( op==OP_Ge || op==OP_Gt || op==OP_Le );
danae8e45c2019-08-19 19:59:502127 assert( pOrderBy && pOrderBy->nExpr==1 );
drhd88fd532022-05-02 20:49:302128 if( pOrderBy->a[0].fg.sortFlags & KEYINFO_ORDER_DESC ){
dan71fddaf2019-03-11 11:12:342129 switch( op ){
2130 case OP_Ge: op = OP_Le; break;
2131 case OP_Gt: op = OP_Lt; break;
2132 default: assert( op==OP_Le ); op = OP_Ge; break;
2133 }
2134 arith = OP_Subtract;
2135 }
2136
dan8b47f522019-08-30 16:14:582137 VdbeModuleComment((v, "CodeRangeTest: if( R%d %s R%d %s R%d ) goto lbl",
2138 reg1, (arith==OP_Add ? "+" : "-"), regVal,
2139 ((op==OP_Ge) ? ">=" : (op==OP_Le) ? "<=" : (op==OP_Gt) ? ">" : "<"), reg2
2140 ));
2141
larrybrbc917382023-06-07 08:40:312142 /* If the BIGNULL flag is set for the ORDER BY, then it is required to
2143 ** consider NULL values to be larger than all other values, instead of
dan8b47f522019-08-30 16:14:582144 ** the usual smaller. The VDBE opcodes OP_Ge and so on do not handle this
2145 ** (and adding that capability causes a performance regression), so
2146 ** instead if the BIGNULL flag is set then cases where either reg1 or
2147 ** reg2 are NULL are handled separately in the following block. The code
2148 ** generated is equivalent to:
2149 **
2150 ** if( reg1 IS NULL ){
dan9889ede2019-08-30 19:45:032151 ** if( op==OP_Ge ) goto lbl;
2152 ** if( op==OP_Gt && reg2 IS NOT NULL ) goto lbl;
dan8b47f522019-08-30 16:14:582153 ** if( op==OP_Le && reg2 IS NULL ) goto lbl;
2154 ** }else if( reg2 IS NULL ){
2155 ** if( op==OP_Le ) goto lbl;
2156 ** }
2157 **
larrybrbc917382023-06-07 08:40:312158 ** Additionally, if either reg1 or reg2 are NULL but the jump to lbl is
dan8b47f522019-08-30 16:14:582159 ** not taken, control jumps over the comparison operator coded below this
2160 ** block. */
drhd88fd532022-05-02 20:49:302161 if( pOrderBy->a[0].fg.sortFlags & KEYINFO_ORDER_BIGNULL ){
dan8b47f522019-08-30 16:14:582162 /* This block runs if reg1 contains a NULL. */
2163 int addr = sqlite3VdbeAddOp1(v, OP_NotNull, reg1); VdbeCoverage(v);
danae8e45c2019-08-19 19:59:502164 switch( op ){
larrybrbc917382023-06-07 08:40:312165 case OP_Ge:
2166 sqlite3VdbeAddOp2(v, OP_Goto, 0, lbl);
dan8b47f522019-08-30 16:14:582167 break;
larrybrbc917382023-06-07 08:40:312168 case OP_Gt:
2169 sqlite3VdbeAddOp2(v, OP_NotNull, reg2, lbl);
2170 VdbeCoverage(v);
danf236b212019-08-21 19:58:112171 break;
larrybrbc917382023-06-07 08:40:312172 case OP_Le:
2173 sqlite3VdbeAddOp2(v, OP_IsNull, reg2, lbl);
2174 VdbeCoverage(v);
danf236b212019-08-21 19:58:112175 break;
drhdb3a32e2019-08-30 18:02:492176 default: assert( op==OP_Lt ); /* no-op */ break;
danae8e45c2019-08-19 19:59:502177 }
dan6b6ec402021-04-05 19:05:182178 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrDone);
dan8b47f522019-08-30 16:14:582179
2180 /* This block runs if reg1 is not NULL, but reg2 is. */
danae8e45c2019-08-19 19:59:502181 sqlite3VdbeJumpHere(v, addr);
drh058e9952022-07-25 19:05:242182 sqlite3VdbeAddOp2(v, OP_IsNull, reg2,
2183 (op==OP_Gt || op==OP_Ge) ? addrDone : lbl);
drh3b01dd02022-07-26 19:10:132184 VdbeCoverage(v);
danae8e45c2019-08-19 19:59:502185 }
dan8b47f522019-08-30 16:14:582186
dan6b6ec402021-04-05 19:05:182187 /* Register reg1 currently contains csr1.peerVal (the peer-value from csr1).
2188 ** This block adds (or subtracts for DESC) the numeric value in regVal
2189 ** from it. Or, if reg1 is not numeric (it is a NULL, a text value or a blob),
2190 ** then leave reg1 as it is. In pseudo-code, this is implemented as:
2191 **
2192 ** if( reg1>='' ) goto addrGe;
2193 ** reg1 = reg1 +/- regVal
2194 ** addrGe:
2195 **
2196 ** Since all strings and blobs are greater-than-or-equal-to an empty string,
2197 ** the add/subtract is skipped for these, as required. If reg1 is a NULL,
2198 ** then the arithmetic is performed, but since adding or subtracting from
2199 ** NULL is always NULL anyway, this case is handled as required too. */
2200 sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC);
2201 addrGe = sqlite3VdbeAddOp3(v, OP_Ge, regString, 0, reg1);
2202 VdbeCoverage(v);
2203 if( (op==OP_Ge && arith==OP_Add) || (op==OP_Le && arith==OP_Subtract) ){
2204 sqlite3VdbeAddOp3(v, op, reg2, lbl, reg1); VdbeCoverage(v);
2205 }
2206 sqlite3VdbeAddOp3(v, arith, regVal, reg1, reg1);
2207 sqlite3VdbeJumpHere(v, addrGe);
2208
dan8b47f522019-08-30 16:14:582209 /* Compare registers reg2 and reg1, taking the jump if required. Note that
2210 ** control skips over this test if the BIGNULL flag is set and either
2211 ** reg1 or reg2 contain a NULL value. */
drh6f883592019-03-30 20:37:042212 sqlite3VdbeAddOp3(v, op, reg2, lbl, reg1); VdbeCoverage(v);
dan7f8653a2021-03-06 14:46:242213 pColl = sqlite3ExprNNCollSeq(pParse, pOrderBy->a[0].pExpr);
2214 sqlite3VdbeAppendP4(v, (void*)pColl, P4_COLLSEQ);
danbdabe742019-03-18 16:51:242215 sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
dan6b6ec402021-04-05 19:05:182216 sqlite3VdbeResolveLabel(v, addrDone);
dan8b47f522019-08-30 16:14:582217
drh6f883592019-03-30 20:37:042218 assert( op==OP_Ge || op==OP_Gt || op==OP_Lt || op==OP_Le );
2219 testcase(op==OP_Ge); VdbeCoverageIf(v, op==OP_Ge);
2220 testcase(op==OP_Lt); VdbeCoverageIf(v, op==OP_Lt);
2221 testcase(op==OP_Le); VdbeCoverageIf(v, op==OP_Le);
2222 testcase(op==OP_Gt); VdbeCoverageIf(v, op==OP_Gt);
dan72b9fdc2019-03-09 20:49:172223 sqlite3ReleaseTempReg(pParse, reg1);
2224 sqlite3ReleaseTempReg(pParse, reg2);
dan8b47f522019-08-30 16:14:582225
2226 VdbeModuleComment((v, "CodeRangeTest: end"));
dan72b9fdc2019-03-09 20:49:172227}
2228
dan0525b6f2019-03-18 21:19:402229/*
2230** Helper function for sqlite3WindowCodeStep(). Each call to this function
larrybrbc917382023-06-07 08:40:312231** generates VM code for a single RETURN_ROW, AGGSTEP or AGGINVERSE
dan0525b6f2019-03-18 21:19:402232** operation. Refer to the header comment for sqlite3WindowCodeStep() for
2233** details.
2234*/
dan00267b82019-03-06 21:04:112235static int windowCodeOp(
dan0525b6f2019-03-18 21:19:402236 WindowCodeArg *p, /* Context object */
2237 int op, /* WINDOW_RETURN_ROW, AGGSTEP or AGGINVERSE */
2238 int regCountdown, /* Register for OP_IfPos countdown */
2239 int jumpOnEof /* Jump here if stepped cursor reaches EOF */
dan00267b82019-03-06 21:04:112240){
dan6c75b392019-03-08 20:02:522241 int csr, reg;
2242 Parse *pParse = p->pParse;
dan54975cd2019-03-07 20:47:462243 Window *pMWin = p->pMWin;
dan00267b82019-03-06 21:04:112244 int ret = 0;
2245 Vdbe *v = p->pVdbe;
dan6c75b392019-03-08 20:02:522246 int addrContinue = 0;
drhfc15f4c2019-03-28 13:03:412247 int bPeer = (pMWin->eFrmType!=TK_ROWS);
dan00267b82019-03-06 21:04:112248
dan72b9fdc2019-03-09 20:49:172249 int lblDone = sqlite3VdbeMakeLabel(pParse);
2250 int addrNextRange = 0;
2251
dan54975cd2019-03-07 20:47:462252 /* Special case - WINDOW_AGGINVERSE is always a no-op if the frame
2253 ** starts with UNBOUNDED PRECEDING. */
2254 if( op==WINDOW_AGGINVERSE && pMWin->eStart==TK_UNBOUNDED ){
2255 assert( regCountdown==0 && jumpOnEof==0 );
2256 return 0;
2257 }
2258
dan00267b82019-03-06 21:04:112259 if( regCountdown>0 ){
drhfc15f4c2019-03-28 13:03:412260 if( pMWin->eFrmType==TK_RANGE ){
dan72b9fdc2019-03-09 20:49:172261 addrNextRange = sqlite3VdbeCurrentAddr(v);
dan0525b6f2019-03-18 21:19:402262 assert( op==WINDOW_AGGINVERSE || op==WINDOW_AGGSTEP );
2263 if( op==WINDOW_AGGINVERSE ){
2264 if( pMWin->eStart==TK_FOLLOWING ){
dan72b9fdc2019-03-09 20:49:172265 windowCodeRangeTest(
dan0525b6f2019-03-18 21:19:402266 p, OP_Le, p->current.csr, regCountdown, p->start.csr, lblDone
dan72b9fdc2019-03-09 20:49:172267 );
dan0525b6f2019-03-18 21:19:402268 }else{
2269 windowCodeRangeTest(
2270 p, OP_Ge, p->start.csr, regCountdown, p->current.csr, lblDone
2271 );
dan72b9fdc2019-03-09 20:49:172272 }
dan0525b6f2019-03-18 21:19:402273 }else{
2274 windowCodeRangeTest(
2275 p, OP_Gt, p->end.csr, regCountdown, p->current.csr, lblDone
2276 );
dan72b9fdc2019-03-09 20:49:172277 }
dan72b9fdc2019-03-09 20:49:172278 }else{
dan37d296a2019-09-24 20:20:052279 sqlite3VdbeAddOp3(v, OP_IfPos, regCountdown, lblDone, 1);
dan1d4b25f2019-03-19 16:49:152280 VdbeCoverage(v);
dan72b9fdc2019-03-09 20:49:172281 }
dan00267b82019-03-06 21:04:112282 }
2283
dan0525b6f2019-03-18 21:19:402284 if( op==WINDOW_RETURN_ROW && pMWin->regStartRowid==0 ){
danc782a812019-03-15 20:46:192285 windowAggFinal(p, 0);
dan6c75b392019-03-08 20:02:522286 }
2287 addrContinue = sqlite3VdbeCurrentAddr(v);
dane7579a52019-09-25 16:41:442288
2289 /* If this is a (RANGE BETWEEN a FOLLOWING AND b FOLLOWING) or
larrybrbc917382023-06-07 08:40:312290 ** (RANGE BETWEEN b PRECEDING AND a PRECEDING) frame, ensure the
2291 ** start cursor does not advance past the end cursor within the
drh113a33c2021-04-24 23:40:052292 ** temporary table. It otherwise might, if (a>b). Also ensure that,
2293 ** if the input cursor is still finding new rows, that the end
2294 ** cursor does not go past it to EOF. */
dane7579a52019-09-25 16:41:442295 if( pMWin->eStart==pMWin->eEnd && regCountdown
drh113a33c2021-04-24 23:40:052296 && pMWin->eFrmType==TK_RANGE
dane7579a52019-09-25 16:41:442297 ){
2298 int regRowid1 = sqlite3GetTempReg(pParse);
2299 int regRowid2 = sqlite3GetTempReg(pParse);
drh113a33c2021-04-24 23:40:052300 if( op==WINDOW_AGGINVERSE ){
2301 sqlite3VdbeAddOp2(v, OP_Rowid, p->start.csr, regRowid1);
2302 sqlite3VdbeAddOp2(v, OP_Rowid, p->end.csr, regRowid2);
2303 sqlite3VdbeAddOp3(v, OP_Ge, regRowid2, lblDone, regRowid1);
2304 VdbeCoverage(v);
2305 }else if( p->regRowid ){
2306 sqlite3VdbeAddOp2(v, OP_Rowid, p->end.csr, regRowid1);
2307 sqlite3VdbeAddOp3(v, OP_Ge, p->regRowid, lblDone, regRowid1);
drh79f313f2021-04-28 15:43:362308 VdbeCoverageNeverNull(v);
drh113a33c2021-04-24 23:40:052309 }
dane7579a52019-09-25 16:41:442310 sqlite3ReleaseTempReg(pParse, regRowid1);
2311 sqlite3ReleaseTempReg(pParse, regRowid2);
2312 assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_FOLLOWING );
2313 }
2314
dan00267b82019-03-06 21:04:112315 switch( op ){
2316 case WINDOW_RETURN_ROW:
dan6c75b392019-03-08 20:02:522317 csr = p->current.csr;
2318 reg = p->current.reg;
danc782a812019-03-15 20:46:192319 windowReturnOneRow(p);
dan00267b82019-03-06 21:04:112320 break;
2321
2322 case WINDOW_AGGINVERSE:
dan6c75b392019-03-08 20:02:522323 csr = p->start.csr;
2324 reg = p->start.reg;
dana0f6b832019-03-14 16:36:202325 if( pMWin->regStartRowid ){
2326 assert( pMWin->regEndRowid );
2327 sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regStartRowid, 1);
2328 }else{
dan37d296a2019-09-24 20:20:052329 windowAggStep(p, pMWin, csr, 1, p->regArg);
dana0f6b832019-03-14 16:36:202330 }
dan00267b82019-03-06 21:04:112331 break;
2332
dan0525b6f2019-03-18 21:19:402333 default:
2334 assert( op==WINDOW_AGGSTEP );
dan6c75b392019-03-08 20:02:522335 csr = p->end.csr;
2336 reg = p->end.reg;
dana0f6b832019-03-14 16:36:202337 if( pMWin->regStartRowid ){
2338 assert( pMWin->regEndRowid );
2339 sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regEndRowid, 1);
2340 }else{
dan37d296a2019-09-24 20:20:052341 windowAggStep(p, pMWin, csr, 0, p->regArg);
dana0f6b832019-03-14 16:36:202342 }
dan00267b82019-03-06 21:04:112343 break;
2344 }
2345
danb560a712019-03-13 15:29:142346 if( op==p->eDelete ){
2347 sqlite3VdbeAddOp1(v, OP_Delete, csr);
2348 sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
2349 }
2350
danc8137502019-03-07 19:26:172351 if( jumpOnEof ){
2352 sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+2);
dan1d4b25f2019-03-19 16:49:152353 VdbeCoverage(v);
danc8137502019-03-07 19:26:172354 ret = sqlite3VdbeAddOp0(v, OP_Goto);
2355 }else{
dan6c75b392019-03-08 20:02:522356 sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+1+bPeer);
dan1d4b25f2019-03-19 16:49:152357 VdbeCoverage(v);
dan6c75b392019-03-08 20:02:522358 if( bPeer ){
dan37d296a2019-09-24 20:20:052359 sqlite3VdbeAddOp2(v, OP_Goto, 0, lblDone);
dan6c75b392019-03-08 20:02:522360 }
dan00267b82019-03-06 21:04:112361 }
danc8137502019-03-07 19:26:172362
dan6c75b392019-03-08 20:02:522363 if( bPeer ){
dan6c75b392019-03-08 20:02:522364 int nReg = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);
dane7579a52019-09-25 16:41:442365 int regTmp = (nReg ? sqlite3GetTempRange(pParse, nReg) : 0);
dan6c75b392019-03-08 20:02:522366 windowReadPeerValues(p, csr, regTmp);
dan935d9d82019-03-12 15:21:512367 windowIfNewPeer(pParse, pMWin->pOrderBy, regTmp, reg, addrContinue);
dan6c75b392019-03-08 20:02:522368 sqlite3ReleaseTempRange(pParse, regTmp, nReg);
dan00267b82019-03-06 21:04:112369 }
dan6c75b392019-03-08 20:02:522370
dan72b9fdc2019-03-09 20:49:172371 if( addrNextRange ){
2372 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNextRange);
2373 }
2374 sqlite3VdbeResolveLabel(v, lblDone);
dan00267b82019-03-06 21:04:112375 return ret;
2376}
2377
dana786e452019-03-11 18:17:042378
dan00267b82019-03-06 21:04:112379/*
dana786e452019-03-11 18:17:042380** Allocate and return a duplicate of the Window object indicated by the
2381** third argument. Set the Window.pOwner field of the new object to
2382** pOwner.
2383*/
2384Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p){
2385 Window *pNew = 0;
2386 if( ALWAYS(p) ){
2387 pNew = sqlite3DbMallocZero(db, sizeof(Window));
2388 if( pNew ){
2389 pNew->zName = sqlite3DbStrDup(db, p->zName);
danb42eb352019-09-16 05:34:082390 pNew->zBase = sqlite3DbStrDup(db, p->zBase);
dana786e452019-03-11 18:17:042391 pNew->pFilter = sqlite3ExprDup(db, p->pFilter, 0);
drh105dcaa2022-03-10 16:01:142392 pNew->pWFunc = p->pWFunc;
dana786e452019-03-11 18:17:042393 pNew->pPartition = sqlite3ExprListDup(db, p->pPartition, 0);
2394 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, 0);
drhfc15f4c2019-03-28 13:03:412395 pNew->eFrmType = p->eFrmType;
dana786e452019-03-11 18:17:042396 pNew->eEnd = p->eEnd;
2397 pNew->eStart = p->eStart;
danc782a812019-03-15 20:46:192398 pNew->eExclude = p->eExclude;
drhb555b082019-07-19 01:11:272399 pNew->regResult = p->regResult;
dan0a21ea92020-02-29 17:19:422400 pNew->regAccum = p->regAccum;
2401 pNew->iArgCol = p->iArgCol;
2402 pNew->iEphCsr = p->iEphCsr;
2403 pNew->bExprArgs = p->bExprArgs;
dana786e452019-03-11 18:17:042404 pNew->pStart = sqlite3ExprDup(db, p->pStart, 0);
2405 pNew->pEnd = sqlite3ExprDup(db, p->pEnd, 0);
2406 pNew->pOwner = pOwner;
danb42eb352019-09-16 05:34:082407 pNew->bImplicitFrame = p->bImplicitFrame;
dana786e452019-03-11 18:17:042408 }
2409 }
2410 return pNew;
2411}
2412
2413/*
2414** Return a copy of the linked list of Window objects passed as the
2415** second argument.
2416*/
2417Window *sqlite3WindowListDup(sqlite3 *db, Window *p){
2418 Window *pWin;
2419 Window *pRet = 0;
2420 Window **pp = &pRet;
2421
2422 for(pWin=p; pWin; pWin=pWin->pNextWin){
2423 *pp = sqlite3WindowDup(db, 0, pWin);
2424 if( *pp==0 ) break;
2425 pp = &((*pp)->pNextWin);
2426 }
2427
2428 return pRet;
2429}
2430
2431/*
larrybrbc917382023-06-07 08:40:312432** Return true if it can be determined at compile time that expression
2433** pExpr evaluates to a value that, when cast to an integer, is greater
dan725b1cf2019-03-26 16:47:172434** than zero. False otherwise.
2435**
larrybrbc917382023-06-07 08:40:312436** If an OOM error occurs, this function sets the Parse.db.mallocFailed
dan725b1cf2019-03-26 16:47:172437** flag and returns zero.
2438*/
2439static int windowExprGtZero(Parse *pParse, Expr *pExpr){
2440 int ret = 0;
2441 sqlite3 *db = pParse->db;
2442 sqlite3_value *pVal = 0;
2443 sqlite3ValueFromExpr(db, pExpr, db->enc, SQLITE_AFF_NUMERIC, &pVal);
2444 if( pVal && sqlite3_value_int(pVal)>0 ){
2445 ret = 1;
2446 }
2447 sqlite3ValueFree(pVal);
2448 return ret;
2449}
2450
2451/*
larrybrbc917382023-06-07 08:40:312452** sqlite3WhereBegin() has already been called for the SELECT statement
dana786e452019-03-11 18:17:042453** passed as the second argument when this function is invoked. It generates
larrybrbc917382023-06-07 08:40:312454** code to populate the Window.regResult register for each window function
dana786e452019-03-11 18:17:042455** and invoke the sub-routine at instruction addrGosub once for each row.
larrybrbc917382023-06-07 08:40:312456** sqlite3WhereEnd() is always called before returning.
dan00267b82019-03-06 21:04:112457**
dana786e452019-03-11 18:17:042458** This function handles several different types of window frames, which
2459** require slightly different processing. The following pseudo code is
2460** used to implement window frames of the form:
dan00267b82019-03-06 21:04:112461**
dana786e452019-03-11 18:17:042462** ROWS BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
dan00267b82019-03-06 21:04:112463**
dana786e452019-03-11 18:17:042464** Other window frame types use variants of the following:
2465**
2466** ... loop started by sqlite3WhereBegin() ...
dan00267b82019-03-06 21:04:112467** if( new partition ){
2468** Gosub flush
dana786e452019-03-11 18:17:042469** }
dan00267b82019-03-06 21:04:112470** Insert new row into eph table.
larrybrbc917382023-06-07 08:40:312471**
dan00267b82019-03-06 21:04:112472** if( first row of partition ){
dana786e452019-03-11 18:17:042473** // Rewind three cursors, all open on the eph table.
2474** Rewind(csrEnd);
2475** Rewind(csrStart);
2476** Rewind(csrCurrent);
larrybrbc917382023-06-07 08:40:312477**
dan00267b82019-03-06 21:04:112478** regEnd = <expr2> // FOLLOWING expression
2479** regStart = <expr1> // PRECEDING expression
2480** }else{
larrybrbc917382023-06-07 08:40:312481** // First time this branch is taken, the eph table contains two
dana786e452019-03-11 18:17:042482** // rows. The first row in the partition, which all three cursors
2483** // currently point to, and the following row.
2484** AGGSTEP
dan00267b82019-03-06 21:04:112485** if( (regEnd--)<=0 ){
dana786e452019-03-11 18:17:042486** RETURN_ROW
2487** if( (regStart--)<=0 ){
2488** AGGINVERSE
dan00267b82019-03-06 21:04:112489** }
2490** }
dana786e452019-03-11 18:17:042491** }
2492** }
dan00267b82019-03-06 21:04:112493** flush:
dana786e452019-03-11 18:17:042494** AGGSTEP
2495** while( 1 ){
2496** RETURN ROW
2497** if( csrCurrent is EOF ) break;
2498** if( (regStart--)<=0 ){
2499** AggInverse(csrStart)
2500** Next(csrStart)
dan00267b82019-03-06 21:04:112501** }
dana786e452019-03-11 18:17:042502** }
dan00267b82019-03-06 21:04:112503**
dana786e452019-03-11 18:17:042504** The pseudo-code above uses the following shorthand:
dan00267b82019-03-06 21:04:112505**
dana786e452019-03-11 18:17:042506** AGGSTEP: invoke the aggregate xStep() function for each window function
2507** with arguments read from the current row of cursor csrEnd, then
2508** step cursor csrEnd forward one row (i.e. sqlite3BtreeNext()).
2509**
larrybrbc917382023-06-07 08:40:312510** RETURN_ROW: return a row to the caller based on the contents of the
2511** current row of csrCurrent and the current state of all
dana786e452019-03-11 18:17:042512** aggregates. Then step cursor csrCurrent forward one row.
2513**
larrybrbc917382023-06-07 08:40:312514** AGGINVERSE: invoke the aggregate xInverse() function for each window
dana786e452019-03-11 18:17:042515** functions with arguments read from the current row of cursor
2516** csrStart. Then step csrStart forward one row.
2517**
2518** There are two other ROWS window frames that are handled significantly
2519** differently from the above - "BETWEEN <expr> PRECEDING AND <expr> PRECEDING"
larrybrbc917382023-06-07 08:40:312520** and "BETWEEN <expr> FOLLOWING AND <expr> FOLLOWING". These are special
dana786e452019-03-11 18:17:042521** cases because they change the order in which the three cursors (csrStart,
2522** csrCurrent and csrEnd) iterate through the ephemeral table. Cases that
2523** use UNBOUNDED or CURRENT ROW are much simpler variations on one of these
2524** three.
2525**
2526** ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
2527**
2528** ... loop started by sqlite3WhereBegin() ...
dan00267b82019-03-06 21:04:112529** if( new partition ){
2530** Gosub flush
dana786e452019-03-11 18:17:042531** }
dan00267b82019-03-06 21:04:112532** Insert new row into eph table.
2533** if( first row of partition ){
dan935d9d82019-03-12 15:21:512534** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
dana786e452019-03-11 18:17:042535** regEnd = <expr2>
2536** regStart = <expr1>
dan00267b82019-03-06 21:04:112537** }else{
dana786e452019-03-11 18:17:042538** if( (regEnd--)<=0 ){
2539** AGGSTEP
2540** }
2541** RETURN_ROW
2542** if( (regStart--)<=0 ){
2543** AGGINVERSE
2544** }
2545** }
2546** }
dan00267b82019-03-06 21:04:112547** flush:
dana786e452019-03-11 18:17:042548** if( (regEnd--)<=0 ){
2549** AGGSTEP
2550** }
2551** RETURN_ROW
2552**
2553**
2554** ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
2555**
2556** ... loop started by sqlite3WhereBegin() ...
2557** if( new partition ){
2558** Gosub flush
2559** }
2560** Insert new row into eph table.
2561** if( first row of partition ){
dan935d9d82019-03-12 15:21:512562** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
dana786e452019-03-11 18:17:042563** regEnd = <expr2>
2564** regStart = regEnd - <expr1>
2565** }else{
2566** AGGSTEP
2567** if( (regEnd--)<=0 ){
2568** RETURN_ROW
2569** }
2570** if( (regStart--)<=0 ){
2571** AGGINVERSE
2572** }
2573** }
2574** }
2575** flush:
2576** AGGSTEP
2577** while( 1 ){
2578** if( (regEnd--)<=0 ){
2579** RETURN_ROW
2580** if( eof ) break;
2581** }
2582** if( (regStart--)<=0 ){
2583** AGGINVERSE
2584** if( eof ) break
2585** }
2586** }
2587** while( !eof csrCurrent ){
2588** RETURN_ROW
2589** }
2590**
2591** For the most part, the patterns above are adapted to support UNBOUNDED by
2592** assuming that it is equivalent to "infinity PRECEDING/FOLLOWING" and
larrybrbc917382023-06-07 08:40:312593** CURRENT ROW by assuming that it is equivalent to "0 PRECEDING/FOLLOWING".
dana786e452019-03-11 18:17:042594** This is optimized of course - branches that will never be taken and
2595** conditions that are always true are omitted from the VM code. The only
2596** exceptional case is:
2597**
2598** ROWS BETWEEN <expr1> FOLLOWING AND UNBOUNDED FOLLOWING
2599**
2600** ... loop started by sqlite3WhereBegin() ...
2601** if( new partition ){
2602** Gosub flush
2603** }
2604** Insert new row into eph table.
2605** if( first row of partition ){
dan935d9d82019-03-12 15:21:512606** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
dana786e452019-03-11 18:17:042607** regStart = <expr1>
2608** }else{
2609** AGGSTEP
2610** }
2611** }
2612** flush:
2613** AGGSTEP
2614** while( 1 ){
2615** if( (regStart--)<=0 ){
2616** AGGINVERSE
2617** if( eof ) break
2618** }
2619** RETURN_ROW
2620** }
2621** while( !eof csrCurrent ){
2622** RETURN_ROW
2623** }
dan935d9d82019-03-12 15:21:512624**
2625** Also requiring special handling are the cases:
2626**
2627** ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
2628** ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
2629**
2630** when (expr1 < expr2). This is detected at runtime, not by this function.
2631** To handle this case, the pseudo-code programs depicted above are modified
2632** slightly to be:
2633**
2634** ... loop started by sqlite3WhereBegin() ...
2635** if( new partition ){
2636** Gosub flush
2637** }
2638** Insert new row into eph table.
2639** if( first row of partition ){
2640** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2641** regEnd = <expr2>
2642** regStart = <expr1>
2643** if( regEnd < regStart ){
2644** RETURN_ROW
2645** delete eph table contents
2646** continue
2647** }
2648** ...
2649**
2650** The new "continue" statement in the above jumps to the next iteration
2651** of the outer loop - the one started by sqlite3WhereBegin().
2652**
2653** The various GROUPS cases are implemented using the same patterns as
2654** ROWS. The VM code is modified slightly so that:
2655**
2656** 1. The else branch in the main loop is only taken if the row just
2657** added to the ephemeral table is the start of a new group. In
2658** other words, it becomes:
2659**
2660** ... loop started by sqlite3WhereBegin() ...
2661** if( new partition ){
2662** Gosub flush
2663** }
2664** Insert new row into eph table.
2665** if( first row of partition ){
2666** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2667** regEnd = <expr2>
2668** regStart = <expr1>
2669** }else if( new group ){
larrybrbc917382023-06-07 08:40:312670** ...
dan935d9d82019-03-12 15:21:512671** }
2672** }
2673**
larrybrbc917382023-06-07 08:40:312674** 2. Instead of processing a single row, each RETURN_ROW, AGGSTEP or
dan935d9d82019-03-12 15:21:512675** AGGINVERSE step processes the current row of the relevant cursor and
2676** all subsequent rows belonging to the same group.
2677**
larrybrbc917382023-06-07 08:40:312678** RANGE window frames are a little different again. As for GROUPS, the
dan935d9d82019-03-12 15:21:512679** main loop runs once per group only. And RETURN_ROW, AGGSTEP and AGGINVERSE
2680** deal in groups instead of rows. As for ROWS and GROUPS, there are three
2681** basic cases:
2682**
2683** RANGE BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
2684**
2685** ... loop started by sqlite3WhereBegin() ...
2686** if( new partition ){
2687** Gosub flush
2688** }
2689** Insert new row into eph table.
2690** if( first row of partition ){
2691** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2692** regEnd = <expr2>
2693** regStart = <expr1>
2694** }else{
2695** AGGSTEP
2696** while( (csrCurrent.key + regEnd) < csrEnd.key ){
2697** RETURN_ROW
2698** while( csrStart.key + regStart) < csrCurrent.key ){
2699** AGGINVERSE
2700** }
2701** }
2702** }
2703** }
2704** flush:
2705** AGGSTEP
2706** while( 1 ){
2707** RETURN ROW
2708** if( csrCurrent is EOF ) break;
2709** while( csrStart.key + regStart) < csrCurrent.key ){
2710** AGGINVERSE
2711** }
2712** }
2713** }
2714**
larrybrbc917382023-06-07 08:40:312715** In the above notation, "csr.key" means the current value of the ORDER BY
dan935d9d82019-03-12 15:21:512716** expression (there is only ever 1 for a RANGE that uses an <expr> FOLLOWING
2717** or <expr PRECEDING) read from cursor csr.
2718**
2719** RANGE BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
2720**
2721** ... loop started by sqlite3WhereBegin() ...
2722** if( new partition ){
2723** Gosub flush
2724** }
2725** Insert new row into eph table.
2726** if( first row of partition ){
2727** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2728** regEnd = <expr2>
2729** regStart = <expr1>
2730** }else{
dan37d296a2019-09-24 20:20:052731** while( (csrEnd.key + regEnd) <= csrCurrent.key ){
dan935d9d82019-03-12 15:21:512732** AGGSTEP
2733** }
dan935d9d82019-03-12 15:21:512734** while( (csrStart.key + regStart) < csrCurrent.key ){
2735** AGGINVERSE
2736** }
dane7579a52019-09-25 16:41:442737** RETURN_ROW
dan935d9d82019-03-12 15:21:512738** }
2739** }
2740** flush:
2741** while( (csrEnd.key + regEnd) <= csrCurrent.key ){
2742** AGGSTEP
2743** }
dan3f49c322019-04-03 16:27:442744** while( (csrStart.key + regStart) < csrCurrent.key ){
2745** AGGINVERSE
2746** }
dane7579a52019-09-25 16:41:442747** RETURN_ROW
dan935d9d82019-03-12 15:21:512748**
2749** RANGE BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
2750**
2751** ... loop started by sqlite3WhereBegin() ...
2752** if( new partition ){
2753** Gosub flush
2754** }
2755** Insert new row into eph table.
2756** if( first row of partition ){
2757** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2758** regEnd = <expr2>
2759** regStart = <expr1>
2760** }else{
2761** AGGSTEP
2762** while( (csrCurrent.key + regEnd) < csrEnd.key ){
2763** while( (csrCurrent.key + regStart) > csrStart.key ){
2764** AGGINVERSE
2765** }
2766** RETURN_ROW
2767** }
2768** }
2769** }
2770** flush:
2771** AGGSTEP
2772** while( 1 ){
2773** while( (csrCurrent.key + regStart) > csrStart.key ){
2774** AGGINVERSE
2775** if( eof ) break "while( 1 )" loop.
2776** }
2777** RETURN_ROW
2778** }
2779** while( !eof csrCurrent ){
2780** RETURN_ROW
2781** }
2782**
danb6f2dea2019-03-13 17:20:272783** The text above leaves out many details. Refer to the code and comments
2784** below for a more complete picture.
dan00267b82019-03-06 21:04:112785*/
dana786e452019-03-11 18:17:042786void sqlite3WindowCodeStep(
dancc7a8502019-03-11 19:50:542787 Parse *pParse, /* Parse context */
dana786e452019-03-11 18:17:042788 Select *p, /* Rewritten SELECT statement */
2789 WhereInfo *pWInfo, /* Context returned by sqlite3WhereBegin() */
2790 int regGosub, /* Register for OP_Gosub */
2791 int addrGosub /* OP_Gosub here to return each row */
dan680f6e82019-03-04 21:07:112792){
2793 Window *pMWin = p->pWin;
dan6c75b392019-03-08 20:02:522794 ExprList *pOrderBy = pMWin->pOrderBy;
dan680f6e82019-03-04 21:07:112795 Vdbe *v = sqlite3GetVdbe(pParse);
dana786e452019-03-11 18:17:042796 int csrWrite; /* Cursor used to write to eph. table */
2797 int csrInput = p->pSrc->a[0].iCursor; /* Cursor of sub-select */
drhb204b6a2024-08-17 23:23:232798 int nInput = p->pSrc->a[0].pSTab->nCol; /* Number of cols returned by sub */
dana786e452019-03-11 18:17:042799 int iInput; /* To iterate through sub cols */
danbf845152019-03-16 10:15:242800 int addrNe; /* Address of OP_Ne */
drhd4a591d2019-03-26 16:21:112801 int addrGosubFlush = 0; /* Address of OP_Gosub to flush: */
2802 int addrInteger = 0; /* Address of OP_Integer */
dand4461652019-03-13 08:28:512803 int addrEmpty; /* Address of OP_Rewind in flush: */
dana786e452019-03-11 18:17:042804 int regNew; /* Array of registers holding new input row */
2805 int regRecord; /* regNew array in record form */
dana786e452019-03-11 18:17:042806 int regNewPeer = 0; /* Peer values for new row (part of regNew) */
2807 int regPeer = 0; /* Peer values for current row */
dand4461652019-03-13 08:28:512808 int regFlushPart = 0; /* Register for "Gosub flush_partition" */
dana786e452019-03-11 18:17:042809 WindowCodeArg s; /* Context object for sub-routines */
dan935d9d82019-03-12 15:21:512810 int lblWhereEnd; /* Label just before sqlite3WhereEnd() code */
dane7579a52019-09-25 16:41:442811 int regStart = 0; /* Value of <expr> PRECEDING */
2812 int regEnd = 0; /* Value of <expr> FOLLOWING */
dan680f6e82019-03-04 21:07:112813
larrybrbc917382023-06-07 08:40:312814 assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_CURRENT
2815 || pMWin->eStart==TK_FOLLOWING || pMWin->eStart==TK_UNBOUNDED
dan72b9fdc2019-03-09 20:49:172816 );
larrybrbc917382023-06-07 08:40:312817 assert( pMWin->eEnd==TK_FOLLOWING || pMWin->eEnd==TK_CURRENT
2818 || pMWin->eEnd==TK_UNBOUNDED || pMWin->eEnd==TK_PRECEDING
dan72b9fdc2019-03-09 20:49:172819 );
dan108e6b22019-03-18 18:55:352820 assert( pMWin->eExclude==0 || pMWin->eExclude==TK_CURRENT
2821 || pMWin->eExclude==TK_GROUP || pMWin->eExclude==TK_TIES
2822 || pMWin->eExclude==TK_NO
2823 );
dan72b9fdc2019-03-09 20:49:172824
dan935d9d82019-03-12 15:21:512825 lblWhereEnd = sqlite3VdbeMakeLabel(pParse);
dana786e452019-03-11 18:17:042826
2827 /* Fill in the context object */
dan00267b82019-03-06 21:04:112828 memset(&s, 0, sizeof(WindowCodeArg));
2829 s.pParse = pParse;
2830 s.pMWin = pMWin;
2831 s.pVdbe = v;
2832 s.regGosub = regGosub;
2833 s.addrGosub = addrGosub;
dan6c75b392019-03-08 20:02:522834 s.current.csr = pMWin->iEphCsr;
dana786e452019-03-11 18:17:042835 csrWrite = s.current.csr+1;
dan6c75b392019-03-08 20:02:522836 s.start.csr = s.current.csr+2;
2837 s.end.csr = s.current.csr+3;
danb33487b2019-03-06 17:12:322838
danb560a712019-03-13 15:29:142839 /* Figure out when rows may be deleted from the ephemeral table. There
larrybrbc917382023-06-07 08:40:312840 ** are four options - they may never be deleted (eDelete==0), they may
danb560a712019-03-13 15:29:142841 ** be deleted as soon as they are no longer part of the window frame
larrybrbc917382023-06-07 08:40:312842 ** (eDelete==WINDOW_AGGINVERSE), they may be deleted as after the row
danb560a712019-03-13 15:29:142843 ** has been returned to the caller (WINDOW_RETURN_ROW), or they may
2844 ** be deleted after they enter the frame (WINDOW_AGGSTEP). */
2845 switch( pMWin->eStart ){
dan725b1cf2019-03-26 16:47:172846 case TK_FOLLOWING:
drhfc15f4c2019-03-28 13:03:412847 if( pMWin->eFrmType!=TK_RANGE
2848 && windowExprGtZero(pParse, pMWin->pStart)
2849 ){
dan725b1cf2019-03-26 16:47:172850 s.eDelete = WINDOW_RETURN_ROW;
danb560a712019-03-13 15:29:142851 }
danb560a712019-03-13 15:29:142852 break;
danb560a712019-03-13 15:29:142853 case TK_UNBOUNDED:
2854 if( windowCacheFrame(pMWin)==0 ){
2855 if( pMWin->eEnd==TK_PRECEDING ){
drhfc15f4c2019-03-28 13:03:412856 if( pMWin->eFrmType!=TK_RANGE
2857 && windowExprGtZero(pParse, pMWin->pEnd)
2858 ){
dan725b1cf2019-03-26 16:47:172859 s.eDelete = WINDOW_AGGSTEP;
2860 }
danb560a712019-03-13 15:29:142861 }else{
2862 s.eDelete = WINDOW_RETURN_ROW;
2863 }
2864 }
2865 break;
2866 default:
2867 s.eDelete = WINDOW_AGGINVERSE;
2868 break;
2869 }
2870
dand4461652019-03-13 08:28:512871 /* Allocate registers for the array of values from the sub-query, the
larrybrbc917382023-06-07 08:40:312872 ** same values in record form, and the rowid used to insert said record
dand4461652019-03-13 08:28:512873 ** into the ephemeral table. */
dana786e452019-03-11 18:17:042874 regNew = pParse->nMem+1;
2875 pParse->nMem += nInput;
2876 regRecord = ++pParse->nMem;
drh113a33c2021-04-24 23:40:052877 s.regRowid = ++pParse->nMem;
dan54975cd2019-03-07 20:47:462878
dana786e452019-03-11 18:17:042879 /* If the window frame contains an "<expr> PRECEDING" or "<expr> FOLLOWING"
2880 ** clause, allocate registers to store the results of evaluating each
2881 ** <expr>. */
dan54975cd2019-03-07 20:47:462882 if( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_FOLLOWING ){
dane7579a52019-09-25 16:41:442883 regStart = ++pParse->nMem;
dan54975cd2019-03-07 20:47:462884 }
2885 if( pMWin->eEnd==TK_PRECEDING || pMWin->eEnd==TK_FOLLOWING ){
dane7579a52019-09-25 16:41:442886 regEnd = ++pParse->nMem;
dan54975cd2019-03-07 20:47:462887 }
dan680f6e82019-03-04 21:07:112888
dan72b9fdc2019-03-09 20:49:172889 /* If this is not a "ROWS BETWEEN ..." frame, then allocate arrays of
larrybrbc917382023-06-07 08:40:312890 ** registers to store copies of the ORDER BY expressions (peer values)
dana786e452019-03-11 18:17:042891 ** for the main loop, and for each cursor (start, current and end). */
drhfc15f4c2019-03-28 13:03:412892 if( pMWin->eFrmType!=TK_ROWS ){
dan6c75b392019-03-08 20:02:522893 int nPeer = (pOrderBy ? pOrderBy->nExpr : 0);
dana786e452019-03-11 18:17:042894 regNewPeer = regNew + pMWin->nBufferCol;
dan6c75b392019-03-08 20:02:522895 if( pMWin->pPartition ) regNewPeer += pMWin->pPartition->nExpr;
dan6c75b392019-03-08 20:02:522896 regPeer = pParse->nMem+1; pParse->nMem += nPeer;
2897 s.start.reg = pParse->nMem+1; pParse->nMem += nPeer;
2898 s.current.reg = pParse->nMem+1; pParse->nMem += nPeer;
2899 s.end.reg = pParse->nMem+1; pParse->nMem += nPeer;
2900 }
2901
dan680f6e82019-03-04 21:07:112902 /* Load the column values for the row returned by the sub-select
dana786e452019-03-11 18:17:042903 ** into an array of registers starting at regNew. Assemble them into
2904 ** a record in register regRecord. */
2905 for(iInput=0; iInput<nInput; iInput++){
2906 sqlite3VdbeAddOp3(v, OP_Column, csrInput, iInput, regNew+iInput);
dan680f6e82019-03-04 21:07:112907 }
dana786e452019-03-11 18:17:042908 sqlite3VdbeAddOp3(v, OP_MakeRecord, regNew, nInput, regRecord);
dan680f6e82019-03-04 21:07:112909
danb33487b2019-03-06 17:12:322910 /* An input row has just been read into an array of registers starting
larrybrbc917382023-06-07 08:40:312911 ** at regNew. If the window has a PARTITION clause, this block generates
danb33487b2019-03-06 17:12:322912 ** VM code to check if the input row is the start of a new partition.
2913 ** If so, it does an OP_Gosub to an address to be filled in later. The
dana786e452019-03-11 18:17:042914 ** address of the OP_Gosub is stored in local variable addrGosubFlush. */
dan680f6e82019-03-04 21:07:112915 if( pMWin->pPartition ){
2916 int addr;
2917 ExprList *pPart = pMWin->pPartition;
2918 int nPart = pPart->nExpr;
dana786e452019-03-11 18:17:042919 int regNewPart = regNew + pMWin->nBufferCol;
dan680f6e82019-03-04 21:07:112920 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pPart, 0, 0);
2921
dand4461652019-03-13 08:28:512922 regFlushPart = ++pParse->nMem;
dan680f6e82019-03-04 21:07:112923 addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPart, pMWin->regPart, nPart);
2924 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
danb33487b2019-03-06 17:12:322925 sqlite3VdbeAddOp3(v, OP_Jump, addr+2, addr+4, addr+2);
dan680f6e82019-03-04 21:07:112926 VdbeCoverageEqNe(v);
2927 addrGosubFlush = sqlite3VdbeAddOp1(v, OP_Gosub, regFlushPart);
2928 VdbeComment((v, "call flush_partition"));
danb33487b2019-03-06 17:12:322929 sqlite3VdbeAddOp3(v, OP_Copy, regNewPart, pMWin->regPart, nPart-1);
dan680f6e82019-03-04 21:07:112930 }
2931
2932 /* Insert the new row into the ephemeral table */
drh113a33c2021-04-24 23:40:052933 sqlite3VdbeAddOp2(v, OP_NewRowid, csrWrite, s.regRowid);
2934 sqlite3VdbeAddOp3(v, OP_Insert, csrWrite, regRecord, s.regRowid);
2935 addrNe = sqlite3VdbeAddOp3(v, OP_Ne, pMWin->regOne, 0, s.regRowid);
drh83c5bb92019-04-01 15:55:382936 VdbeCoverageNeverNull(v);
danb25a2142019-03-05 19:29:362937
danb33487b2019-03-06 17:12:322938 /* This block is run for the first row of each partition */
dana786e452019-03-11 18:17:042939 s.regArg = windowInitAccum(pParse, pMWin);
dan680f6e82019-03-04 21:07:112940
dane7579a52019-09-25 16:41:442941 if( regStart ){
2942 sqlite3ExprCode(pParse, pMWin->pStart, regStart);
2943 windowCheckValue(pParse, regStart, 0 + (pMWin->eFrmType==TK_RANGE?3:0));
dan54975cd2019-03-07 20:47:462944 }
dane7579a52019-09-25 16:41:442945 if( regEnd ){
2946 sqlite3ExprCode(pParse, pMWin->pEnd, regEnd);
2947 windowCheckValue(pParse, regEnd, 1 + (pMWin->eFrmType==TK_RANGE?3:0));
dan54975cd2019-03-07 20:47:462948 }
danb25a2142019-03-05 19:29:362949
dane7579a52019-09-25 16:41:442950 if( pMWin->eFrmType!=TK_RANGE && pMWin->eStart==pMWin->eEnd && regStart ){
danb25a2142019-03-05 19:29:362951 int op = ((pMWin->eStart==TK_FOLLOWING) ? OP_Ge : OP_Le);
dane7579a52019-09-25 16:41:442952 int addrGe = sqlite3VdbeAddOp3(v, op, regStart, 0, regEnd);
drh495ed622019-04-01 16:23:212953 VdbeCoverageNeverNullIf(v, op==OP_Ge); /* NeverNull because bound <expr> */
2954 VdbeCoverageNeverNullIf(v, op==OP_Le); /* values previously checked */
danc782a812019-03-15 20:46:192955 windowAggFinal(&s, 0);
drhd2467a82023-01-11 17:50:242956 sqlite3VdbeAddOp1(v, OP_Rewind, s.current.csr);
danc782a812019-03-15 20:46:192957 windowReturnOneRow(&s);
dancc7a8502019-03-11 19:50:542958 sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr);
dan935d9d82019-03-12 15:21:512959 sqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd);
danb25a2142019-03-05 19:29:362960 sqlite3VdbeJumpHere(v, addrGe);
2961 }
dane7579a52019-09-25 16:41:442962 if( pMWin->eStart==TK_FOLLOWING && pMWin->eFrmType!=TK_RANGE && regEnd ){
dan54975cd2019-03-07 20:47:462963 assert( pMWin->eEnd==TK_FOLLOWING );
dane7579a52019-09-25 16:41:442964 sqlite3VdbeAddOp3(v, OP_Subtract, regStart, regEnd, regStart);
danb25a2142019-03-05 19:29:362965 }
2966
dan54975cd2019-03-07 20:47:462967 if( pMWin->eStart!=TK_UNBOUNDED ){
drhd2467a82023-01-11 17:50:242968 sqlite3VdbeAddOp1(v, OP_Rewind, s.start.csr);
dan54975cd2019-03-07 20:47:462969 }
drhd2467a82023-01-11 17:50:242970 sqlite3VdbeAddOp1(v, OP_Rewind, s.current.csr);
2971 sqlite3VdbeAddOp1(v, OP_Rewind, s.end.csr);
dan6c75b392019-03-08 20:02:522972 if( regPeer && pOrderBy ){
dancc7a8502019-03-11 19:50:542973 sqlite3VdbeAddOp3(v, OP_Copy, regNewPeer, regPeer, pOrderBy->nExpr-1);
dan6c75b392019-03-08 20:02:522974 sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.start.reg, pOrderBy->nExpr-1);
2975 sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.current.reg, pOrderBy->nExpr-1);
2976 sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.end.reg, pOrderBy->nExpr-1);
2977 }
danb25a2142019-03-05 19:29:362978
dan935d9d82019-03-12 15:21:512979 sqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd);
dan680f6e82019-03-04 21:07:112980
danbf845152019-03-16 10:15:242981 sqlite3VdbeJumpHere(v, addrNe);
dan3f49c322019-04-03 16:27:442982
2983 /* Beginning of the block executed for the second and subsequent rows. */
dan6c75b392019-03-08 20:02:522984 if( regPeer ){
dan935d9d82019-03-12 15:21:512985 windowIfNewPeer(pParse, pOrderBy, regNewPeer, regPeer, lblWhereEnd);
dan6c75b392019-03-08 20:02:522986 }
danb25a2142019-03-05 19:29:362987 if( pMWin->eStart==TK_FOLLOWING ){
dan6c75b392019-03-08 20:02:522988 windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
dan54975cd2019-03-07 20:47:462989 if( pMWin->eEnd!=TK_UNBOUNDED ){
drhfc15f4c2019-03-28 13:03:412990 if( pMWin->eFrmType==TK_RANGE ){
dan72b9fdc2019-03-09 20:49:172991 int lbl = sqlite3VdbeMakeLabel(pParse);
2992 int addrNext = sqlite3VdbeCurrentAddr(v);
dane7579a52019-09-25 16:41:442993 windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl);
2994 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
dan72b9fdc2019-03-09 20:49:172995 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
2996 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNext);
2997 sqlite3VdbeResolveLabel(v, lbl);
2998 }else{
dane7579a52019-09-25 16:41:442999 windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 0);
3000 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
dan72b9fdc2019-03-09 20:49:173001 }
dan54975cd2019-03-07 20:47:463002 }
danb25a2142019-03-05 19:29:363003 }else
3004 if( pMWin->eEnd==TK_PRECEDING ){
dan3f49c322019-04-03 16:27:443005 int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE);
dane7579a52019-09-25 16:41:443006 windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0);
3007 if( bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
dan6c75b392019-03-08 20:02:523008 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
dane7579a52019-09-25 16:41:443009 if( !bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
danb25a2142019-03-05 19:29:363010 }else{
mistachkinba9ee092019-03-27 14:58:183011 int addr = 0;
dan6c75b392019-03-08 20:02:523012 windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
dan54975cd2019-03-07 20:47:463013 if( pMWin->eEnd!=TK_UNBOUNDED ){
drhfc15f4c2019-03-28 13:03:413014 if( pMWin->eFrmType==TK_RANGE ){
mistachkinba9ee092019-03-27 14:58:183015 int lbl = 0;
dan72b9fdc2019-03-09 20:49:173016 addr = sqlite3VdbeCurrentAddr(v);
dane7579a52019-09-25 16:41:443017 if( regEnd ){
dan72b9fdc2019-03-09 20:49:173018 lbl = sqlite3VdbeMakeLabel(pParse);
dane7579a52019-09-25 16:41:443019 windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl);
dan72b9fdc2019-03-09 20:49:173020 }
3021 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
dane7579a52019-09-25 16:41:443022 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
3023 if( regEnd ){
dan72b9fdc2019-03-09 20:49:173024 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
3025 sqlite3VdbeResolveLabel(v, lbl);
3026 }
3027 }else{
dane7579a52019-09-25 16:41:443028 if( regEnd ){
3029 addr = sqlite3VdbeAddOp3(v, OP_IfPos, regEnd, 0, 1);
dan1d4b25f2019-03-19 16:49:153030 VdbeCoverage(v);
3031 }
dan72b9fdc2019-03-09 20:49:173032 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
dane7579a52019-09-25 16:41:443033 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
3034 if( regEnd ) sqlite3VdbeJumpHere(v, addr);
dan72b9fdc2019-03-09 20:49:173035 }
dan54975cd2019-03-07 20:47:463036 }
danb25a2142019-03-05 19:29:363037 }
dan680f6e82019-03-04 21:07:113038
dan680f6e82019-03-04 21:07:113039 /* End of the main input loop */
dan935d9d82019-03-12 15:21:513040 sqlite3VdbeResolveLabel(v, lblWhereEnd);
dancc7a8502019-03-11 19:50:543041 sqlite3WhereEnd(pWInfo);
dan680f6e82019-03-04 21:07:113042
3043 /* Fall through */
dancc7a8502019-03-11 19:50:543044 if( pMWin->pPartition ){
dan680f6e82019-03-04 21:07:113045 addrInteger = sqlite3VdbeAddOp2(v, OP_Integer, 0, regFlushPart);
3046 sqlite3VdbeJumpHere(v, addrGosubFlush);
3047 }
3048
drh113a33c2021-04-24 23:40:053049 s.regRowid = 0;
danc8137502019-03-07 19:26:173050 addrEmpty = sqlite3VdbeAddOp1(v, OP_Rewind, csrWrite);
dan1d4b25f2019-03-19 16:49:153051 VdbeCoverage(v);
dan00267b82019-03-06 21:04:113052 if( pMWin->eEnd==TK_PRECEDING ){
dan3f49c322019-04-03 16:27:443053 int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE);
dane7579a52019-09-25 16:41:443054 windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0);
3055 if( bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
dan6c75b392019-03-08 20:02:523056 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
danc8137502019-03-07 19:26:173057 }else if( pMWin->eStart==TK_FOLLOWING ){
3058 int addrStart;
3059 int addrBreak1;
3060 int addrBreak2;
3061 int addrBreak3;
dan6c75b392019-03-08 20:02:523062 windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
drhfc15f4c2019-03-28 13:03:413063 if( pMWin->eFrmType==TK_RANGE ){
dan72b9fdc2019-03-09 20:49:173064 addrStart = sqlite3VdbeCurrentAddr(v);
dane7579a52019-09-25 16:41:443065 addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1);
dan72b9fdc2019-03-09 20:49:173066 addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
3067 }else
dan54975cd2019-03-07 20:47:463068 if( pMWin->eEnd==TK_UNBOUNDED ){
3069 addrStart = sqlite3VdbeCurrentAddr(v);
dane7579a52019-09-25 16:41:443070 addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regStart, 1);
dan6c75b392019-03-08 20:02:523071 addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, 0, 1);
dan54975cd2019-03-07 20:47:463072 }else{
3073 assert( pMWin->eEnd==TK_FOLLOWING );
3074 addrStart = sqlite3VdbeCurrentAddr(v);
dane7579a52019-09-25 16:41:443075 addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 1);
3076 addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1);
dan54975cd2019-03-07 20:47:463077 }
danc8137502019-03-07 19:26:173078 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
3079 sqlite3VdbeJumpHere(v, addrBreak2);
3080 addrStart = sqlite3VdbeCurrentAddr(v);
dan6c75b392019-03-08 20:02:523081 addrBreak3 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
danc8137502019-03-07 19:26:173082 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
3083 sqlite3VdbeJumpHere(v, addrBreak1);
3084 sqlite3VdbeJumpHere(v, addrBreak3);
danb25a2142019-03-05 19:29:363085 }else{
dan00267b82019-03-06 21:04:113086 int addrBreak;
danc8137502019-03-07 19:26:173087 int addrStart;
dan6c75b392019-03-08 20:02:523088 windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
danc8137502019-03-07 19:26:173089 addrStart = sqlite3VdbeCurrentAddr(v);
dan6c75b392019-03-08 20:02:523090 addrBreak = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
dane7579a52019-09-25 16:41:443091 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
dan00267b82019-03-06 21:04:113092 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
3093 sqlite3VdbeJumpHere(v, addrBreak);
danb25a2142019-03-05 19:29:363094 }
danc8137502019-03-07 19:26:173095 sqlite3VdbeJumpHere(v, addrEmpty);
3096
dan6c75b392019-03-08 20:02:523097 sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr);
dan680f6e82019-03-04 21:07:113098 if( pMWin->pPartition ){
dana0f6b832019-03-14 16:36:203099 if( pMWin->regStartRowid ){
3100 sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid);
3101 sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid);
3102 }
dan680f6e82019-03-04 21:07:113103 sqlite3VdbeChangeP1(v, addrInteger, sqlite3VdbeCurrentAddr(v));
3104 sqlite3VdbeAddOp1(v, OP_Return, regFlushPart);
3105 }
3106}
3107
dan67a9b8e2018-06-22 20:51:353108#endif /* SQLITE_OMIT_WINDOWFUNC */