blob: d3603e7a1e68591d39f89ffb334267f2b5d8bb9f [file] [log] [blame]
dan86fb6e12018-05-16 20:58:07 +00001/*
dan26522d12018-06-11 18:16:51 +00002** 2018 May 08
dan86fb6e12018-05-16 20:58:07 +00003**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11*************************************************************************
12*/
13#include "sqliteInt.h"
14
dan67a9b8e2018-06-22 20:51:35 +000015#ifndef SQLITE_OMIT_WINDOWFUNC
16
dandfa552f2018-06-02 21:04:28 +000017/*
dan73925692018-06-12 18:40:17 +000018** SELECT REWRITING
19**
20** Any SELECT statement that contains one or more window functions in
21** either the select list or ORDER BY clause (the only two places window
22** functions may be used) is transformed by function sqlite3WindowRewrite()
23** in order to support window function processing. For example, with the
24** schema:
25**
26** CREATE TABLE t1(a, b, c, d, e, f, g);
27**
28** the statement:
29**
30** SELECT a+1, max(b) OVER (PARTITION BY c ORDER BY d) FROM t1 ORDER BY e;
31**
32** is transformed to:
33**
34** SELECT a+1, max(b) OVER (PARTITION BY c ORDER BY d) FROM (
35** SELECT a, e, c, d, b FROM t1 ORDER BY c, d
36** ) ORDER BY e;
37**
38** The flattening optimization is disabled when processing this transformed
39** SELECT statement. This allows the implementation of the window function
40** (in this case max()) to process rows sorted in order of (c, d), which
41** makes things easier for obvious reasons. More generally:
42**
43** * FROM, WHERE, GROUP BY and HAVING clauses are all moved to
44** the sub-query.
45**
46** * ORDER BY, LIMIT and OFFSET remain part of the parent query.
47**
48** * Terminals from each of the expression trees that make up the
49** select-list and ORDER BY expressions in the parent query are
50** selected by the sub-query. For the purposes of the transformation,
51** terminals are column references and aggregate functions.
52**
53** If there is more than one window function in the SELECT that uses
54** the same window declaration (the OVER bit), then a single scan may
55** be used to process more than one window function. For example:
56**
57** SELECT max(b) OVER (PARTITION BY c ORDER BY d),
58** min(e) OVER (PARTITION BY c ORDER BY d)
59** FROM t1;
60**
61** is transformed in the same way as the example above. However:
62**
63** SELECT max(b) OVER (PARTITION BY c ORDER BY d),
64** min(e) OVER (PARTITION BY a ORDER BY b)
65** FROM t1;
66**
67** Must be transformed to:
68**
69** SELECT max(b) OVER (PARTITION BY c ORDER BY d) FROM (
70** SELECT e, min(e) OVER (PARTITION BY a ORDER BY b), c, d, b FROM
71** SELECT a, e, c, d, b FROM t1 ORDER BY a, b
72** ) ORDER BY c, d
73** ) ORDER BY e;
74**
75** so that both min() and max() may process rows in the order defined by
76** their respective window declarations.
77**
78** INTERFACE WITH SELECT.C
79**
80** When processing the rewritten SELECT statement, code in select.c calls
81** sqlite3WhereBegin() to begin iterating through the results of the
82** sub-query, which is always implemented as a co-routine. It then calls
83** sqlite3WindowCodeStep() to process rows and finish the scan by calling
84** sqlite3WhereEnd().
85**
86** sqlite3WindowCodeStep() generates VM code so that, for each row returned
87** by the sub-query a sub-routine (OP_Gosub) coded by select.c is invoked.
88** When the sub-routine is invoked:
89**
90** * The results of all window-functions for the row are stored
91** in the associated Window.regResult registers.
92**
93** * The required terminal values are stored in the current row of
94** temp table Window.iEphCsr.
95**
96** In some cases, depending on the window frame and the specific window
97** functions invoked, sqlite3WindowCodeStep() caches each entire partition
98** in a temp table before returning any rows. In other cases it does not.
99** This detail is encapsulated within this file, the code generated by
100** select.c is the same in either case.
101**
102** BUILT-IN WINDOW FUNCTIONS
103**
104** This implementation features the following built-in window functions:
105**
106** row_number()
107** rank()
108** dense_rank()
109** percent_rank()
110** cume_dist()
111** ntile(N)
112** lead(expr [, offset [, default]])
113** lag(expr [, offset [, default]])
114** first_value(expr)
115** last_value(expr)
116** nth_value(expr, N)
117**
118** These are the same built-in window functions supported by Postgres.
119** Although the behaviour of aggregate window functions (functions that
120** can be used as either aggregates or window funtions) allows them to
121** be implemented using an API, built-in window functions are much more
122** esoteric. Additionally, some window functions (e.g. nth_value())
123** may only be implemented by caching the entire partition in memory.
124** As such, some built-in window functions use the same API as aggregate
125** window functions and some are implemented directly using VDBE
126** instructions. Additionally, for those functions that use the API, the
127** window frame is sometimes modified before the SELECT statement is
128** rewritten. For example, regardless of the specified window frame, the
129** row_number() function always uses:
130**
131** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
132**
133** See sqlite3WindowUpdate() for details.
danc0bb4452018-06-12 20:53:38 +0000134**
135** As well as some of the built-in window functions, aggregate window
136** functions min() and max() are implemented using VDBE instructions if
137** the start of the window frame is declared as anything other than
138** UNBOUNDED PRECEDING.
dan73925692018-06-12 18:40:17 +0000139*/
140
141/*
dandfa552f2018-06-02 21:04:28 +0000142** Implementation of built-in window function row_number(). Assumes that the
143** window frame has been coerced to:
144**
145** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
146*/
147static void row_numberStepFunc(
148 sqlite3_context *pCtx,
149 int nArg,
150 sqlite3_value **apArg
151){
152 i64 *p = (i64*)sqlite3_aggregate_context(pCtx, sizeof(*p));
drh5d6374f2018-07-10 23:31:17 +0000153 if( p ) (*p)++;
drhc7bf5712018-07-09 22:49:01 +0000154 UNUSED_PARAMETER(nArg);
155 UNUSED_PARAMETER(apArg);
dandfa552f2018-06-02 21:04:28 +0000156}
dandfa552f2018-06-02 21:04:28 +0000157static void row_numberValueFunc(sqlite3_context *pCtx){
158 i64 *p = (i64*)sqlite3_aggregate_context(pCtx, sizeof(*p));
159 sqlite3_result_int64(pCtx, (p ? *p : 0));
160}
161
162/*
dan2a11bb22018-06-11 20:50:25 +0000163** Context object type used by rank(), dense_rank(), percent_rank() and
164** cume_dist().
dandfa552f2018-06-02 21:04:28 +0000165*/
166struct CallCount {
167 i64 nValue;
168 i64 nStep;
169 i64 nTotal;
170};
171
172/*
dan9c277582018-06-20 09:23:49 +0000173** Implementation of built-in window function dense_rank(). Assumes that
174** the window frame has been set to:
175**
176** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
dandfa552f2018-06-02 21:04:28 +0000177*/
178static void dense_rankStepFunc(
179 sqlite3_context *pCtx,
180 int nArg,
181 sqlite3_value **apArg
182){
183 struct CallCount *p;
184 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
drh5d6374f2018-07-10 23:31:17 +0000185 if( p ) p->nStep = 1;
drhc7bf5712018-07-09 22:49:01 +0000186 UNUSED_PARAMETER(nArg);
187 UNUSED_PARAMETER(apArg);
dandfa552f2018-06-02 21:04:28 +0000188}
dandfa552f2018-06-02 21:04:28 +0000189static void dense_rankValueFunc(sqlite3_context *pCtx){
190 struct CallCount *p;
191 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
192 if( p ){
193 if( p->nStep ){
194 p->nValue++;
195 p->nStep = 0;
196 }
197 sqlite3_result_int64(pCtx, p->nValue);
198 }
199}
200
201/*
dana0f6b832019-03-14 16:36:20 +0000202** Implementation of built-in window function nth_value(). This
203** implementation is used in "slow mode" only - when the EXCLUDE clause
204** is not set to the default value "NO OTHERS".
205*/
206struct NthValueCtx {
207 i64 nStep;
208 sqlite3_value *pValue;
209};
210static void nth_valueStepFunc(
211 sqlite3_context *pCtx,
212 int nArg,
213 sqlite3_value **apArg
214){
215 struct NthValueCtx *p;
216 p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
217 if( p ){
dan108e6b22019-03-18 18:55:35 +0000218 i64 iVal;
219 switch( sqlite3_value_numeric_type(apArg[1]) ){
220 case SQLITE_INTEGER:
221 iVal = sqlite3_value_int64(apArg[1]);
222 break;
223 case SQLITE_FLOAT: {
224 double fVal = sqlite3_value_double(apArg[1]);
225 if( ((i64)fVal)!=fVal ) goto error_out;
226 iVal = (i64)fVal;
227 break;
228 }
229 default:
230 goto error_out;
231 }
232 if( iVal<=0 ) goto error_out;
233
dana0f6b832019-03-14 16:36:20 +0000234 p->nStep++;
235 if( iVal==p->nStep ){
236 p->pValue = sqlite3_value_dup(apArg[0]);
dan108e6b22019-03-18 18:55:35 +0000237 if( !p->pValue ){
238 sqlite3_result_error_nomem(pCtx);
239 }
dana0f6b832019-03-14 16:36:20 +0000240 }
241 }
242 UNUSED_PARAMETER(nArg);
243 UNUSED_PARAMETER(apArg);
dan108e6b22019-03-18 18:55:35 +0000244 return;
245
246 error_out:
247 sqlite3_result_error(
248 pCtx, "second argument to nth_value must be a positive integer", -1
249 );
dana0f6b832019-03-14 16:36:20 +0000250}
dana0f6b832019-03-14 16:36:20 +0000251static void nth_valueFinalizeFunc(sqlite3_context *pCtx){
252 struct NthValueCtx *p;
dan0525b6f2019-03-18 21:19:40 +0000253 p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, 0);
dana0f6b832019-03-14 16:36:20 +0000254 if( p && p->pValue ){
255 sqlite3_result_value(pCtx, p->pValue);
256 sqlite3_value_free(p->pValue);
257 p->pValue = 0;
258 }
259}
260#define nth_valueInvFunc noopStepFunc
dan0525b6f2019-03-18 21:19:40 +0000261#define nth_valueValueFunc noopValueFunc
dana0f6b832019-03-14 16:36:20 +0000262
danc782a812019-03-15 20:46:19 +0000263static void first_valueStepFunc(
264 sqlite3_context *pCtx,
265 int nArg,
266 sqlite3_value **apArg
267){
268 struct NthValueCtx *p;
269 p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
270 if( p && p->pValue==0 ){
271 p->pValue = sqlite3_value_dup(apArg[0]);
dan108e6b22019-03-18 18:55:35 +0000272 if( !p->pValue ){
273 sqlite3_result_error_nomem(pCtx);
274 }
danc782a812019-03-15 20:46:19 +0000275 }
276 UNUSED_PARAMETER(nArg);
277 UNUSED_PARAMETER(apArg);
278}
danc782a812019-03-15 20:46:19 +0000279static void first_valueFinalizeFunc(sqlite3_context *pCtx){
280 struct NthValueCtx *p;
281 p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
282 if( p && p->pValue ){
283 sqlite3_result_value(pCtx, p->pValue);
284 sqlite3_value_free(p->pValue);
285 p->pValue = 0;
286 }
287}
288#define first_valueInvFunc noopStepFunc
dan0525b6f2019-03-18 21:19:40 +0000289#define first_valueValueFunc noopValueFunc
danc782a812019-03-15 20:46:19 +0000290
dana0f6b832019-03-14 16:36:20 +0000291/*
dan9c277582018-06-20 09:23:49 +0000292** Implementation of built-in window function rank(). Assumes that
293** the window frame has been set to:
294**
295** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
dandfa552f2018-06-02 21:04:28 +0000296*/
297static void rankStepFunc(
298 sqlite3_context *pCtx,
299 int nArg,
300 sqlite3_value **apArg
301){
302 struct CallCount *p;
303 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
drh5d6374f2018-07-10 23:31:17 +0000304 if( p ){
dandfa552f2018-06-02 21:04:28 +0000305 p->nStep++;
306 if( p->nValue==0 ){
307 p->nValue = p->nStep;
308 }
309 }
drhc7bf5712018-07-09 22:49:01 +0000310 UNUSED_PARAMETER(nArg);
311 UNUSED_PARAMETER(apArg);
dandfa552f2018-06-02 21:04:28 +0000312}
dandfa552f2018-06-02 21:04:28 +0000313static void rankValueFunc(sqlite3_context *pCtx){
314 struct CallCount *p;
315 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
316 if( p ){
317 sqlite3_result_int64(pCtx, p->nValue);
318 p->nValue = 0;
319 }
320}
321
322/*
dan9c277582018-06-20 09:23:49 +0000323** Implementation of built-in window function percent_rank(). Assumes that
324** the window frame has been set to:
325**
dancc7a8502019-03-11 19:50:54 +0000326** GROUPS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
dandfa552f2018-06-02 21:04:28 +0000327*/
328static void percent_rankStepFunc(
329 sqlite3_context *pCtx,
330 int nArg,
331 sqlite3_value **apArg
332){
333 struct CallCount *p;
dancc7a8502019-03-11 19:50:54 +0000334 UNUSED_PARAMETER(nArg); assert( nArg==0 );
drhd4a591d2019-03-26 16:21:11 +0000335 UNUSED_PARAMETER(apArg);
dandfa552f2018-06-02 21:04:28 +0000336 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
drh5d6374f2018-07-10 23:31:17 +0000337 if( p ){
dancc7a8502019-03-11 19:50:54 +0000338 p->nTotal++;
dandfa552f2018-06-02 21:04:28 +0000339 }
340}
dancc7a8502019-03-11 19:50:54 +0000341static void percent_rankInvFunc(
342 sqlite3_context *pCtx,
343 int nArg,
344 sqlite3_value **apArg
345){
346 struct CallCount *p;
347 UNUSED_PARAMETER(nArg); assert( nArg==0 );
drhd4a591d2019-03-26 16:21:11 +0000348 UNUSED_PARAMETER(apArg);
dancc7a8502019-03-11 19:50:54 +0000349 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
350 p->nStep++;
351}
dandfa552f2018-06-02 21:04:28 +0000352static void percent_rankValueFunc(sqlite3_context *pCtx){
353 struct CallCount *p;
354 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
355 if( p ){
dancc7a8502019-03-11 19:50:54 +0000356 p->nValue = p->nStep;
dandfa552f2018-06-02 21:04:28 +0000357 if( p->nTotal>1 ){
dancc7a8502019-03-11 19:50:54 +0000358 double r = (double)p->nValue / (double)(p->nTotal-1);
dandfa552f2018-06-02 21:04:28 +0000359 sqlite3_result_double(pCtx, r);
360 }else{
danb7306f62018-06-21 19:20:39 +0000361 sqlite3_result_double(pCtx, 0.0);
dandfa552f2018-06-02 21:04:28 +0000362 }
dandfa552f2018-06-02 21:04:28 +0000363 }
364}
dancc7a8502019-03-11 19:50:54 +0000365#define percent_rankFinalizeFunc percent_rankValueFunc
dandfa552f2018-06-02 21:04:28 +0000366
dan9c277582018-06-20 09:23:49 +0000367/*
368** Implementation of built-in window function cume_dist(). Assumes that
369** the window frame has been set to:
370**
dancc7a8502019-03-11 19:50:54 +0000371** GROUPS BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING
dan9c277582018-06-20 09:23:49 +0000372*/
danf1abe362018-06-04 08:22:09 +0000373static void cume_distStepFunc(
374 sqlite3_context *pCtx,
375 int nArg,
376 sqlite3_value **apArg
377){
378 struct CallCount *p;
dancc7a8502019-03-11 19:50:54 +0000379 UNUSED_PARAMETER(nArg); assert( nArg==0 );
drhd4a591d2019-03-26 16:21:11 +0000380 UNUSED_PARAMETER(apArg);
danf1abe362018-06-04 08:22:09 +0000381 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
drh5d6374f2018-07-10 23:31:17 +0000382 if( p ){
dancc7a8502019-03-11 19:50:54 +0000383 p->nTotal++;
danf1abe362018-06-04 08:22:09 +0000384 }
385}
dancc7a8502019-03-11 19:50:54 +0000386static void cume_distInvFunc(
387 sqlite3_context *pCtx,
388 int nArg,
389 sqlite3_value **apArg
390){
391 struct CallCount *p;
392 UNUSED_PARAMETER(nArg); assert( nArg==0 );
drhd4a591d2019-03-26 16:21:11 +0000393 UNUSED_PARAMETER(apArg);
dancc7a8502019-03-11 19:50:54 +0000394 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
395 p->nStep++;
396}
danf1abe362018-06-04 08:22:09 +0000397static void cume_distValueFunc(sqlite3_context *pCtx){
398 struct CallCount *p;
dan0525b6f2019-03-18 21:19:40 +0000399 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, 0);
400 if( p ){
danf1abe362018-06-04 08:22:09 +0000401 double r = (double)(p->nStep) / (double)(p->nTotal);
402 sqlite3_result_double(pCtx, r);
403 }
404}
dancc7a8502019-03-11 19:50:54 +0000405#define cume_distFinalizeFunc cume_distValueFunc
danf1abe362018-06-04 08:22:09 +0000406
dan2a11bb22018-06-11 20:50:25 +0000407/*
408** Context object for ntile() window function.
409*/
dan6bc5c9e2018-06-04 18:55:11 +0000410struct NtileCtx {
411 i64 nTotal; /* Total rows in partition */
412 i64 nParam; /* Parameter passed to ntile(N) */
413 i64 iRow; /* Current row */
414};
415
416/*
417** Implementation of ntile(). This assumes that the window frame has
418** been coerced to:
419**
dancc7a8502019-03-11 19:50:54 +0000420** ROWS CURRENT ROW AND UNBOUNDED FOLLOWING
dan6bc5c9e2018-06-04 18:55:11 +0000421*/
422static void ntileStepFunc(
423 sqlite3_context *pCtx,
424 int nArg,
425 sqlite3_value **apArg
426){
427 struct NtileCtx *p;
dancc7a8502019-03-11 19:50:54 +0000428 assert( nArg==1 ); UNUSED_PARAMETER(nArg);
dan6bc5c9e2018-06-04 18:55:11 +0000429 p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
drh5d6374f2018-07-10 23:31:17 +0000430 if( p ){
dan6bc5c9e2018-06-04 18:55:11 +0000431 if( p->nTotal==0 ){
432 p->nParam = sqlite3_value_int64(apArg[0]);
dan6bc5c9e2018-06-04 18:55:11 +0000433 if( p->nParam<=0 ){
434 sqlite3_result_error(
435 pCtx, "argument of ntile must be a positive integer", -1
436 );
437 }
438 }
dancc7a8502019-03-11 19:50:54 +0000439 p->nTotal++;
dan6bc5c9e2018-06-04 18:55:11 +0000440 }
441}
dancc7a8502019-03-11 19:50:54 +0000442static void ntileInvFunc(
443 sqlite3_context *pCtx,
444 int nArg,
445 sqlite3_value **apArg
446){
447 struct NtileCtx *p;
448 assert( nArg==1 ); UNUSED_PARAMETER(nArg);
drhd4a591d2019-03-26 16:21:11 +0000449 UNUSED_PARAMETER(apArg);
dancc7a8502019-03-11 19:50:54 +0000450 p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
451 p->iRow++;
452}
dan6bc5c9e2018-06-04 18:55:11 +0000453static void ntileValueFunc(sqlite3_context *pCtx){
454 struct NtileCtx *p;
455 p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
456 if( p && p->nParam>0 ){
457 int nSize = (p->nTotal / p->nParam);
458 if( nSize==0 ){
dancc7a8502019-03-11 19:50:54 +0000459 sqlite3_result_int64(pCtx, p->iRow+1);
dan6bc5c9e2018-06-04 18:55:11 +0000460 }else{
461 i64 nLarge = p->nTotal - p->nParam*nSize;
462 i64 iSmall = nLarge*(nSize+1);
dancc7a8502019-03-11 19:50:54 +0000463 i64 iRow = p->iRow;
dan6bc5c9e2018-06-04 18:55:11 +0000464
465 assert( (nLarge*(nSize+1) + (p->nParam-nLarge)*nSize)==p->nTotal );
466
467 if( iRow<iSmall ){
468 sqlite3_result_int64(pCtx, 1 + iRow/(nSize+1));
469 }else{
470 sqlite3_result_int64(pCtx, 1 + nLarge + (iRow-iSmall)/nSize);
471 }
472 }
473 }
474}
dancc7a8502019-03-11 19:50:54 +0000475#define ntileFinalizeFunc ntileValueFunc
dan6bc5c9e2018-06-04 18:55:11 +0000476
dan2a11bb22018-06-11 20:50:25 +0000477/*
478** Context object for last_value() window function.
479*/
dan1c5ed622018-06-05 16:16:17 +0000480struct LastValueCtx {
481 sqlite3_value *pVal;
482 int nVal;
483};
484
485/*
486** Implementation of last_value().
487*/
488static void last_valueStepFunc(
489 sqlite3_context *pCtx,
490 int nArg,
491 sqlite3_value **apArg
492){
493 struct LastValueCtx *p;
drhc7bf5712018-07-09 22:49:01 +0000494 UNUSED_PARAMETER(nArg);
dan9c277582018-06-20 09:23:49 +0000495 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
dan1c5ed622018-06-05 16:16:17 +0000496 if( p ){
497 sqlite3_value_free(p->pVal);
498 p->pVal = sqlite3_value_dup(apArg[0]);
dan6fde1792018-06-15 19:01:35 +0000499 if( p->pVal==0 ){
500 sqlite3_result_error_nomem(pCtx);
501 }else{
502 p->nVal++;
503 }
dan1c5ed622018-06-05 16:16:17 +0000504 }
505}
dan2a11bb22018-06-11 20:50:25 +0000506static void last_valueInvFunc(
dan1c5ed622018-06-05 16:16:17 +0000507 sqlite3_context *pCtx,
508 int nArg,
509 sqlite3_value **apArg
510){
511 struct LastValueCtx *p;
drhc7bf5712018-07-09 22:49:01 +0000512 UNUSED_PARAMETER(nArg);
513 UNUSED_PARAMETER(apArg);
dan9c277582018-06-20 09:23:49 +0000514 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
515 if( ALWAYS(p) ){
dan1c5ed622018-06-05 16:16:17 +0000516 p->nVal--;
517 if( p->nVal==0 ){
518 sqlite3_value_free(p->pVal);
519 p->pVal = 0;
520 }
521 }
522}
523static void last_valueValueFunc(sqlite3_context *pCtx){
524 struct LastValueCtx *p;
dan0525b6f2019-03-18 21:19:40 +0000525 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, 0);
dan1c5ed622018-06-05 16:16:17 +0000526 if( p && p->pVal ){
527 sqlite3_result_value(pCtx, p->pVal);
528 }
529}
530static void last_valueFinalizeFunc(sqlite3_context *pCtx){
531 struct LastValueCtx *p;
dan9c277582018-06-20 09:23:49 +0000532 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
dan1c5ed622018-06-05 16:16:17 +0000533 if( p && p->pVal ){
534 sqlite3_result_value(pCtx, p->pVal);
535 sqlite3_value_free(p->pVal);
536 p->pVal = 0;
537 }
538}
539
dan2a11bb22018-06-11 20:50:25 +0000540/*
drh19dc4d42018-07-08 01:02:26 +0000541** Static names for the built-in window function names. These static
542** names are used, rather than string literals, so that FuncDef objects
543** can be associated with a particular window function by direct
544** comparison of the zName pointer. Example:
545**
546** if( pFuncDef->zName==row_valueName ){ ... }
dan2a11bb22018-06-11 20:50:25 +0000547*/
drh19dc4d42018-07-08 01:02:26 +0000548static const char row_numberName[] = "row_number";
549static const char dense_rankName[] = "dense_rank";
550static const char rankName[] = "rank";
551static const char percent_rankName[] = "percent_rank";
552static const char cume_distName[] = "cume_dist";
553static const char ntileName[] = "ntile";
554static const char last_valueName[] = "last_value";
555static const char nth_valueName[] = "nth_value";
556static const char first_valueName[] = "first_value";
557static const char leadName[] = "lead";
558static const char lagName[] = "lag";
danfe4e25a2018-06-07 20:08:59 +0000559
drh19dc4d42018-07-08 01:02:26 +0000560/*
561** No-op implementations of xStep() and xFinalize(). Used as place-holders
562** for built-in window functions that never call those interfaces.
563**
564** The noopValueFunc() is called but is expected to do nothing. The
565** noopStepFunc() is never called, and so it is marked with NO_TEST to
566** let the test coverage routine know not to expect this function to be
567** invoked.
568*/
569static void noopStepFunc( /*NO_TEST*/
570 sqlite3_context *p, /*NO_TEST*/
571 int n, /*NO_TEST*/
572 sqlite3_value **a /*NO_TEST*/
573){ /*NO_TEST*/
drhc7bf5712018-07-09 22:49:01 +0000574 UNUSED_PARAMETER(p); /*NO_TEST*/
575 UNUSED_PARAMETER(n); /*NO_TEST*/
576 UNUSED_PARAMETER(a); /*NO_TEST*/
drh19dc4d42018-07-08 01:02:26 +0000577 assert(0); /*NO_TEST*/
578} /*NO_TEST*/
drhc7bf5712018-07-09 22:49:01 +0000579static void noopValueFunc(sqlite3_context *p){ UNUSED_PARAMETER(p); /*no-op*/ }
dandfa552f2018-06-02 21:04:28 +0000580
drh19dc4d42018-07-08 01:02:26 +0000581/* Window functions that use all window interfaces: xStep, xFinal,
582** xValue, and xInverse */
583#define WINDOWFUNCALL(name,nArg,extra) { \
dan1c5ed622018-06-05 16:16:17 +0000584 nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
585 name ## StepFunc, name ## FinalizeFunc, name ## ValueFunc, \
drhc7bf5712018-07-09 22:49:01 +0000586 name ## InvFunc, name ## Name, {0} \
dan1c5ed622018-06-05 16:16:17 +0000587}
588
drh19dc4d42018-07-08 01:02:26 +0000589/* Window functions that are implemented using bytecode and thus have
590** no-op routines for their methods */
591#define WINDOWFUNCNOOP(name,nArg,extra) { \
592 nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
593 noopStepFunc, noopValueFunc, noopValueFunc, \
drhc7bf5712018-07-09 22:49:01 +0000594 noopStepFunc, name ## Name, {0} \
drh19dc4d42018-07-08 01:02:26 +0000595}
596
597/* Window functions that use all window interfaces: xStep, the
598** same routine for xFinalize and xValue and which never call
599** xInverse. */
600#define WINDOWFUNCX(name,nArg,extra) { \
601 nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
602 name ## StepFunc, name ## ValueFunc, name ## ValueFunc, \
drhc7bf5712018-07-09 22:49:01 +0000603 noopStepFunc, name ## Name, {0} \
drh19dc4d42018-07-08 01:02:26 +0000604}
605
606
dandfa552f2018-06-02 21:04:28 +0000607/*
608** Register those built-in window functions that are not also aggregates.
609*/
610void sqlite3WindowFunctions(void){
611 static FuncDef aWindowFuncs[] = {
drh19dc4d42018-07-08 01:02:26 +0000612 WINDOWFUNCX(row_number, 0, 0),
613 WINDOWFUNCX(dense_rank, 0, 0),
614 WINDOWFUNCX(rank, 0, 0),
dancc7a8502019-03-11 19:50:54 +0000615 WINDOWFUNCALL(percent_rank, 0, 0),
616 WINDOWFUNCALL(cume_dist, 0, 0),
617 WINDOWFUNCALL(ntile, 1, 0),
drh19dc4d42018-07-08 01:02:26 +0000618 WINDOWFUNCALL(last_value, 1, 0),
dana0f6b832019-03-14 16:36:20 +0000619 WINDOWFUNCALL(nth_value, 2, 0),
danc782a812019-03-15 20:46:19 +0000620 WINDOWFUNCALL(first_value, 1, 0),
drh19dc4d42018-07-08 01:02:26 +0000621 WINDOWFUNCNOOP(lead, 1, 0),
622 WINDOWFUNCNOOP(lead, 2, 0),
623 WINDOWFUNCNOOP(lead, 3, 0),
624 WINDOWFUNCNOOP(lag, 1, 0),
625 WINDOWFUNCNOOP(lag, 2, 0),
626 WINDOWFUNCNOOP(lag, 3, 0),
dandfa552f2018-06-02 21:04:28 +0000627 };
628 sqlite3InsertBuiltinFuncs(aWindowFuncs, ArraySize(aWindowFuncs));
629}
630
dane7c9ca42019-02-16 17:27:51 +0000631static Window *windowFind(Parse *pParse, Window *pList, const char *zName){
632 Window *p;
633 for(p=pList; p; p=p->pNextWin){
634 if( sqlite3StrICmp(p->zName, zName)==0 ) break;
635 }
636 if( p==0 ){
637 sqlite3ErrorMsg(pParse, "no such window: %s", zName);
638 }
639 return p;
640}
641
danc0bb4452018-06-12 20:53:38 +0000642/*
643** This function is called immediately after resolving the function name
644** for a window function within a SELECT statement. Argument pList is a
645** linked list of WINDOW definitions for the current SELECT statement.
646** Argument pFunc is the function definition just resolved and pWin
647** is the Window object representing the associated OVER clause. This
648** function updates the contents of pWin as follows:
649**
650** * If the OVER clause refered to a named window (as in "max(x) OVER win"),
651** search list pList for a matching WINDOW definition, and update pWin
652** accordingly. If no such WINDOW clause can be found, leave an error
653** in pParse.
654**
655** * If the function is a built-in window function that requires the
656** window to be coerced (see "BUILT-IN WINDOW FUNCTIONS" at the top
657** of this file), pWin is updated here.
658*/
dane3bf6322018-06-08 20:58:27 +0000659void sqlite3WindowUpdate(
660 Parse *pParse,
danc0bb4452018-06-12 20:53:38 +0000661 Window *pList, /* List of named windows for this SELECT */
662 Window *pWin, /* Window frame to update */
663 FuncDef *pFunc /* Window function definition */
dane3bf6322018-06-08 20:58:27 +0000664){
drhfc15f4c2019-03-28 13:03:41 +0000665 if( pWin->zName && pWin->eFrmType==0 ){
dane7c9ca42019-02-16 17:27:51 +0000666 Window *p = windowFind(pParse, pList, pWin->zName);
667 if( p==0 ) return;
dane3bf6322018-06-08 20:58:27 +0000668 pWin->pPartition = sqlite3ExprListDup(pParse->db, p->pPartition, 0);
669 pWin->pOrderBy = sqlite3ExprListDup(pParse->db, p->pOrderBy, 0);
670 pWin->pStart = sqlite3ExprDup(pParse->db, p->pStart, 0);
671 pWin->pEnd = sqlite3ExprDup(pParse->db, p->pEnd, 0);
672 pWin->eStart = p->eStart;
673 pWin->eEnd = p->eEnd;
drhfc15f4c2019-03-28 13:03:41 +0000674 pWin->eFrmType = p->eFrmType;
danc782a812019-03-15 20:46:19 +0000675 pWin->eExclude = p->eExclude;
dane7c9ca42019-02-16 17:27:51 +0000676 }else{
677 sqlite3WindowChain(pParse, pWin, pList);
dane3bf6322018-06-08 20:58:27 +0000678 }
drhfc15f4c2019-03-28 13:03:41 +0000679 if( (pWin->eFrmType==TK_RANGE)
dan72b9fdc2019-03-09 20:49:17 +0000680 && (pWin->pStart || pWin->pEnd)
681 && (pWin->pOrderBy==0 || pWin->pOrderBy->nExpr!=1)
682 ){
683 sqlite3ErrorMsg(pParse,
684 "RANGE with offset PRECEDING/FOLLOWING requires one ORDER BY expression"
685 );
686 }else
dandfa552f2018-06-02 21:04:28 +0000687 if( pFunc->funcFlags & SQLITE_FUNC_WINDOW ){
688 sqlite3 *db = pParse->db;
dan8b985602018-06-09 17:43:45 +0000689 if( pWin->pFilter ){
690 sqlite3ErrorMsg(pParse,
691 "FILTER clause may only be used with aggregate window functions"
692 );
dancc7a8502019-03-11 19:50:54 +0000693 }else{
694 struct WindowUpdate {
695 const char *zFunc;
drhfc15f4c2019-03-28 13:03:41 +0000696 int eFrmType;
dancc7a8502019-03-11 19:50:54 +0000697 int eStart;
698 int eEnd;
699 } aUp[] = {
700 { row_numberName, TK_ROWS, TK_UNBOUNDED, TK_CURRENT },
701 { dense_rankName, TK_RANGE, TK_UNBOUNDED, TK_CURRENT },
702 { rankName, TK_RANGE, TK_UNBOUNDED, TK_CURRENT },
703 { percent_rankName, TK_GROUPS, TK_CURRENT, TK_UNBOUNDED },
704 { cume_distName, TK_GROUPS, TK_FOLLOWING, TK_UNBOUNDED },
705 { ntileName, TK_ROWS, TK_CURRENT, TK_UNBOUNDED },
706 { leadName, TK_ROWS, TK_UNBOUNDED, TK_UNBOUNDED },
danb560a712019-03-13 15:29:14 +0000707 { lagName, TK_ROWS, TK_UNBOUNDED, TK_CURRENT },
dancc7a8502019-03-11 19:50:54 +0000708 };
709 int i;
710 for(i=0; i<ArraySize(aUp); i++){
711 if( pFunc->zName==aUp[i].zFunc ){
712 sqlite3ExprDelete(db, pWin->pStart);
713 sqlite3ExprDelete(db, pWin->pEnd);
714 pWin->pEnd = pWin->pStart = 0;
drhfc15f4c2019-03-28 13:03:41 +0000715 pWin->eFrmType = aUp[i].eFrmType;
dancc7a8502019-03-11 19:50:54 +0000716 pWin->eStart = aUp[i].eStart;
717 pWin->eEnd = aUp[i].eEnd;
dana0f6b832019-03-14 16:36:20 +0000718 pWin->eExclude = 0;
dancc7a8502019-03-11 19:50:54 +0000719 if( pWin->eStart==TK_FOLLOWING ){
720 pWin->pStart = sqlite3Expr(db, TK_INTEGER, "1");
721 }
722 break;
723 }
724 }
dandfa552f2018-06-02 21:04:28 +0000725 }
726 }
dan2a11bb22018-06-11 20:50:25 +0000727 pWin->pFunc = pFunc;
dandfa552f2018-06-02 21:04:28 +0000728}
729
danc0bb4452018-06-12 20:53:38 +0000730/*
731** Context object passed through sqlite3WalkExprList() to
732** selectWindowRewriteExprCb() by selectWindowRewriteEList().
733*/
dandfa552f2018-06-02 21:04:28 +0000734typedef struct WindowRewrite WindowRewrite;
735struct WindowRewrite {
736 Window *pWin;
danb556f262018-07-10 17:26:12 +0000737 SrcList *pSrc;
dandfa552f2018-06-02 21:04:28 +0000738 ExprList *pSub;
dan62742fd2019-07-08 12:01:39 +0000739 Table *pTab;
danb556f262018-07-10 17:26:12 +0000740 Select *pSubSelect; /* Current sub-select, if any */
dandfa552f2018-06-02 21:04:28 +0000741};
742
danc0bb4452018-06-12 20:53:38 +0000743/*
744** Callback function used by selectWindowRewriteEList(). If necessary,
745** this function appends to the output expression-list and updates
746** expression (*ppExpr) in place.
747*/
dandfa552f2018-06-02 21:04:28 +0000748static int selectWindowRewriteExprCb(Walker *pWalker, Expr *pExpr){
749 struct WindowRewrite *p = pWalker->u.pRewrite;
750 Parse *pParse = pWalker->pParse;
drh55f66b32019-07-16 19:44:32 +0000751 assert( p!=0 );
752 assert( p->pWin!=0 );
dandfa552f2018-06-02 21:04:28 +0000753
danb556f262018-07-10 17:26:12 +0000754 /* If this function is being called from within a scalar sub-select
755 ** that used by the SELECT statement being processed, only process
756 ** TK_COLUMN expressions that refer to it (the outer SELECT). Do
757 ** not process aggregates or window functions at all, as they belong
758 ** to the scalar sub-select. */
759 if( p->pSubSelect ){
760 if( pExpr->op!=TK_COLUMN ){
761 return WRC_Continue;
762 }else{
763 int nSrc = p->pSrc->nSrc;
764 int i;
765 for(i=0; i<nSrc; i++){
766 if( pExpr->iTable==p->pSrc->a[i].iCursor ) break;
767 }
768 if( i==nSrc ) return WRC_Continue;
769 }
770 }
771
dandfa552f2018-06-02 21:04:28 +0000772 switch( pExpr->op ){
773
774 case TK_FUNCTION:
drheda079c2018-09-20 19:02:15 +0000775 if( !ExprHasProperty(pExpr, EP_WinFunc) ){
dandfa552f2018-06-02 21:04:28 +0000776 break;
777 }else{
778 Window *pWin;
779 for(pWin=p->pWin; pWin; pWin=pWin->pNextWin){
drheda079c2018-09-20 19:02:15 +0000780 if( pExpr->y.pWin==pWin ){
dan2a11bb22018-06-11 20:50:25 +0000781 assert( pWin->pOwner==pExpr );
dandfa552f2018-06-02 21:04:28 +0000782 return WRC_Prune;
783 }
784 }
785 }
786 /* Fall through. */
787
dan73925692018-06-12 18:40:17 +0000788 case TK_AGG_FUNCTION:
dandfa552f2018-06-02 21:04:28 +0000789 case TK_COLUMN: {
790 Expr *pDup = sqlite3ExprDup(pParse->db, pExpr, 0);
791 p->pSub = sqlite3ExprListAppend(pParse, p->pSub, pDup);
792 if( p->pSub ){
793 assert( ExprHasProperty(pExpr, EP_Static)==0 );
794 ExprSetProperty(pExpr, EP_Static);
795 sqlite3ExprDelete(pParse->db, pExpr);
796 ExprClearProperty(pExpr, EP_Static);
797 memset(pExpr, 0, sizeof(Expr));
798
799 pExpr->op = TK_COLUMN;
800 pExpr->iColumn = p->pSub->nExpr-1;
801 pExpr->iTable = p->pWin->iEphCsr;
dan62742fd2019-07-08 12:01:39 +0000802 pExpr->y.pTab = p->pTab;
dandfa552f2018-06-02 21:04:28 +0000803 }
804
805 break;
806 }
807
808 default: /* no-op */
809 break;
810 }
811
812 return WRC_Continue;
813}
danc0bb4452018-06-12 20:53:38 +0000814static int selectWindowRewriteSelectCb(Walker *pWalker, Select *pSelect){
danb556f262018-07-10 17:26:12 +0000815 struct WindowRewrite *p = pWalker->u.pRewrite;
816 Select *pSave = p->pSubSelect;
817 if( pSave==pSelect ){
818 return WRC_Continue;
819 }else{
820 p->pSubSelect = pSelect;
821 sqlite3WalkSelect(pWalker, pSelect);
822 p->pSubSelect = pSave;
823 }
danc0bb4452018-06-12 20:53:38 +0000824 return WRC_Prune;
825}
dandfa552f2018-06-02 21:04:28 +0000826
danc0bb4452018-06-12 20:53:38 +0000827
828/*
829** Iterate through each expression in expression-list pEList. For each:
830**
831** * TK_COLUMN,
832** * aggregate function, or
833** * window function with a Window object that is not a member of the
danb556f262018-07-10 17:26:12 +0000834** Window list passed as the second argument (pWin).
danc0bb4452018-06-12 20:53:38 +0000835**
836** Append the node to output expression-list (*ppSub). And replace it
837** with a TK_COLUMN that reads the (N-1)th element of table
838** pWin->iEphCsr, where N is the number of elements in (*ppSub) after
839** appending the new one.
840*/
dan13b08bb2018-06-15 20:46:12 +0000841static void selectWindowRewriteEList(
dandfa552f2018-06-02 21:04:28 +0000842 Parse *pParse,
843 Window *pWin,
danb556f262018-07-10 17:26:12 +0000844 SrcList *pSrc,
dandfa552f2018-06-02 21:04:28 +0000845 ExprList *pEList, /* Rewrite expressions in this list */
dan62742fd2019-07-08 12:01:39 +0000846 Table *pTab,
dandfa552f2018-06-02 21:04:28 +0000847 ExprList **ppSub /* IN/OUT: Sub-select expression-list */
848){
849 Walker sWalker;
850 WindowRewrite sRewrite;
dandfa552f2018-06-02 21:04:28 +0000851
drh55f66b32019-07-16 19:44:32 +0000852 assert( pWin!=0 );
dandfa552f2018-06-02 21:04:28 +0000853 memset(&sWalker, 0, sizeof(Walker));
854 memset(&sRewrite, 0, sizeof(WindowRewrite));
855
856 sRewrite.pSub = *ppSub;
857 sRewrite.pWin = pWin;
danb556f262018-07-10 17:26:12 +0000858 sRewrite.pSrc = pSrc;
dan62742fd2019-07-08 12:01:39 +0000859 sRewrite.pTab = pTab;
dandfa552f2018-06-02 21:04:28 +0000860
861 sWalker.pParse = pParse;
862 sWalker.xExprCallback = selectWindowRewriteExprCb;
863 sWalker.xSelectCallback = selectWindowRewriteSelectCb;
864 sWalker.u.pRewrite = &sRewrite;
865
dan13b08bb2018-06-15 20:46:12 +0000866 (void)sqlite3WalkExprList(&sWalker, pEList);
dandfa552f2018-06-02 21:04:28 +0000867
868 *ppSub = sRewrite.pSub;
dandfa552f2018-06-02 21:04:28 +0000869}
870
danc0bb4452018-06-12 20:53:38 +0000871/*
872** Append a copy of each expression in expression-list pAppend to
873** expression list pList. Return a pointer to the result list.
874*/
dandfa552f2018-06-02 21:04:28 +0000875static ExprList *exprListAppendList(
876 Parse *pParse, /* Parsing context */
877 ExprList *pList, /* List to which to append. Might be NULL */
dan08f6de72019-05-10 14:26:32 +0000878 ExprList *pAppend, /* List of values to append. Might be NULL */
879 int bIntToNull
dandfa552f2018-06-02 21:04:28 +0000880){
881 if( pAppend ){
882 int i;
883 int nInit = pList ? pList->nExpr : 0;
884 for(i=0; i<pAppend->nExpr; i++){
885 Expr *pDup = sqlite3ExprDup(pParse->db, pAppend->a[i].pExpr, 0);
dan08f6de72019-05-10 14:26:32 +0000886 if( bIntToNull && pDup && pDup->op==TK_INTEGER ){
887 pDup->op = TK_NULL;
888 pDup->flags &= ~(EP_IntValue|EP_IsTrue|EP_IsFalse);
889 }
dandfa552f2018-06-02 21:04:28 +0000890 pList = sqlite3ExprListAppend(pParse, pList, pDup);
dan6e118922019-08-12 16:36:38 +0000891 if( pList ) pList->a[nInit+i].sortFlags = pAppend->a[i].sortFlags;
dandfa552f2018-06-02 21:04:28 +0000892 }
893 }
894 return pList;
895}
896
897/*
898** If the SELECT statement passed as the second argument does not invoke
899** any SQL window functions, this function is a no-op. Otherwise, it
900** rewrites the SELECT statement so that window function xStep functions
danc0bb4452018-06-12 20:53:38 +0000901** are invoked in the correct order as described under "SELECT REWRITING"
902** at the top of this file.
dandfa552f2018-06-02 21:04:28 +0000903*/
904int sqlite3WindowRewrite(Parse *pParse, Select *p){
905 int rc = SQLITE_OK;
dan0f5f5402018-10-23 13:48:19 +0000906 if( p->pWin && p->pPrior==0 ){
dandfa552f2018-06-02 21:04:28 +0000907 Vdbe *v = sqlite3GetVdbe(pParse);
dandfa552f2018-06-02 21:04:28 +0000908 sqlite3 *db = pParse->db;
909 Select *pSub = 0; /* The subquery */
910 SrcList *pSrc = p->pSrc;
911 Expr *pWhere = p->pWhere;
912 ExprList *pGroupBy = p->pGroupBy;
913 Expr *pHaving = p->pHaving;
914 ExprList *pSort = 0;
915
916 ExprList *pSublist = 0; /* Expression list for sub-query */
917 Window *pMWin = p->pWin; /* Master window object */
918 Window *pWin; /* Window object iterator */
dan62742fd2019-07-08 12:01:39 +0000919 Table *pTab;
920
921 pTab = sqlite3DbMallocZero(db, sizeof(Table));
922 if( pTab==0 ){
923 return SQLITE_NOMEM;
924 }
dandfa552f2018-06-02 21:04:28 +0000925
926 p->pSrc = 0;
927 p->pWhere = 0;
928 p->pGroupBy = 0;
929 p->pHaving = 0;
dan62742fd2019-07-08 12:01:39 +0000930 p->selFlags &= ~SF_Aggregate;
dandfa552f2018-06-02 21:04:28 +0000931
danf02cdd32018-06-27 19:48:50 +0000932 /* Create the ORDER BY clause for the sub-select. This is the concatenation
933 ** of the window PARTITION and ORDER BY clauses. Then, if this makes it
934 ** redundant, remove the ORDER BY from the parent SELECT. */
935 pSort = sqlite3ExprListDup(db, pMWin->pPartition, 0);
dan08f6de72019-05-10 14:26:32 +0000936 pSort = exprListAppendList(pParse, pSort, pMWin->pOrderBy, 1);
dan0e3c50c2019-08-07 17:45:37 +0000937 if( pSort && p->pOrderBy && p->pOrderBy->nExpr<=pSort->nExpr ){
938 int nSave = pSort->nExpr;
939 pSort->nExpr = p->pOrderBy->nExpr;
danf02cdd32018-06-27 19:48:50 +0000940 if( sqlite3ExprListCompare(pSort, p->pOrderBy, -1)==0 ){
941 sqlite3ExprListDelete(db, p->pOrderBy);
942 p->pOrderBy = 0;
943 }
dan0e3c50c2019-08-07 17:45:37 +0000944 pSort->nExpr = nSave;
danf02cdd32018-06-27 19:48:50 +0000945 }
946
dandfa552f2018-06-02 21:04:28 +0000947 /* Assign a cursor number for the ephemeral table used to buffer rows.
948 ** The OpenEphemeral instruction is coded later, after it is known how
949 ** many columns the table will have. */
950 pMWin->iEphCsr = pParse->nTab++;
dan680f6e82019-03-04 21:07:11 +0000951 pParse->nTab += 3;
dandfa552f2018-06-02 21:04:28 +0000952
dan62742fd2019-07-08 12:01:39 +0000953 selectWindowRewriteEList(pParse, pMWin, pSrc, p->pEList, pTab, &pSublist);
954 selectWindowRewriteEList(pParse, pMWin, pSrc, p->pOrderBy, pTab, &pSublist);
dandfa552f2018-06-02 21:04:28 +0000955 pMWin->nBufferCol = (pSublist ? pSublist->nExpr : 0);
956
danf02cdd32018-06-27 19:48:50 +0000957 /* Append the PARTITION BY and ORDER BY expressions to the to the
958 ** sub-select expression list. They are required to figure out where
959 ** boundaries for partitions and sets of peer rows lie. */
dan08f6de72019-05-10 14:26:32 +0000960 pSublist = exprListAppendList(pParse, pSublist, pMWin->pPartition, 0);
961 pSublist = exprListAppendList(pParse, pSublist, pMWin->pOrderBy, 0);
dandfa552f2018-06-02 21:04:28 +0000962
963 /* Append the arguments passed to each window function to the
964 ** sub-select expression list. Also allocate two registers for each
965 ** window function - one for the accumulator, another for interim
966 ** results. */
967 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
968 pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);
dan08f6de72019-05-10 14:26:32 +0000969 pSublist = exprListAppendList(pParse, pSublist, pWin->pOwner->x.pList, 0);
dan8b985602018-06-09 17:43:45 +0000970 if( pWin->pFilter ){
971 Expr *pFilter = sqlite3ExprDup(db, pWin->pFilter, 0);
972 pSublist = sqlite3ExprListAppend(pParse, pSublist, pFilter);
973 }
dandfa552f2018-06-02 21:04:28 +0000974 pWin->regAccum = ++pParse->nMem;
975 pWin->regResult = ++pParse->nMem;
976 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
977 }
978
dan9c277582018-06-20 09:23:49 +0000979 /* If there is no ORDER BY or PARTITION BY clause, and the window
980 ** function accepts zero arguments, and there are no other columns
981 ** selected (e.g. "SELECT row_number() OVER () FROM t1"), it is possible
982 ** that pSublist is still NULL here. Add a constant expression here to
983 ** keep everything legal in this case.
984 */
985 if( pSublist==0 ){
986 pSublist = sqlite3ExprListAppend(pParse, 0,
987 sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0)
988 );
989 }
990
dandfa552f2018-06-02 21:04:28 +0000991 pSub = sqlite3SelectNew(
992 pParse, pSublist, pSrc, pWhere, pGroupBy, pHaving, pSort, 0, 0
993 );
drh29c992c2019-01-17 15:40:41 +0000994 p->pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
dandfa552f2018-06-02 21:04:28 +0000995 if( p->pSrc ){
dan62742fd2019-07-08 12:01:39 +0000996 Table *pTab2;
dandfa552f2018-06-02 21:04:28 +0000997 p->pSrc->a[0].pSelect = pSub;
998 sqlite3SrcListAssignCursors(pParse, p->pSrc);
dan62742fd2019-07-08 12:01:39 +0000999 pSub->selFlags |= SF_Expanded;
drh96fb16e2019-08-06 14:37:24 +00001000 pTab2 = sqlite3ResultSetOfSelect(pParse, pSub, SQLITE_AFF_NONE);
dan62742fd2019-07-08 12:01:39 +00001001 if( pTab2==0 ){
dandfa552f2018-06-02 21:04:28 +00001002 rc = SQLITE_NOMEM;
1003 }else{
dan62742fd2019-07-08 12:01:39 +00001004 memcpy(pTab, pTab2, sizeof(Table));
1005 pTab->tabFlags |= TF_Ephemeral;
1006 p->pSrc->a[0].pTab = pTab;
1007 pTab = pTab2;
dandfa552f2018-06-02 21:04:28 +00001008 }
dan6fde1792018-06-15 19:01:35 +00001009 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pMWin->iEphCsr, pSublist->nExpr);
dan680f6e82019-03-04 21:07:11 +00001010 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+1, pMWin->iEphCsr);
1011 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+2, pMWin->iEphCsr);
1012 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+3, pMWin->iEphCsr);
dan6fde1792018-06-15 19:01:35 +00001013 }else{
1014 sqlite3SelectDelete(db, pSub);
1015 }
1016 if( db->mallocFailed ) rc = SQLITE_NOMEM;
dan62742fd2019-07-08 12:01:39 +00001017 sqlite3DbFree(db, pTab);
dandfa552f2018-06-02 21:04:28 +00001018 }
1019
1020 return rc;
1021}
1022
danc0bb4452018-06-12 20:53:38 +00001023/*
drhe2094572019-07-22 19:01:38 +00001024** Unlink the Window object from the Select to which it is attached,
1025** if it is attached.
1026*/
1027void sqlite3WindowUnlinkFromSelect(Window *p){
1028 if( p->ppThis ){
1029 *p->ppThis = p->pNextWin;
1030 if( p->pNextWin ) p->pNextWin->ppThis = p->ppThis;
1031 p->ppThis = 0;
1032 }
1033}
1034
1035/*
danc0bb4452018-06-12 20:53:38 +00001036** Free the Window object passed as the second argument.
1037*/
dan86fb6e12018-05-16 20:58:07 +00001038void sqlite3WindowDelete(sqlite3 *db, Window *p){
1039 if( p ){
drhe2094572019-07-22 19:01:38 +00001040 sqlite3WindowUnlinkFromSelect(p);
dan86fb6e12018-05-16 20:58:07 +00001041 sqlite3ExprDelete(db, p->pFilter);
1042 sqlite3ExprListDelete(db, p->pPartition);
1043 sqlite3ExprListDelete(db, p->pOrderBy);
1044 sqlite3ExprDelete(db, p->pEnd);
1045 sqlite3ExprDelete(db, p->pStart);
dane3bf6322018-06-08 20:58:27 +00001046 sqlite3DbFree(db, p->zName);
dane7c9ca42019-02-16 17:27:51 +00001047 sqlite3DbFree(db, p->zBase);
dan86fb6e12018-05-16 20:58:07 +00001048 sqlite3DbFree(db, p);
1049 }
1050}
1051
danc0bb4452018-06-12 20:53:38 +00001052/*
1053** Free the linked list of Window objects starting at the second argument.
1054*/
dane3bf6322018-06-08 20:58:27 +00001055void sqlite3WindowListDelete(sqlite3 *db, Window *p){
1056 while( p ){
1057 Window *pNext = p->pNextWin;
1058 sqlite3WindowDelete(db, p);
1059 p = pNext;
1060 }
1061}
1062
danc0bb4452018-06-12 20:53:38 +00001063/*
drhe4984a22018-07-06 17:19:20 +00001064** The argument expression is an PRECEDING or FOLLOWING offset. The
1065** value should be a non-negative integer. If the value is not a
1066** constant, change it to NULL. The fact that it is then a non-negative
1067** integer will be caught later. But it is important not to leave
1068** variable values in the expression tree.
1069*/
1070static Expr *sqlite3WindowOffsetExpr(Parse *pParse, Expr *pExpr){
1071 if( 0==sqlite3ExprIsConstant(pExpr) ){
danfb8ac322019-01-16 12:05:22 +00001072 if( IN_RENAME_OBJECT ) sqlite3RenameExprUnmap(pParse, pExpr);
drhe4984a22018-07-06 17:19:20 +00001073 sqlite3ExprDelete(pParse->db, pExpr);
1074 pExpr = sqlite3ExprAlloc(pParse->db, TK_NULL, 0, 0);
1075 }
1076 return pExpr;
1077}
1078
1079/*
1080** Allocate and return a new Window object describing a Window Definition.
danc0bb4452018-06-12 20:53:38 +00001081*/
dan86fb6e12018-05-16 20:58:07 +00001082Window *sqlite3WindowAlloc(
drhe4984a22018-07-06 17:19:20 +00001083 Parse *pParse, /* Parsing context */
drhfc15f4c2019-03-28 13:03:41 +00001084 int eType, /* Frame type. TK_RANGE, TK_ROWS, TK_GROUPS, or 0 */
drhe4984a22018-07-06 17:19:20 +00001085 int eStart, /* Start type: CURRENT, PRECEDING, FOLLOWING, UNBOUNDED */
1086 Expr *pStart, /* Start window size if TK_PRECEDING or FOLLOWING */
1087 int eEnd, /* End type: CURRENT, FOLLOWING, TK_UNBOUNDED, PRECEDING */
dand35300f2019-03-14 20:53:21 +00001088 Expr *pEnd, /* End window size if TK_FOLLOWING or PRECEDING */
1089 u8 eExclude /* EXCLUDE clause */
dan86fb6e12018-05-16 20:58:07 +00001090){
dan7a606e12018-07-05 18:34:53 +00001091 Window *pWin = 0;
dane7c9ca42019-02-16 17:27:51 +00001092 int bImplicitFrame = 0;
dan7a606e12018-07-05 18:34:53 +00001093
drhe4984a22018-07-06 17:19:20 +00001094 /* Parser assures the following: */
dan6c75b392019-03-08 20:02:52 +00001095 assert( eType==0 || eType==TK_RANGE || eType==TK_ROWS || eType==TK_GROUPS );
drhe4984a22018-07-06 17:19:20 +00001096 assert( eStart==TK_CURRENT || eStart==TK_PRECEDING
1097 || eStart==TK_UNBOUNDED || eStart==TK_FOLLOWING );
1098 assert( eEnd==TK_CURRENT || eEnd==TK_FOLLOWING
1099 || eEnd==TK_UNBOUNDED || eEnd==TK_PRECEDING );
1100 assert( (eStart==TK_PRECEDING || eStart==TK_FOLLOWING)==(pStart!=0) );
1101 assert( (eEnd==TK_FOLLOWING || eEnd==TK_PRECEDING)==(pEnd!=0) );
1102
dane7c9ca42019-02-16 17:27:51 +00001103 if( eType==0 ){
1104 bImplicitFrame = 1;
1105 eType = TK_RANGE;
1106 }
drhe4984a22018-07-06 17:19:20 +00001107
drhe4984a22018-07-06 17:19:20 +00001108 /* Additionally, the
dan5d764ac2018-07-06 14:15:49 +00001109 ** starting boundary type may not occur earlier in the following list than
1110 ** the ending boundary type:
1111 **
1112 ** UNBOUNDED PRECEDING
1113 ** <expr> PRECEDING
1114 ** CURRENT ROW
1115 ** <expr> FOLLOWING
1116 ** UNBOUNDED FOLLOWING
1117 **
1118 ** The parser ensures that "UNBOUNDED PRECEDING" cannot be used as an ending
1119 ** boundary, and than "UNBOUNDED FOLLOWING" cannot be used as a starting
1120 ** frame boundary.
1121 */
drhe4984a22018-07-06 17:19:20 +00001122 if( (eStart==TK_CURRENT && eEnd==TK_PRECEDING)
dan5d764ac2018-07-06 14:15:49 +00001123 || (eStart==TK_FOLLOWING && (eEnd==TK_PRECEDING || eEnd==TK_CURRENT))
1124 ){
dan72b9fdc2019-03-09 20:49:17 +00001125 sqlite3ErrorMsg(pParse, "unsupported frame specification");
drhe4984a22018-07-06 17:19:20 +00001126 goto windowAllocErr;
dan7a606e12018-07-05 18:34:53 +00001127 }
dan86fb6e12018-05-16 20:58:07 +00001128
drhe4984a22018-07-06 17:19:20 +00001129 pWin = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
1130 if( pWin==0 ) goto windowAllocErr;
drhfc15f4c2019-03-28 13:03:41 +00001131 pWin->eFrmType = eType;
drhe4984a22018-07-06 17:19:20 +00001132 pWin->eStart = eStart;
1133 pWin->eEnd = eEnd;
drh94809082019-04-02 17:45:56 +00001134 if( eExclude==0 && OptimizationDisabled(pParse->db, SQLITE_WindowFunc) ){
dan108e6b22019-03-18 18:55:35 +00001135 eExclude = TK_NO;
1136 }
dand35300f2019-03-14 20:53:21 +00001137 pWin->eExclude = eExclude;
dane7c9ca42019-02-16 17:27:51 +00001138 pWin->bImplicitFrame = bImplicitFrame;
drhe4984a22018-07-06 17:19:20 +00001139 pWin->pEnd = sqlite3WindowOffsetExpr(pParse, pEnd);
1140 pWin->pStart = sqlite3WindowOffsetExpr(pParse, pStart);
dan86fb6e12018-05-16 20:58:07 +00001141 return pWin;
drhe4984a22018-07-06 17:19:20 +00001142
1143windowAllocErr:
1144 sqlite3ExprDelete(pParse->db, pEnd);
1145 sqlite3ExprDelete(pParse->db, pStart);
1146 return 0;
dan86fb6e12018-05-16 20:58:07 +00001147}
1148
danc0bb4452018-06-12 20:53:38 +00001149/*
dane7c9ca42019-02-16 17:27:51 +00001150** Attach PARTITION and ORDER BY clauses pPartition and pOrderBy to window
1151** pWin. Also, if parameter pBase is not NULL, set pWin->zBase to the
1152** equivalent nul-terminated string.
1153*/
1154Window *sqlite3WindowAssemble(
1155 Parse *pParse,
1156 Window *pWin,
1157 ExprList *pPartition,
1158 ExprList *pOrderBy,
1159 Token *pBase
1160){
1161 if( pWin ){
1162 pWin->pPartition = pPartition;
1163 pWin->pOrderBy = pOrderBy;
1164 if( pBase ){
1165 pWin->zBase = sqlite3DbStrNDup(pParse->db, pBase->z, pBase->n);
1166 }
1167 }else{
1168 sqlite3ExprListDelete(pParse->db, pPartition);
1169 sqlite3ExprListDelete(pParse->db, pOrderBy);
1170 }
1171 return pWin;
1172}
1173
1174/*
1175** Window *pWin has just been created from a WINDOW clause. Tokne pBase
1176** is the base window. Earlier windows from the same WINDOW clause are
1177** stored in the linked list starting at pWin->pNextWin. This function
1178** either updates *pWin according to the base specification, or else
1179** leaves an error in pParse.
1180*/
1181void sqlite3WindowChain(Parse *pParse, Window *pWin, Window *pList){
1182 if( pWin->zBase ){
1183 sqlite3 *db = pParse->db;
1184 Window *pExist = windowFind(pParse, pList, pWin->zBase);
1185 if( pExist ){
1186 const char *zErr = 0;
1187 /* Check for errors */
1188 if( pWin->pPartition ){
1189 zErr = "PARTITION clause";
1190 }else if( pExist->pOrderBy && pWin->pOrderBy ){
1191 zErr = "ORDER BY clause";
1192 }else if( pExist->bImplicitFrame==0 ){
1193 zErr = "frame specification";
1194 }
1195 if( zErr ){
1196 sqlite3ErrorMsg(pParse,
1197 "cannot override %s of window: %s", zErr, pWin->zBase
1198 );
1199 }else{
1200 pWin->pPartition = sqlite3ExprListDup(db, pExist->pPartition, 0);
1201 if( pExist->pOrderBy ){
1202 assert( pWin->pOrderBy==0 );
1203 pWin->pOrderBy = sqlite3ExprListDup(db, pExist->pOrderBy, 0);
1204 }
1205 sqlite3DbFree(db, pWin->zBase);
1206 pWin->zBase = 0;
1207 }
1208 }
1209 }
1210}
1211
1212/*
danc0bb4452018-06-12 20:53:38 +00001213** Attach window object pWin to expression p.
1214*/
dan4f9adee2019-07-13 16:22:50 +00001215void sqlite3WindowAttach(Parse *pParse, Expr *p, Window *pWin){
dan86fb6e12018-05-16 20:58:07 +00001216 if( p ){
drheda079c2018-09-20 19:02:15 +00001217 assert( p->op==TK_FUNCTION );
dan4f9adee2019-07-13 16:22:50 +00001218 assert( pWin );
1219 p->y.pWin = pWin;
1220 ExprSetProperty(p, EP_WinFunc);
1221 pWin->pOwner = p;
1222 if( (p->flags & EP_Distinct) && pWin->eFrmType!=TK_FILTER ){
1223 sqlite3ErrorMsg(pParse,
1224 "DISTINCT is not supported for window functions"
1225 );
dane33f6e72018-07-06 07:42:42 +00001226 }
dan86fb6e12018-05-16 20:58:07 +00001227 }else{
1228 sqlite3WindowDelete(pParse->db, pWin);
1229 }
1230}
dane2f781b2018-05-17 19:24:08 +00001231
1232/*
dana3fcc002019-08-15 13:53:22 +00001233** Possibly link window pWin into the list at pSel->pWin (window functions
1234** to be processed as part of SELECT statement pSel). The window is linked
1235** in if either (a) there are no other windows already linked to this
1236** SELECT, or (b) the windows already linked use a compatible window frame.
1237*/
1238void sqlite3WindowLink(Select *pSel, Window *pWin){
1239 if( 0==pSel->pWin
1240 || 0==sqlite3WindowCompare(0, pSel->pWin, pWin, 0)
1241 ){
1242 pWin->pNextWin = pSel->pWin;
1243 if( pSel->pWin ){
1244 pSel->pWin->ppThis = &pWin->pNextWin;
1245 }
1246 pSel->pWin = pWin;
1247 pWin->ppThis = &pSel->pWin;
1248 }
1249}
1250
1251/*
dane2f781b2018-05-17 19:24:08 +00001252** Return 0 if the two window objects are identical, or non-zero otherwise.
dan13078ca2018-06-13 20:29:38 +00001253** Identical window objects can be processed in a single scan.
dane2f781b2018-05-17 19:24:08 +00001254*/
dan4f9adee2019-07-13 16:22:50 +00001255int sqlite3WindowCompare(Parse *pParse, Window *p1, Window *p2, int bFilter){
drhfc15f4c2019-03-28 13:03:41 +00001256 if( p1->eFrmType!=p2->eFrmType ) return 1;
dane2f781b2018-05-17 19:24:08 +00001257 if( p1->eStart!=p2->eStart ) return 1;
1258 if( p1->eEnd!=p2->eEnd ) return 1;
dana0f6b832019-03-14 16:36:20 +00001259 if( p1->eExclude!=p2->eExclude ) return 1;
dane2f781b2018-05-17 19:24:08 +00001260 if( sqlite3ExprCompare(pParse, p1->pStart, p2->pStart, -1) ) return 1;
1261 if( sqlite3ExprCompare(pParse, p1->pEnd, p2->pEnd, -1) ) return 1;
1262 if( sqlite3ExprListCompare(p1->pPartition, p2->pPartition, -1) ) return 1;
1263 if( sqlite3ExprListCompare(p1->pOrderBy, p2->pOrderBy, -1) ) return 1;
dan4f9adee2019-07-13 16:22:50 +00001264 if( bFilter ){
1265 if( sqlite3ExprCompare(pParse, p1->pFilter, p2->pFilter, -1) ) return 1;
1266 }
dane2f781b2018-05-17 19:24:08 +00001267 return 0;
1268}
1269
dan13078ca2018-06-13 20:29:38 +00001270
1271/*
1272** This is called by code in select.c before it calls sqlite3WhereBegin()
1273** to begin iterating through the sub-query results. It is used to allocate
1274** and initialize registers and cursors used by sqlite3WindowCodeStep().
1275*/
1276void sqlite3WindowCodeInit(Parse *pParse, Window *pMWin){
danc9a86682018-05-30 20:44:58 +00001277 Window *pWin;
dan13078ca2018-06-13 20:29:38 +00001278 Vdbe *v = sqlite3GetVdbe(pParse);
danb6f2dea2019-03-13 17:20:27 +00001279
1280 /* Allocate registers to use for PARTITION BY values, if any. Initialize
1281 ** said registers to NULL. */
1282 if( pMWin->pPartition ){
1283 int nExpr = pMWin->pPartition->nExpr;
dan13078ca2018-06-13 20:29:38 +00001284 pMWin->regPart = pParse->nMem+1;
danb6f2dea2019-03-13 17:20:27 +00001285 pParse->nMem += nExpr;
1286 sqlite3VdbeAddOp3(v, OP_Null, 0, pMWin->regPart, pMWin->regPart+nExpr-1);
dan13078ca2018-06-13 20:29:38 +00001287 }
1288
danbf845152019-03-16 10:15:24 +00001289 pMWin->regOne = ++pParse->nMem;
1290 sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regOne);
dan680f6e82019-03-04 21:07:11 +00001291
dana0f6b832019-03-14 16:36:20 +00001292 if( pMWin->eExclude ){
1293 pMWin->regStartRowid = ++pParse->nMem;
1294 pMWin->regEndRowid = ++pParse->nMem;
1295 pMWin->csrApp = pParse->nTab++;
1296 sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid);
1297 sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid);
1298 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->csrApp, pMWin->iEphCsr);
1299 return;
1300 }
1301
danc9a86682018-05-30 20:44:58 +00001302 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
danec891fd2018-06-06 20:51:02 +00001303 FuncDef *p = pWin->pFunc;
1304 if( (p->funcFlags & SQLITE_FUNC_MINMAX) && pWin->eStart!=TK_UNBOUNDED ){
dan9a947222018-06-14 19:06:36 +00001305 /* The inline versions of min() and max() require a single ephemeral
1306 ** table and 3 registers. The registers are used as follows:
1307 **
1308 ** regApp+0: slot to copy min()/max() argument to for MakeRecord
1309 ** regApp+1: integer value used to ensure keys are unique
1310 ** regApp+2: output of MakeRecord
1311 */
danc9a86682018-05-30 20:44:58 +00001312 ExprList *pList = pWin->pOwner->x.pList;
1313 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pList, 0, 0);
danc9a86682018-05-30 20:44:58 +00001314 pWin->csrApp = pParse->nTab++;
1315 pWin->regApp = pParse->nMem+1;
1316 pParse->nMem += 3;
1317 if( pKeyInfo && pWin->pFunc->zName[1]=='i' ){
dan6e118922019-08-12 16:36:38 +00001318 assert( pKeyInfo->aSortFlags[0]==0 );
1319 pKeyInfo->aSortFlags[0] = KEYINFO_ORDER_DESC;
danc9a86682018-05-30 20:44:58 +00001320 }
1321 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pWin->csrApp, 2);
1322 sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
1323 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
1324 }
drh19dc4d42018-07-08 01:02:26 +00001325 else if( p->zName==nth_valueName || p->zName==first_valueName ){
danec891fd2018-06-06 20:51:02 +00001326 /* Allocate two registers at pWin->regApp. These will be used to
1327 ** store the start and end index of the current frame. */
danec891fd2018-06-06 20:51:02 +00001328 pWin->regApp = pParse->nMem+1;
1329 pWin->csrApp = pParse->nTab++;
1330 pParse->nMem += 2;
danec891fd2018-06-06 20:51:02 +00001331 sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
1332 }
drh19dc4d42018-07-08 01:02:26 +00001333 else if( p->zName==leadName || p->zName==lagName ){
danfe4e25a2018-06-07 20:08:59 +00001334 pWin->csrApp = pParse->nTab++;
1335 sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
1336 }
danc9a86682018-05-30 20:44:58 +00001337 }
1338}
1339
danbb407272019-03-12 18:28:51 +00001340#define WINDOW_STARTING_INT 0
1341#define WINDOW_ENDING_INT 1
1342#define WINDOW_NTH_VALUE_INT 2
1343#define WINDOW_STARTING_NUM 3
1344#define WINDOW_ENDING_NUM 4
1345
dan13078ca2018-06-13 20:29:38 +00001346/*
dana1a7e112018-07-09 13:31:18 +00001347** A "PRECEDING <expr>" (eCond==0) or "FOLLOWING <expr>" (eCond==1) or the
1348** value of the second argument to nth_value() (eCond==2) has just been
1349** evaluated and the result left in register reg. This function generates VM
1350** code to check that the value is a non-negative integer and throws an
1351** exception if it is not.
dan13078ca2018-06-13 20:29:38 +00001352*/
danbb407272019-03-12 18:28:51 +00001353static void windowCheckValue(Parse *pParse, int reg, int eCond){
danc3a20c12018-05-23 20:55:37 +00001354 static const char *azErr[] = {
1355 "frame starting offset must be a non-negative integer",
dana1a7e112018-07-09 13:31:18 +00001356 "frame ending offset must be a non-negative integer",
danbb407272019-03-12 18:28:51 +00001357 "second argument to nth_value must be a positive integer",
1358 "frame starting offset must be a non-negative number",
1359 "frame ending offset must be a non-negative number",
danc3a20c12018-05-23 20:55:37 +00001360 };
danbb407272019-03-12 18:28:51 +00001361 static int aOp[] = { OP_Ge, OP_Ge, OP_Gt, OP_Ge, OP_Ge };
danc3a20c12018-05-23 20:55:37 +00001362 Vdbe *v = sqlite3GetVdbe(pParse);
dan13078ca2018-06-13 20:29:38 +00001363 int regZero = sqlite3GetTempReg(pParse);
danbb407272019-03-12 18:28:51 +00001364 assert( eCond>=0 && eCond<ArraySize(azErr) );
danc3a20c12018-05-23 20:55:37 +00001365 sqlite3VdbeAddOp2(v, OP_Integer, 0, regZero);
dane5166e02019-03-19 11:56:39 +00001366 if( eCond>=WINDOW_STARTING_NUM ){
1367 int regString = sqlite3GetTempReg(pParse);
1368 sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC);
1369 sqlite3VdbeAddOp3(v, OP_Ge, regString, sqlite3VdbeCurrentAddr(v)+2, reg);
drh21826f42019-04-01 14:30:30 +00001370 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC|SQLITE_JUMPIFNULL);
drh6f883592019-03-30 20:37:04 +00001371 VdbeCoverage(v);
1372 assert( eCond==3 || eCond==4 );
1373 VdbeCoverageIf(v, eCond==3);
1374 VdbeCoverageIf(v, eCond==4);
dane5166e02019-03-19 11:56:39 +00001375 }else{
1376 sqlite3VdbeAddOp2(v, OP_MustBeInt, reg, sqlite3VdbeCurrentAddr(v)+2);
drh6f883592019-03-30 20:37:04 +00001377 VdbeCoverage(v);
1378 assert( eCond==0 || eCond==1 || eCond==2 );
1379 VdbeCoverageIf(v, eCond==0);
1380 VdbeCoverageIf(v, eCond==1);
1381 VdbeCoverageIf(v, eCond==2);
dane5166e02019-03-19 11:56:39 +00001382 }
dana1a7e112018-07-09 13:31:18 +00001383 sqlite3VdbeAddOp3(v, aOp[eCond], regZero, sqlite3VdbeCurrentAddr(v)+2, reg);
drh21826f42019-04-01 14:30:30 +00001384 VdbeCoverageNeverNullIf(v, eCond==0); /* NULL case captured by */
1385 VdbeCoverageNeverNullIf(v, eCond==1); /* the OP_MustBeInt */
1386 VdbeCoverageNeverNullIf(v, eCond==2);
1387 VdbeCoverageNeverNullIf(v, eCond==3); /* NULL case caught by */
1388 VdbeCoverageNeverNullIf(v, eCond==4); /* the OP_Ge */
drh211a0852019-01-27 02:41:34 +00001389 sqlite3MayAbort(pParse);
danc3a20c12018-05-23 20:55:37 +00001390 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_ERROR, OE_Abort);
dana1a7e112018-07-09 13:31:18 +00001391 sqlite3VdbeAppendP4(v, (void*)azErr[eCond], P4_STATIC);
dan13078ca2018-06-13 20:29:38 +00001392 sqlite3ReleaseTempReg(pParse, regZero);
danc3a20c12018-05-23 20:55:37 +00001393}
1394
dan13078ca2018-06-13 20:29:38 +00001395/*
1396** Return the number of arguments passed to the window-function associated
1397** with the object passed as the only argument to this function.
1398*/
dan2a11bb22018-06-11 20:50:25 +00001399static int windowArgCount(Window *pWin){
1400 ExprList *pList = pWin->pOwner->x.pList;
1401 return (pList ? pList->nExpr : 0);
1402}
1403
danc9a86682018-05-30 20:44:58 +00001404/*
1405** Generate VM code to invoke either xStep() (if bInverse is 0) or
1406** xInverse (if bInverse is non-zero) for each window function in the
dan13078ca2018-06-13 20:29:38 +00001407** linked list starting at pMWin. Or, for built-in window functions
1408** that do not use the standard function API, generate the required
1409** inline VM code.
1410**
1411** If argument csr is greater than or equal to 0, then argument reg is
1412** the first register in an array of registers guaranteed to be large
1413** enough to hold the array of arguments for each function. In this case
1414** the arguments are extracted from the current row of csr into the
drh8f26da62018-07-05 21:22:57 +00001415** array of registers before invoking OP_AggStep or OP_AggInverse
dan13078ca2018-06-13 20:29:38 +00001416**
1417** Or, if csr is less than zero, then the array of registers at reg is
1418** already populated with all columns from the current row of the sub-query.
1419**
1420** If argument regPartSize is non-zero, then it is a register containing the
1421** number of rows in the current partition.
danc9a86682018-05-30 20:44:58 +00001422*/
dan31f56392018-05-24 21:10:57 +00001423static void windowAggStep(
1424 Parse *pParse,
dan13078ca2018-06-13 20:29:38 +00001425 Window *pMWin, /* Linked list of window functions */
1426 int csr, /* Read arguments from this cursor */
1427 int bInverse, /* True to invoke xInverse instead of xStep */
dana0f6b832019-03-14 16:36:20 +00001428 int reg /* Array of registers */
dan31f56392018-05-24 21:10:57 +00001429){
1430 Vdbe *v = sqlite3GetVdbe(pParse);
1431 Window *pWin;
1432 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
dana0f6b832019-03-14 16:36:20 +00001433 FuncDef *pFunc = pWin->pFunc;
danc9a86682018-05-30 20:44:58 +00001434 int regArg;
dan2a11bb22018-06-11 20:50:25 +00001435 int nArg = windowArgCount(pWin);
dana0f6b832019-03-14 16:36:20 +00001436 int i;
dandfa552f2018-06-02 21:04:28 +00001437
dana3fcc002019-08-15 13:53:22 +00001438 assert( bInverse==0 || pWin->eStart!=TK_UNBOUNDED );
1439
dana0f6b832019-03-14 16:36:20 +00001440 for(i=0; i<nArg; i++){
danc782a812019-03-15 20:46:19 +00001441 if( i!=1 || pFunc->zName!=nth_valueName ){
1442 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+i, reg+i);
1443 }else{
1444 sqlite3VdbeAddOp3(v, OP_Column, pMWin->iEphCsr, pWin->iArgCol+i, reg+i);
1445 }
dan31f56392018-05-24 21:10:57 +00001446 }
dana0f6b832019-03-14 16:36:20 +00001447 regArg = reg;
danc9a86682018-05-30 20:44:58 +00001448
dana0f6b832019-03-14 16:36:20 +00001449 if( pMWin->regStartRowid==0
1450 && (pFunc->funcFlags & SQLITE_FUNC_MINMAX)
1451 && (pWin->eStart!=TK_UNBOUNDED)
danec891fd2018-06-06 20:51:02 +00001452 ){
dand4fc49f2018-07-07 17:30:44 +00001453 int addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regArg);
1454 VdbeCoverage(v);
danc9a86682018-05-30 20:44:58 +00001455 if( bInverse==0 ){
1456 sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1, 1);
1457 sqlite3VdbeAddOp2(v, OP_SCopy, regArg, pWin->regApp);
1458 sqlite3VdbeAddOp3(v, OP_MakeRecord, pWin->regApp, 2, pWin->regApp+2);
1459 sqlite3VdbeAddOp2(v, OP_IdxInsert, pWin->csrApp, pWin->regApp+2);
1460 }else{
1461 sqlite3VdbeAddOp4Int(v, OP_SeekGE, pWin->csrApp, 0, regArg, 1);
drh93419162018-07-11 03:27:52 +00001462 VdbeCoverageNeverTaken(v);
danc9a86682018-05-30 20:44:58 +00001463 sqlite3VdbeAddOp1(v, OP_Delete, pWin->csrApp);
1464 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
1465 }
dand4fc49f2018-07-07 17:30:44 +00001466 sqlite3VdbeJumpHere(v, addrIsNull);
danec891fd2018-06-06 20:51:02 +00001467 }else if( pWin->regApp ){
dana0f6b832019-03-14 16:36:20 +00001468 assert( pFunc->zName==nth_valueName
1469 || pFunc->zName==first_valueName
dan7095c002018-06-07 17:45:22 +00001470 );
danec891fd2018-06-06 20:51:02 +00001471 assert( bInverse==0 || bInverse==1 );
1472 sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1-bInverse, 1);
dana0f6b832019-03-14 16:36:20 +00001473 }else if( pFunc->xSFunc!=noopStepFunc ){
dan8b985602018-06-09 17:43:45 +00001474 int addrIf = 0;
1475 if( pWin->pFilter ){
1476 int regTmp;
danf5e8e312018-07-09 06:51:36 +00001477 assert( nArg==0 || nArg==pWin->pOwner->x.pList->nExpr );
1478 assert( nArg || pWin->pOwner->x.pList==0 );
dana0f6b832019-03-14 16:36:20 +00001479 regTmp = sqlite3GetTempReg(pParse);
1480 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+nArg,regTmp);
dan8b985602018-06-09 17:43:45 +00001481 addrIf = sqlite3VdbeAddOp3(v, OP_IfNot, regTmp, 0, 1);
dan01e12292018-06-27 20:24:59 +00001482 VdbeCoverage(v);
dana0f6b832019-03-14 16:36:20 +00001483 sqlite3ReleaseTempReg(pParse, regTmp);
dan8b985602018-06-09 17:43:45 +00001484 }
dana0f6b832019-03-14 16:36:20 +00001485 if( pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
danc9a86682018-05-30 20:44:58 +00001486 CollSeq *pColl;
danf5e8e312018-07-09 06:51:36 +00001487 assert( nArg>0 );
dan8b985602018-06-09 17:43:45 +00001488 pColl = sqlite3ExprNNCollSeq(pParse, pWin->pOwner->x.pList->a[0].pExpr);
danc9a86682018-05-30 20:44:58 +00001489 sqlite3VdbeAddOp4(v, OP_CollSeq, 0,0,0, (const char*)pColl, P4_COLLSEQ);
1490 }
drh8f26da62018-07-05 21:22:57 +00001491 sqlite3VdbeAddOp3(v, bInverse? OP_AggInverse : OP_AggStep,
1492 bInverse, regArg, pWin->regAccum);
dana0f6b832019-03-14 16:36:20 +00001493 sqlite3VdbeAppendP4(v, pFunc, P4_FUNCDEF);
dandfa552f2018-06-02 21:04:28 +00001494 sqlite3VdbeChangeP5(v, (u8)nArg);
dan8b985602018-06-09 17:43:45 +00001495 if( addrIf ) sqlite3VdbeJumpHere(v, addrIf);
danc9a86682018-05-30 20:44:58 +00001496 }
dan31f56392018-05-24 21:10:57 +00001497 }
1498}
1499
danc782a812019-03-15 20:46:19 +00001500typedef struct WindowCodeArg WindowCodeArg;
1501typedef struct WindowCsrAndReg WindowCsrAndReg;
1502struct WindowCsrAndReg {
1503 int csr;
1504 int reg;
1505};
1506
1507struct WindowCodeArg {
1508 Parse *pParse;
1509 Window *pMWin;
1510 Vdbe *pVdbe;
1511 int regGosub;
1512 int addrGosub;
1513 int regArg;
1514 int eDelete;
1515
1516 WindowCsrAndReg start;
1517 WindowCsrAndReg current;
1518 WindowCsrAndReg end;
1519};
1520
1521/*
1522** Values that may be passed as the second argument to windowCodeOp().
1523*/
1524#define WINDOW_RETURN_ROW 1
1525#define WINDOW_AGGINVERSE 2
1526#define WINDOW_AGGSTEP 3
1527
1528/*
1529** Generate VM code to read the window frames peer values from cursor csr into
1530** an array of registers starting at reg.
1531*/
1532static void windowReadPeerValues(
1533 WindowCodeArg *p,
1534 int csr,
1535 int reg
1536){
1537 Window *pMWin = p->pMWin;
1538 ExprList *pOrderBy = pMWin->pOrderBy;
1539 if( pOrderBy ){
1540 Vdbe *v = sqlite3GetVdbe(p->pParse);
1541 ExprList *pPart = pMWin->pPartition;
1542 int iColOff = pMWin->nBufferCol + (pPart ? pPart->nExpr : 0);
1543 int i;
1544 for(i=0; i<pOrderBy->nExpr; i++){
1545 sqlite3VdbeAddOp3(v, OP_Column, csr, iColOff+i, reg+i);
1546 }
1547 }
1548}
1549
dan13078ca2018-06-13 20:29:38 +00001550/*
dana0f6b832019-03-14 16:36:20 +00001551** Generate VM code to invoke either xValue() (bFin==0) or xFinalize()
1552** (bFin==1) for each window function in the linked list starting at
dan13078ca2018-06-13 20:29:38 +00001553** pMWin. Or, for built-in window-functions that do not use the standard
1554** API, generate the equivalent VM code.
1555*/
danc782a812019-03-15 20:46:19 +00001556static void windowAggFinal(WindowCodeArg *p, int bFin){
1557 Parse *pParse = p->pParse;
1558 Window *pMWin = p->pMWin;
dand6f784e2018-05-28 18:30:45 +00001559 Vdbe *v = sqlite3GetVdbe(pParse);
1560 Window *pWin;
1561
1562 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
dana0f6b832019-03-14 16:36:20 +00001563 if( pMWin->regStartRowid==0
1564 && (pWin->pFunc->funcFlags & SQLITE_FUNC_MINMAX)
1565 && (pWin->eStart!=TK_UNBOUNDED)
danec891fd2018-06-06 20:51:02 +00001566 ){
dand6f784e2018-05-28 18:30:45 +00001567 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
danc9a86682018-05-30 20:44:58 +00001568 sqlite3VdbeAddOp1(v, OP_Last, pWin->csrApp);
dan01e12292018-06-27 20:24:59 +00001569 VdbeCoverage(v);
danc9a86682018-05-30 20:44:58 +00001570 sqlite3VdbeAddOp3(v, OP_Column, pWin->csrApp, 0, pWin->regResult);
1571 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
danec891fd2018-06-06 20:51:02 +00001572 }else if( pWin->regApp ){
dana0f6b832019-03-14 16:36:20 +00001573 assert( pMWin->regStartRowid==0 );
dand6f784e2018-05-28 18:30:45 +00001574 }else{
dana0f6b832019-03-14 16:36:20 +00001575 int nArg = windowArgCount(pWin);
1576 if( bFin ){
1577 sqlite3VdbeAddOp2(v, OP_AggFinal, pWin->regAccum, nArg);
drh8f26da62018-07-05 21:22:57 +00001578 sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
danc9a86682018-05-30 20:44:58 +00001579 sqlite3VdbeAddOp2(v, OP_Copy, pWin->regAccum, pWin->regResult);
dan8b985602018-06-09 17:43:45 +00001580 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
danc9a86682018-05-30 20:44:58 +00001581 }else{
dana0f6b832019-03-14 16:36:20 +00001582 sqlite3VdbeAddOp3(v, OP_AggValue,pWin->regAccum,nArg,pWin->regResult);
drh8f26da62018-07-05 21:22:57 +00001583 sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
danc9a86682018-05-30 20:44:58 +00001584 }
dand6f784e2018-05-28 18:30:45 +00001585 }
1586 }
1587}
1588
dan0525b6f2019-03-18 21:19:40 +00001589/*
1590** Generate code to calculate the current values of all window functions in the
1591** p->pMWin list by doing a full scan of the current window frame. Store the
1592** results in the Window.regResult registers, ready to return the upper
1593** layer.
1594*/
danc782a812019-03-15 20:46:19 +00001595static void windowFullScan(WindowCodeArg *p){
1596 Window *pWin;
1597 Parse *pParse = p->pParse;
1598 Window *pMWin = p->pMWin;
1599 Vdbe *v = p->pVdbe;
1600
1601 int regCRowid = 0; /* Current rowid value */
1602 int regCPeer = 0; /* Current peer values */
1603 int regRowid = 0; /* AggStep rowid value */
1604 int regPeer = 0; /* AggStep peer values */
1605
1606 int nPeer;
1607 int lblNext;
1608 int lblBrk;
1609 int addrNext;
drh55f66b32019-07-16 19:44:32 +00001610 int csr;
danc782a812019-03-15 20:46:19 +00001611
drh55f66b32019-07-16 19:44:32 +00001612 assert( pMWin!=0 );
1613 csr = pMWin->csrApp;
danc782a812019-03-15 20:46:19 +00001614 nPeer = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);
1615
1616 lblNext = sqlite3VdbeMakeLabel(pParse);
1617 lblBrk = sqlite3VdbeMakeLabel(pParse);
1618
1619 regCRowid = sqlite3GetTempReg(pParse);
1620 regRowid = sqlite3GetTempReg(pParse);
1621 if( nPeer ){
1622 regCPeer = sqlite3GetTempRange(pParse, nPeer);
1623 regPeer = sqlite3GetTempRange(pParse, nPeer);
1624 }
1625
1626 sqlite3VdbeAddOp2(v, OP_Rowid, pMWin->iEphCsr, regCRowid);
1627 windowReadPeerValues(p, pMWin->iEphCsr, regCPeer);
1628
1629 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1630 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
1631 }
1632
1633 sqlite3VdbeAddOp3(v, OP_SeekGE, csr, lblBrk, pMWin->regStartRowid);
dan1d4b25f2019-03-19 16:49:15 +00001634 VdbeCoverage(v);
danc782a812019-03-15 20:46:19 +00001635 addrNext = sqlite3VdbeCurrentAddr(v);
1636 sqlite3VdbeAddOp2(v, OP_Rowid, csr, regRowid);
1637 sqlite3VdbeAddOp3(v, OP_Gt, pMWin->regEndRowid, lblBrk, regRowid);
dan1d4b25f2019-03-19 16:49:15 +00001638 VdbeCoverageNeverNull(v);
dan108e6b22019-03-18 18:55:35 +00001639
danc782a812019-03-15 20:46:19 +00001640 if( pMWin->eExclude==TK_CURRENT ){
1641 sqlite3VdbeAddOp3(v, OP_Eq, regCRowid, lblNext, regRowid);
drh83c5bb92019-04-01 15:55:38 +00001642 VdbeCoverageNeverNull(v);
danc782a812019-03-15 20:46:19 +00001643 }else if( pMWin->eExclude!=TK_NO ){
1644 int addr;
dan108e6b22019-03-18 18:55:35 +00001645 int addrEq = 0;
dan66033422019-03-19 19:19:53 +00001646 KeyInfo *pKeyInfo = 0;
dan108e6b22019-03-18 18:55:35 +00001647
dan66033422019-03-19 19:19:53 +00001648 if( pMWin->pOrderBy ){
1649 pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pMWin->pOrderBy, 0, 0);
danc782a812019-03-15 20:46:19 +00001650 }
dan66033422019-03-19 19:19:53 +00001651 if( pMWin->eExclude==TK_TIES ){
1652 addrEq = sqlite3VdbeAddOp3(v, OP_Eq, regCRowid, 0, regRowid);
drh83c5bb92019-04-01 15:55:38 +00001653 VdbeCoverageNeverNull(v);
dan66033422019-03-19 19:19:53 +00001654 }
1655 if( pKeyInfo ){
1656 windowReadPeerValues(p, csr, regPeer);
1657 sqlite3VdbeAddOp3(v, OP_Compare, regPeer, regCPeer, nPeer);
1658 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
1659 addr = sqlite3VdbeCurrentAddr(v)+1;
1660 sqlite3VdbeAddOp3(v, OP_Jump, addr, lblNext, addr);
1661 VdbeCoverageEqNe(v);
1662 }else{
1663 sqlite3VdbeAddOp2(v, OP_Goto, 0, lblNext);
1664 }
danc782a812019-03-15 20:46:19 +00001665 if( addrEq ) sqlite3VdbeJumpHere(v, addrEq);
1666 }
1667
1668 windowAggStep(pParse, pMWin, csr, 0, p->regArg);
1669
1670 sqlite3VdbeResolveLabel(v, lblNext);
1671 sqlite3VdbeAddOp2(v, OP_Next, csr, addrNext);
dan1d4b25f2019-03-19 16:49:15 +00001672 VdbeCoverage(v);
danc782a812019-03-15 20:46:19 +00001673 sqlite3VdbeJumpHere(v, addrNext-1);
1674 sqlite3VdbeJumpHere(v, addrNext+1);
1675 sqlite3ReleaseTempReg(pParse, regRowid);
1676 sqlite3ReleaseTempReg(pParse, regCRowid);
1677 if( nPeer ){
1678 sqlite3ReleaseTempRange(pParse, regPeer, nPeer);
1679 sqlite3ReleaseTempRange(pParse, regCPeer, nPeer);
1680 }
1681
1682 windowAggFinal(p, 1);
1683}
1684
dan13078ca2018-06-13 20:29:38 +00001685/*
dan13078ca2018-06-13 20:29:38 +00001686** Invoke the sub-routine at regGosub (generated by code in select.c) to
1687** return the current row of Window.iEphCsr. If all window functions are
1688** aggregate window functions that use the standard API, a single
1689** OP_Gosub instruction is all that this routine generates. Extra VM code
1690** for per-row processing is only generated for the following built-in window
1691** functions:
1692**
1693** nth_value()
1694** first_value()
1695** lag()
1696** lead()
1697*/
danc782a812019-03-15 20:46:19 +00001698static void windowReturnOneRow(WindowCodeArg *p){
1699 Window *pMWin = p->pMWin;
1700 Vdbe *v = p->pVdbe;
dan7095c002018-06-07 17:45:22 +00001701
danc782a812019-03-15 20:46:19 +00001702 if( pMWin->regStartRowid ){
1703 windowFullScan(p);
1704 }else{
1705 Parse *pParse = p->pParse;
1706 Window *pWin;
1707
1708 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1709 FuncDef *pFunc = pWin->pFunc;
1710 if( pFunc->zName==nth_valueName
1711 || pFunc->zName==first_valueName
1712 ){
dana0f6b832019-03-14 16:36:20 +00001713 int csr = pWin->csrApp;
danc782a812019-03-15 20:46:19 +00001714 int lbl = sqlite3VdbeMakeLabel(pParse);
1715 int tmpReg = sqlite3GetTempReg(pParse);
1716 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
1717
1718 if( pFunc->zName==nth_valueName ){
1719 sqlite3VdbeAddOp3(v, OP_Column,pMWin->iEphCsr,pWin->iArgCol+1,tmpReg);
1720 windowCheckValue(pParse, tmpReg, 2);
1721 }else{
1722 sqlite3VdbeAddOp2(v, OP_Integer, 1, tmpReg);
1723 }
dana0f6b832019-03-14 16:36:20 +00001724 sqlite3VdbeAddOp3(v, OP_Add, tmpReg, pWin->regApp, tmpReg);
1725 sqlite3VdbeAddOp3(v, OP_Gt, pWin->regApp+1, lbl, tmpReg);
1726 VdbeCoverageNeverNull(v);
1727 sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, 0, tmpReg);
1728 VdbeCoverageNeverTaken(v);
1729 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
danc782a812019-03-15 20:46:19 +00001730 sqlite3VdbeResolveLabel(v, lbl);
1731 sqlite3ReleaseTempReg(pParse, tmpReg);
dana0f6b832019-03-14 16:36:20 +00001732 }
danc782a812019-03-15 20:46:19 +00001733 else if( pFunc->zName==leadName || pFunc->zName==lagName ){
1734 int nArg = pWin->pOwner->x.pList->nExpr;
1735 int csr = pWin->csrApp;
1736 int lbl = sqlite3VdbeMakeLabel(pParse);
1737 int tmpReg = sqlite3GetTempReg(pParse);
1738 int iEph = pMWin->iEphCsr;
1739
1740 if( nArg<3 ){
1741 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
1742 }else{
1743 sqlite3VdbeAddOp3(v, OP_Column, iEph,pWin->iArgCol+2,pWin->regResult);
1744 }
1745 sqlite3VdbeAddOp2(v, OP_Rowid, iEph, tmpReg);
1746 if( nArg<2 ){
1747 int val = (pFunc->zName==leadName ? 1 : -1);
1748 sqlite3VdbeAddOp2(v, OP_AddImm, tmpReg, val);
1749 }else{
1750 int op = (pFunc->zName==leadName ? OP_Add : OP_Subtract);
1751 int tmpReg2 = sqlite3GetTempReg(pParse);
1752 sqlite3VdbeAddOp3(v, OP_Column, iEph, pWin->iArgCol+1, tmpReg2);
1753 sqlite3VdbeAddOp3(v, op, tmpReg2, tmpReg, tmpReg);
1754 sqlite3ReleaseTempReg(pParse, tmpReg2);
1755 }
1756
1757 sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, lbl, tmpReg);
1758 VdbeCoverage(v);
1759 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
1760 sqlite3VdbeResolveLabel(v, lbl);
1761 sqlite3ReleaseTempReg(pParse, tmpReg);
danfe4e25a2018-06-07 20:08:59 +00001762 }
danfe4e25a2018-06-07 20:08:59 +00001763 }
danec891fd2018-06-06 20:51:02 +00001764 }
danc782a812019-03-15 20:46:19 +00001765 sqlite3VdbeAddOp2(v, OP_Gosub, p->regGosub, p->addrGosub);
danec891fd2018-06-06 20:51:02 +00001766}
1767
dan13078ca2018-06-13 20:29:38 +00001768/*
dan54a9ab32018-06-14 14:27:05 +00001769** Generate code to set the accumulator register for each window function
1770** in the linked list passed as the second argument to NULL. And perform
1771** any equivalent initialization required by any built-in window functions
1772** in the list.
1773*/
dan2e605682018-06-07 15:54:26 +00001774static int windowInitAccum(Parse *pParse, Window *pMWin){
1775 Vdbe *v = sqlite3GetVdbe(pParse);
1776 int regArg;
1777 int nArg = 0;
1778 Window *pWin;
1779 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
dan9a947222018-06-14 19:06:36 +00001780 FuncDef *pFunc = pWin->pFunc;
dan2e605682018-06-07 15:54:26 +00001781 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
dan2a11bb22018-06-11 20:50:25 +00001782 nArg = MAX(nArg, windowArgCount(pWin));
dan108e6b22019-03-18 18:55:35 +00001783 if( pMWin->regStartRowid==0 ){
dana0f6b832019-03-14 16:36:20 +00001784 if( pFunc->zName==nth_valueName || pFunc->zName==first_valueName ){
1785 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp);
1786 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
1787 }
dan9a947222018-06-14 19:06:36 +00001788
dana0f6b832019-03-14 16:36:20 +00001789 if( (pFunc->funcFlags & SQLITE_FUNC_MINMAX) && pWin->csrApp ){
1790 assert( pWin->eStart!=TK_UNBOUNDED );
1791 sqlite3VdbeAddOp1(v, OP_ResetSorter, pWin->csrApp);
1792 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
1793 }
dan9a947222018-06-14 19:06:36 +00001794 }
dan2e605682018-06-07 15:54:26 +00001795 }
1796 regArg = pParse->nMem+1;
1797 pParse->nMem += nArg;
1798 return regArg;
1799}
1800
danb33487b2019-03-06 17:12:32 +00001801/*
dancc7a8502019-03-11 19:50:54 +00001802** Return true if the current frame should be cached in the ephemeral table,
1803** even if there are no xInverse() calls required.
danb33487b2019-03-06 17:12:32 +00001804*/
dancc7a8502019-03-11 19:50:54 +00001805static int windowCacheFrame(Window *pMWin){
danb33487b2019-03-06 17:12:32 +00001806 Window *pWin;
dana0f6b832019-03-14 16:36:20 +00001807 if( pMWin->regStartRowid ) return 1;
danb33487b2019-03-06 17:12:32 +00001808 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1809 FuncDef *pFunc = pWin->pFunc;
dancc7a8502019-03-11 19:50:54 +00001810 if( (pFunc->zName==nth_valueName)
danb33487b2019-03-06 17:12:32 +00001811 || (pFunc->zName==first_valueName)
danb560a712019-03-13 15:29:14 +00001812 || (pFunc->zName==leadName)
danb33487b2019-03-06 17:12:32 +00001813 || (pFunc->zName==lagName)
1814 ){
1815 return 1;
1816 }
1817 }
1818 return 0;
1819}
1820
dan6c75b392019-03-08 20:02:52 +00001821/*
1822** regOld and regNew are each the first register in an array of size
1823** pOrderBy->nExpr. This function generates code to compare the two
1824** arrays of registers using the collation sequences and other comparison
1825** parameters specified by pOrderBy.
1826**
1827** If the two arrays are not equal, the contents of regNew is copied to
1828** regOld and control falls through. Otherwise, if the contents of the arrays
1829** are equal, an OP_Goto is executed. The address of the OP_Goto is returned.
1830*/
dan935d9d82019-03-12 15:21:51 +00001831static void windowIfNewPeer(
dan6c75b392019-03-08 20:02:52 +00001832 Parse *pParse,
1833 ExprList *pOrderBy,
1834 int regNew, /* First in array of new values */
dan935d9d82019-03-12 15:21:51 +00001835 int regOld, /* First in array of old values */
1836 int addr /* Jump here */
dan6c75b392019-03-08 20:02:52 +00001837){
1838 Vdbe *v = sqlite3GetVdbe(pParse);
dan6c75b392019-03-08 20:02:52 +00001839 if( pOrderBy ){
1840 int nVal = pOrderBy->nExpr;
1841 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pOrderBy, 0, 0);
1842 sqlite3VdbeAddOp3(v, OP_Compare, regOld, regNew, nVal);
1843 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
dan935d9d82019-03-12 15:21:51 +00001844 sqlite3VdbeAddOp3(v, OP_Jump,
1845 sqlite3VdbeCurrentAddr(v)+1, addr, sqlite3VdbeCurrentAddr(v)+1
dan72b9fdc2019-03-09 20:49:17 +00001846 );
dan6c75b392019-03-08 20:02:52 +00001847 VdbeCoverageEqNe(v);
1848 sqlite3VdbeAddOp3(v, OP_Copy, regNew, regOld, nVal-1);
1849 }else{
dan935d9d82019-03-12 15:21:51 +00001850 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
dan6c75b392019-03-08 20:02:52 +00001851 }
dan6c75b392019-03-08 20:02:52 +00001852}
1853
dan72b9fdc2019-03-09 20:49:17 +00001854/*
1855** This function is called as part of generating VM programs for RANGE
dan1e7cb192019-03-16 20:29:54 +00001856** offset PRECEDING/FOLLOWING frame boundaries. Assuming "ASC" order for
1857** the ORDER BY term in the window, it generates code equivalent to:
dan72b9fdc2019-03-09 20:49:17 +00001858**
1859** if( csr1.peerVal + regVal >= csr2.peerVal ) goto lbl;
dan1e7cb192019-03-16 20:29:54 +00001860**
1861** A special type of arithmetic is used such that if csr.peerVal is not
1862** a numeric type (real or integer), then the result of the addition is
1863** a copy of csr1.peerVal.
dan72b9fdc2019-03-09 20:49:17 +00001864*/
1865static void windowCodeRangeTest(
1866 WindowCodeArg *p,
1867 int op, /* OP_Ge or OP_Gt */
1868 int csr1,
1869 int regVal,
1870 int csr2,
1871 int lbl
1872){
1873 Parse *pParse = p->pParse;
1874 Vdbe *v = sqlite3GetVdbe(pParse);
1875 int reg1 = sqlite3GetTempReg(pParse);
1876 int reg2 = sqlite3GetTempReg(pParse);
dan71fddaf2019-03-11 11:12:34 +00001877 int arith = OP_Add;
dan1e7cb192019-03-16 20:29:54 +00001878 int addrGe;
danae8e45c2019-08-19 19:59:50 +00001879 ExprList *pOrderBy = p->pMWin->pOrderBy;
dan1e7cb192019-03-16 20:29:54 +00001880
1881 int regString = ++pParse->nMem;
dan71fddaf2019-03-11 11:12:34 +00001882
1883 assert( op==OP_Ge || op==OP_Gt || op==OP_Le );
danae8e45c2019-08-19 19:59:50 +00001884 assert( pOrderBy && pOrderBy->nExpr==1 );
1885 if( pOrderBy->a[0].sortFlags & KEYINFO_ORDER_DESC ){
dan71fddaf2019-03-11 11:12:34 +00001886 switch( op ){
1887 case OP_Ge: op = OP_Le; break;
1888 case OP_Gt: op = OP_Lt; break;
1889 default: assert( op==OP_Le ); op = OP_Ge; break;
1890 }
1891 arith = OP_Subtract;
1892 }
1893
dan72b9fdc2019-03-09 20:49:17 +00001894 windowReadPeerValues(p, csr1, reg1);
1895 windowReadPeerValues(p, csr2, reg2);
dan1e7cb192019-03-16 20:29:54 +00001896
1897 /* Check if the peer value for csr1 value is a text or blob by comparing
danbdabe742019-03-18 16:51:24 +00001898 ** it to the smallest possible string - ''. If it is, jump over the
1899 ** OP_Add or OP_Subtract operation and proceed directly to the comparison. */
dan1e7cb192019-03-16 20:29:54 +00001900 sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC);
1901 addrGe = sqlite3VdbeAddOp3(v, OP_Ge, regString, 0, reg1);
dan1d4b25f2019-03-19 16:49:15 +00001902 VdbeCoverage(v);
dan71fddaf2019-03-11 11:12:34 +00001903 sqlite3VdbeAddOp3(v, arith, regVal, reg1, reg1);
dan1e7cb192019-03-16 20:29:54 +00001904 sqlite3VdbeJumpHere(v, addrGe);
danae8e45c2019-08-19 19:59:50 +00001905 if( pOrderBy->a[0].sortFlags & KEYINFO_ORDER_BIGNULL ){
1906 int addr;
1907 addr = sqlite3VdbeAddOp1(v, OP_NotNull, reg1); VdbeCoverage(v);
1908 switch( op ){
1909 case OP_Ge: sqlite3VdbeAddOp2(v, OP_Goto, 0, lbl); break;
danf236b212019-08-21 19:58:11 +00001910 case OP_Gt:
1911 sqlite3VdbeAddOp2(v, OP_NotNull, reg2, lbl);
1912 VdbeCoverage(v);
1913 break;
1914 case OP_Le:
1915 sqlite3VdbeAddOp2(v, OP_IsNull, reg2, lbl);
1916 VdbeCoverage(v);
1917 break;
danae8e45c2019-08-19 19:59:50 +00001918 default: assert( op==OP_Lt ); /* no-op */
1919 }
1920 sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+2);
1921 sqlite3VdbeJumpHere(v, addr);
1922 sqlite3VdbeAddOp2(v, OP_IsNull, reg2, lbl); VdbeCoverage(v);
1923 if( op==OP_Gt || op==OP_Ge ){
1924 sqlite3VdbeChangeP2(v, -1, sqlite3VdbeCurrentAddr(v)+1);
1925 }
1926 }
drh6f883592019-03-30 20:37:04 +00001927 sqlite3VdbeAddOp3(v, op, reg2, lbl, reg1); VdbeCoverage(v);
danbdabe742019-03-18 16:51:24 +00001928 sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
drh6f883592019-03-30 20:37:04 +00001929 assert( op==OP_Ge || op==OP_Gt || op==OP_Lt || op==OP_Le );
1930 testcase(op==OP_Ge); VdbeCoverageIf(v, op==OP_Ge);
1931 testcase(op==OP_Lt); VdbeCoverageIf(v, op==OP_Lt);
1932 testcase(op==OP_Le); VdbeCoverageIf(v, op==OP_Le);
1933 testcase(op==OP_Gt); VdbeCoverageIf(v, op==OP_Gt);
dan1e7cb192019-03-16 20:29:54 +00001934
dan72b9fdc2019-03-09 20:49:17 +00001935 sqlite3ReleaseTempReg(pParse, reg1);
1936 sqlite3ReleaseTempReg(pParse, reg2);
dan72b9fdc2019-03-09 20:49:17 +00001937}
1938
dan0525b6f2019-03-18 21:19:40 +00001939/*
1940** Helper function for sqlite3WindowCodeStep(). Each call to this function
1941** generates VM code for a single RETURN_ROW, AGGSTEP or AGGINVERSE
1942** operation. Refer to the header comment for sqlite3WindowCodeStep() for
1943** details.
1944*/
dan00267b82019-03-06 21:04:11 +00001945static int windowCodeOp(
dan0525b6f2019-03-18 21:19:40 +00001946 WindowCodeArg *p, /* Context object */
1947 int op, /* WINDOW_RETURN_ROW, AGGSTEP or AGGINVERSE */
1948 int regCountdown, /* Register for OP_IfPos countdown */
1949 int jumpOnEof /* Jump here if stepped cursor reaches EOF */
dan00267b82019-03-06 21:04:11 +00001950){
dan6c75b392019-03-08 20:02:52 +00001951 int csr, reg;
1952 Parse *pParse = p->pParse;
dan54975cd2019-03-07 20:47:46 +00001953 Window *pMWin = p->pMWin;
dan00267b82019-03-06 21:04:11 +00001954 int ret = 0;
1955 Vdbe *v = p->pVdbe;
1956 int addrIf = 0;
dan6c75b392019-03-08 20:02:52 +00001957 int addrContinue = 0;
1958 int addrGoto = 0;
drhfc15f4c2019-03-28 13:03:41 +00001959 int bPeer = (pMWin->eFrmType!=TK_ROWS);
dan00267b82019-03-06 21:04:11 +00001960
dan72b9fdc2019-03-09 20:49:17 +00001961 int lblDone = sqlite3VdbeMakeLabel(pParse);
1962 int addrNextRange = 0;
1963
dan54975cd2019-03-07 20:47:46 +00001964 /* Special case - WINDOW_AGGINVERSE is always a no-op if the frame
1965 ** starts with UNBOUNDED PRECEDING. */
1966 if( op==WINDOW_AGGINVERSE && pMWin->eStart==TK_UNBOUNDED ){
1967 assert( regCountdown==0 && jumpOnEof==0 );
1968 return 0;
1969 }
1970
dan00267b82019-03-06 21:04:11 +00001971 if( regCountdown>0 ){
drhfc15f4c2019-03-28 13:03:41 +00001972 if( pMWin->eFrmType==TK_RANGE ){
dan72b9fdc2019-03-09 20:49:17 +00001973 addrNextRange = sqlite3VdbeCurrentAddr(v);
dan0525b6f2019-03-18 21:19:40 +00001974 assert( op==WINDOW_AGGINVERSE || op==WINDOW_AGGSTEP );
1975 if( op==WINDOW_AGGINVERSE ){
1976 if( pMWin->eStart==TK_FOLLOWING ){
dan72b9fdc2019-03-09 20:49:17 +00001977 windowCodeRangeTest(
dan0525b6f2019-03-18 21:19:40 +00001978 p, OP_Le, p->current.csr, regCountdown, p->start.csr, lblDone
dan72b9fdc2019-03-09 20:49:17 +00001979 );
dan0525b6f2019-03-18 21:19:40 +00001980 }else{
1981 windowCodeRangeTest(
1982 p, OP_Ge, p->start.csr, regCountdown, p->current.csr, lblDone
1983 );
dan72b9fdc2019-03-09 20:49:17 +00001984 }
dan0525b6f2019-03-18 21:19:40 +00001985 }else{
1986 windowCodeRangeTest(
1987 p, OP_Gt, p->end.csr, regCountdown, p->current.csr, lblDone
1988 );
dan72b9fdc2019-03-09 20:49:17 +00001989 }
dan72b9fdc2019-03-09 20:49:17 +00001990 }else{
1991 addrIf = sqlite3VdbeAddOp3(v, OP_IfPos, regCountdown, 0, 1);
dan1d4b25f2019-03-19 16:49:15 +00001992 VdbeCoverage(v);
dan72b9fdc2019-03-09 20:49:17 +00001993 }
dan00267b82019-03-06 21:04:11 +00001994 }
1995
dan0525b6f2019-03-18 21:19:40 +00001996 if( op==WINDOW_RETURN_ROW && pMWin->regStartRowid==0 ){
danc782a812019-03-15 20:46:19 +00001997 windowAggFinal(p, 0);
dan6c75b392019-03-08 20:02:52 +00001998 }
1999 addrContinue = sqlite3VdbeCurrentAddr(v);
dan00267b82019-03-06 21:04:11 +00002000 switch( op ){
2001 case WINDOW_RETURN_ROW:
dan6c75b392019-03-08 20:02:52 +00002002 csr = p->current.csr;
2003 reg = p->current.reg;
danc782a812019-03-15 20:46:19 +00002004 windowReturnOneRow(p);
dan00267b82019-03-06 21:04:11 +00002005 break;
2006
2007 case WINDOW_AGGINVERSE:
dan6c75b392019-03-08 20:02:52 +00002008 csr = p->start.csr;
2009 reg = p->start.reg;
dana0f6b832019-03-14 16:36:20 +00002010 if( pMWin->regStartRowid ){
2011 assert( pMWin->regEndRowid );
2012 sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regStartRowid, 1);
2013 }else{
2014 windowAggStep(pParse, pMWin, csr, 1, p->regArg);
2015 }
dan00267b82019-03-06 21:04:11 +00002016 break;
2017
dan0525b6f2019-03-18 21:19:40 +00002018 default:
2019 assert( op==WINDOW_AGGSTEP );
dan6c75b392019-03-08 20:02:52 +00002020 csr = p->end.csr;
2021 reg = p->end.reg;
dana0f6b832019-03-14 16:36:20 +00002022 if( pMWin->regStartRowid ){
2023 assert( pMWin->regEndRowid );
2024 sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regEndRowid, 1);
2025 }else{
2026 windowAggStep(pParse, pMWin, csr, 0, p->regArg);
2027 }
dan00267b82019-03-06 21:04:11 +00002028 break;
2029 }
2030
danb560a712019-03-13 15:29:14 +00002031 if( op==p->eDelete ){
2032 sqlite3VdbeAddOp1(v, OP_Delete, csr);
2033 sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
2034 }
2035
danc8137502019-03-07 19:26:17 +00002036 if( jumpOnEof ){
2037 sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+2);
dan1d4b25f2019-03-19 16:49:15 +00002038 VdbeCoverage(v);
danc8137502019-03-07 19:26:17 +00002039 ret = sqlite3VdbeAddOp0(v, OP_Goto);
2040 }else{
dan6c75b392019-03-08 20:02:52 +00002041 sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+1+bPeer);
dan1d4b25f2019-03-19 16:49:15 +00002042 VdbeCoverage(v);
dan6c75b392019-03-08 20:02:52 +00002043 if( bPeer ){
2044 addrGoto = sqlite3VdbeAddOp0(v, OP_Goto);
2045 }
dan00267b82019-03-06 21:04:11 +00002046 }
danc8137502019-03-07 19:26:17 +00002047
dan6c75b392019-03-08 20:02:52 +00002048 if( bPeer ){
dan6c75b392019-03-08 20:02:52 +00002049 int nReg = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);
2050 int regTmp = (nReg ? sqlite3GetTempRange(pParse, nReg) : 0);
2051 windowReadPeerValues(p, csr, regTmp);
dan935d9d82019-03-12 15:21:51 +00002052 windowIfNewPeer(pParse, pMWin->pOrderBy, regTmp, reg, addrContinue);
dan6c75b392019-03-08 20:02:52 +00002053 sqlite3ReleaseTempRange(pParse, regTmp, nReg);
dan00267b82019-03-06 21:04:11 +00002054 }
dan6c75b392019-03-08 20:02:52 +00002055
dan72b9fdc2019-03-09 20:49:17 +00002056 if( addrNextRange ){
2057 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNextRange);
2058 }
2059 sqlite3VdbeResolveLabel(v, lblDone);
dan6c75b392019-03-08 20:02:52 +00002060 if( addrGoto ) sqlite3VdbeJumpHere(v, addrGoto);
2061 if( addrIf ) sqlite3VdbeJumpHere(v, addrIf);
dan00267b82019-03-06 21:04:11 +00002062 return ret;
2063}
2064
dana786e452019-03-11 18:17:04 +00002065
dan00267b82019-03-06 21:04:11 +00002066/*
dana786e452019-03-11 18:17:04 +00002067** Allocate and return a duplicate of the Window object indicated by the
2068** third argument. Set the Window.pOwner field of the new object to
2069** pOwner.
2070*/
2071Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p){
2072 Window *pNew = 0;
2073 if( ALWAYS(p) ){
2074 pNew = sqlite3DbMallocZero(db, sizeof(Window));
2075 if( pNew ){
2076 pNew->zName = sqlite3DbStrDup(db, p->zName);
2077 pNew->pFilter = sqlite3ExprDup(db, p->pFilter, 0);
2078 pNew->pFunc = p->pFunc;
2079 pNew->pPartition = sqlite3ExprListDup(db, p->pPartition, 0);
2080 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, 0);
drhfc15f4c2019-03-28 13:03:41 +00002081 pNew->eFrmType = p->eFrmType;
dana786e452019-03-11 18:17:04 +00002082 pNew->eEnd = p->eEnd;
2083 pNew->eStart = p->eStart;
danc782a812019-03-15 20:46:19 +00002084 pNew->eExclude = p->eExclude;
drhb555b082019-07-19 01:11:27 +00002085 pNew->regResult = p->regResult;
dana786e452019-03-11 18:17:04 +00002086 pNew->pStart = sqlite3ExprDup(db, p->pStart, 0);
2087 pNew->pEnd = sqlite3ExprDup(db, p->pEnd, 0);
2088 pNew->pOwner = pOwner;
2089 }
2090 }
2091 return pNew;
2092}
2093
2094/*
2095** Return a copy of the linked list of Window objects passed as the
2096** second argument.
2097*/
2098Window *sqlite3WindowListDup(sqlite3 *db, Window *p){
2099 Window *pWin;
2100 Window *pRet = 0;
2101 Window **pp = &pRet;
2102
2103 for(pWin=p; pWin; pWin=pWin->pNextWin){
2104 *pp = sqlite3WindowDup(db, 0, pWin);
2105 if( *pp==0 ) break;
2106 pp = &((*pp)->pNextWin);
2107 }
2108
2109 return pRet;
2110}
2111
2112/*
dan725b1cf2019-03-26 16:47:17 +00002113** Return true if it can be determined at compile time that expression
2114** pExpr evaluates to a value that, when cast to an integer, is greater
2115** than zero. False otherwise.
2116**
2117** If an OOM error occurs, this function sets the Parse.db.mallocFailed
2118** flag and returns zero.
2119*/
2120static int windowExprGtZero(Parse *pParse, Expr *pExpr){
2121 int ret = 0;
2122 sqlite3 *db = pParse->db;
2123 sqlite3_value *pVal = 0;
2124 sqlite3ValueFromExpr(db, pExpr, db->enc, SQLITE_AFF_NUMERIC, &pVal);
2125 if( pVal && sqlite3_value_int(pVal)>0 ){
2126 ret = 1;
2127 }
2128 sqlite3ValueFree(pVal);
2129 return ret;
2130}
2131
2132/*
dana786e452019-03-11 18:17:04 +00002133** sqlite3WhereBegin() has already been called for the SELECT statement
2134** passed as the second argument when this function is invoked. It generates
2135** code to populate the Window.regResult register for each window function
2136** and invoke the sub-routine at instruction addrGosub once for each row.
2137** sqlite3WhereEnd() is always called before returning.
dan00267b82019-03-06 21:04:11 +00002138**
dana786e452019-03-11 18:17:04 +00002139** This function handles several different types of window frames, which
2140** require slightly different processing. The following pseudo code is
2141** used to implement window frames of the form:
dan00267b82019-03-06 21:04:11 +00002142**
dana786e452019-03-11 18:17:04 +00002143** ROWS BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
dan00267b82019-03-06 21:04:11 +00002144**
dana786e452019-03-11 18:17:04 +00002145** Other window frame types use variants of the following:
2146**
2147** ... loop started by sqlite3WhereBegin() ...
dan00267b82019-03-06 21:04:11 +00002148** if( new partition ){
2149** Gosub flush
dana786e452019-03-11 18:17:04 +00002150** }
dan00267b82019-03-06 21:04:11 +00002151** Insert new row into eph table.
dana786e452019-03-11 18:17:04 +00002152**
dan00267b82019-03-06 21:04:11 +00002153** if( first row of partition ){
dana786e452019-03-11 18:17:04 +00002154** // Rewind three cursors, all open on the eph table.
2155** Rewind(csrEnd);
2156** Rewind(csrStart);
2157** Rewind(csrCurrent);
2158**
dan00267b82019-03-06 21:04:11 +00002159** regEnd = <expr2> // FOLLOWING expression
2160** regStart = <expr1> // PRECEDING expression
2161** }else{
dana786e452019-03-11 18:17:04 +00002162** // First time this branch is taken, the eph table contains two
2163** // rows. The first row in the partition, which all three cursors
2164** // currently point to, and the following row.
2165** AGGSTEP
dan00267b82019-03-06 21:04:11 +00002166** if( (regEnd--)<=0 ){
dana786e452019-03-11 18:17:04 +00002167** RETURN_ROW
2168** if( (regStart--)<=0 ){
2169** AGGINVERSE
dan00267b82019-03-06 21:04:11 +00002170** }
2171** }
dana786e452019-03-11 18:17:04 +00002172** }
2173** }
dan00267b82019-03-06 21:04:11 +00002174** flush:
dana786e452019-03-11 18:17:04 +00002175** AGGSTEP
2176** while( 1 ){
2177** RETURN ROW
2178** if( csrCurrent is EOF ) break;
2179** if( (regStart--)<=0 ){
2180** AggInverse(csrStart)
2181** Next(csrStart)
dan00267b82019-03-06 21:04:11 +00002182** }
dana786e452019-03-11 18:17:04 +00002183** }
dan00267b82019-03-06 21:04:11 +00002184**
dana786e452019-03-11 18:17:04 +00002185** The pseudo-code above uses the following shorthand:
dan00267b82019-03-06 21:04:11 +00002186**
dana786e452019-03-11 18:17:04 +00002187** AGGSTEP: invoke the aggregate xStep() function for each window function
2188** with arguments read from the current row of cursor csrEnd, then
2189** step cursor csrEnd forward one row (i.e. sqlite3BtreeNext()).
2190**
2191** RETURN_ROW: return a row to the caller based on the contents of the
2192** current row of csrCurrent and the current state of all
2193** aggregates. Then step cursor csrCurrent forward one row.
2194**
2195** AGGINVERSE: invoke the aggregate xInverse() function for each window
2196** functions with arguments read from the current row of cursor
2197** csrStart. Then step csrStart forward one row.
2198**
2199** There are two other ROWS window frames that are handled significantly
2200** differently from the above - "BETWEEN <expr> PRECEDING AND <expr> PRECEDING"
2201** and "BETWEEN <expr> FOLLOWING AND <expr> FOLLOWING". These are special
2202** cases because they change the order in which the three cursors (csrStart,
2203** csrCurrent and csrEnd) iterate through the ephemeral table. Cases that
2204** use UNBOUNDED or CURRENT ROW are much simpler variations on one of these
2205** three.
2206**
2207** ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
2208**
2209** ... loop started by sqlite3WhereBegin() ...
dan00267b82019-03-06 21:04:11 +00002210** if( new partition ){
2211** Gosub flush
dana786e452019-03-11 18:17:04 +00002212** }
dan00267b82019-03-06 21:04:11 +00002213** Insert new row into eph table.
2214** if( first row of partition ){
dan935d9d82019-03-12 15:21:51 +00002215** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
dana786e452019-03-11 18:17:04 +00002216** regEnd = <expr2>
2217** regStart = <expr1>
dan00267b82019-03-06 21:04:11 +00002218** }else{
dana786e452019-03-11 18:17:04 +00002219** if( (regEnd--)<=0 ){
2220** AGGSTEP
2221** }
2222** RETURN_ROW
2223** if( (regStart--)<=0 ){
2224** AGGINVERSE
2225** }
2226** }
2227** }
dan00267b82019-03-06 21:04:11 +00002228** flush:
dana786e452019-03-11 18:17:04 +00002229** if( (regEnd--)<=0 ){
2230** AGGSTEP
2231** }
2232** RETURN_ROW
2233**
2234**
2235** ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
2236**
2237** ... loop started by sqlite3WhereBegin() ...
2238** if( new partition ){
2239** Gosub flush
2240** }
2241** Insert new row into eph table.
2242** if( first row of partition ){
dan935d9d82019-03-12 15:21:51 +00002243** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
dana786e452019-03-11 18:17:04 +00002244** regEnd = <expr2>
2245** regStart = regEnd - <expr1>
2246** }else{
2247** AGGSTEP
2248** if( (regEnd--)<=0 ){
2249** RETURN_ROW
2250** }
2251** if( (regStart--)<=0 ){
2252** AGGINVERSE
2253** }
2254** }
2255** }
2256** flush:
2257** AGGSTEP
2258** while( 1 ){
2259** if( (regEnd--)<=0 ){
2260** RETURN_ROW
2261** if( eof ) break;
2262** }
2263** if( (regStart--)<=0 ){
2264** AGGINVERSE
2265** if( eof ) break
2266** }
2267** }
2268** while( !eof csrCurrent ){
2269** RETURN_ROW
2270** }
2271**
2272** For the most part, the patterns above are adapted to support UNBOUNDED by
2273** assuming that it is equivalent to "infinity PRECEDING/FOLLOWING" and
2274** CURRENT ROW by assuming that it is equivilent to "0 PRECEDING/FOLLOWING".
2275** This is optimized of course - branches that will never be taken and
2276** conditions that are always true are omitted from the VM code. The only
2277** exceptional case is:
2278**
2279** ROWS BETWEEN <expr1> FOLLOWING AND UNBOUNDED FOLLOWING
2280**
2281** ... loop started by sqlite3WhereBegin() ...
2282** if( new partition ){
2283** Gosub flush
2284** }
2285** Insert new row into eph table.
2286** if( first row of partition ){
dan935d9d82019-03-12 15:21:51 +00002287** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
dana786e452019-03-11 18:17:04 +00002288** regStart = <expr1>
2289** }else{
2290** AGGSTEP
2291** }
2292** }
2293** flush:
2294** AGGSTEP
2295** while( 1 ){
2296** if( (regStart--)<=0 ){
2297** AGGINVERSE
2298** if( eof ) break
2299** }
2300** RETURN_ROW
2301** }
2302** while( !eof csrCurrent ){
2303** RETURN_ROW
2304** }
dan935d9d82019-03-12 15:21:51 +00002305**
2306** Also requiring special handling are the cases:
2307**
2308** ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
2309** ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
2310**
2311** when (expr1 < expr2). This is detected at runtime, not by this function.
2312** To handle this case, the pseudo-code programs depicted above are modified
2313** slightly to be:
2314**
2315** ... loop started by sqlite3WhereBegin() ...
2316** if( new partition ){
2317** Gosub flush
2318** }
2319** Insert new row into eph table.
2320** if( first row of partition ){
2321** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2322** regEnd = <expr2>
2323** regStart = <expr1>
2324** if( regEnd < regStart ){
2325** RETURN_ROW
2326** delete eph table contents
2327** continue
2328** }
2329** ...
2330**
2331** The new "continue" statement in the above jumps to the next iteration
2332** of the outer loop - the one started by sqlite3WhereBegin().
2333**
2334** The various GROUPS cases are implemented using the same patterns as
2335** ROWS. The VM code is modified slightly so that:
2336**
2337** 1. The else branch in the main loop is only taken if the row just
2338** added to the ephemeral table is the start of a new group. In
2339** other words, it becomes:
2340**
2341** ... loop started by sqlite3WhereBegin() ...
2342** if( new partition ){
2343** Gosub flush
2344** }
2345** Insert new row into eph table.
2346** if( first row of partition ){
2347** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2348** regEnd = <expr2>
2349** regStart = <expr1>
2350** }else if( new group ){
2351** ...
2352** }
2353** }
2354**
2355** 2. Instead of processing a single row, each RETURN_ROW, AGGSTEP or
2356** AGGINVERSE step processes the current row of the relevant cursor and
2357** all subsequent rows belonging to the same group.
2358**
2359** RANGE window frames are a little different again. As for GROUPS, the
2360** main loop runs once per group only. And RETURN_ROW, AGGSTEP and AGGINVERSE
2361** deal in groups instead of rows. As for ROWS and GROUPS, there are three
2362** basic cases:
2363**
2364** RANGE BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
2365**
2366** ... loop started by sqlite3WhereBegin() ...
2367** if( new partition ){
2368** Gosub flush
2369** }
2370** Insert new row into eph table.
2371** if( first row of partition ){
2372** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2373** regEnd = <expr2>
2374** regStart = <expr1>
2375** }else{
2376** AGGSTEP
2377** while( (csrCurrent.key + regEnd) < csrEnd.key ){
2378** RETURN_ROW
2379** while( csrStart.key + regStart) < csrCurrent.key ){
2380** AGGINVERSE
2381** }
2382** }
2383** }
2384** }
2385** flush:
2386** AGGSTEP
2387** while( 1 ){
2388** RETURN ROW
2389** if( csrCurrent is EOF ) break;
2390** while( csrStart.key + regStart) < csrCurrent.key ){
2391** AGGINVERSE
2392** }
2393** }
2394** }
2395**
2396** In the above notation, "csr.key" means the current value of the ORDER BY
2397** expression (there is only ever 1 for a RANGE that uses an <expr> FOLLOWING
2398** or <expr PRECEDING) read from cursor csr.
2399**
2400** RANGE BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
2401**
2402** ... loop started by sqlite3WhereBegin() ...
2403** if( new partition ){
2404** Gosub flush
2405** }
2406** Insert new row into eph table.
2407** if( first row of partition ){
2408** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2409** regEnd = <expr2>
2410** regStart = <expr1>
2411** }else{
dan3f49c322019-04-03 16:27:44 +00002412** if( (csrEnd.key + regEnd) <= csrCurrent.key ){
dan935d9d82019-03-12 15:21:51 +00002413** AGGSTEP
2414** }
dan935d9d82019-03-12 15:21:51 +00002415** while( (csrStart.key + regStart) < csrCurrent.key ){
2416** AGGINVERSE
2417** }
dan3f49c322019-04-03 16:27:44 +00002418** RETURN_ROW
dan935d9d82019-03-12 15:21:51 +00002419** }
2420** }
2421** flush:
2422** while( (csrEnd.key + regEnd) <= csrCurrent.key ){
2423** AGGSTEP
2424** }
dan3f49c322019-04-03 16:27:44 +00002425** while( (csrStart.key + regStart) < csrCurrent.key ){
2426** AGGINVERSE
2427** }
dan935d9d82019-03-12 15:21:51 +00002428** RETURN_ROW
2429**
2430** RANGE BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
2431**
2432** ... loop started by sqlite3WhereBegin() ...
2433** if( new partition ){
2434** Gosub flush
2435** }
2436** Insert new row into eph table.
2437** if( first row of partition ){
2438** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
2439** regEnd = <expr2>
2440** regStart = <expr1>
2441** }else{
2442** AGGSTEP
2443** while( (csrCurrent.key + regEnd) < csrEnd.key ){
2444** while( (csrCurrent.key + regStart) > csrStart.key ){
2445** AGGINVERSE
2446** }
2447** RETURN_ROW
2448** }
2449** }
2450** }
2451** flush:
2452** AGGSTEP
2453** while( 1 ){
2454** while( (csrCurrent.key + regStart) > csrStart.key ){
2455** AGGINVERSE
2456** if( eof ) break "while( 1 )" loop.
2457** }
2458** RETURN_ROW
2459** }
2460** while( !eof csrCurrent ){
2461** RETURN_ROW
2462** }
2463**
danb6f2dea2019-03-13 17:20:27 +00002464** The text above leaves out many details. Refer to the code and comments
2465** below for a more complete picture.
dan00267b82019-03-06 21:04:11 +00002466*/
dana786e452019-03-11 18:17:04 +00002467void sqlite3WindowCodeStep(
dancc7a8502019-03-11 19:50:54 +00002468 Parse *pParse, /* Parse context */
dana786e452019-03-11 18:17:04 +00002469 Select *p, /* Rewritten SELECT statement */
2470 WhereInfo *pWInfo, /* Context returned by sqlite3WhereBegin() */
2471 int regGosub, /* Register for OP_Gosub */
2472 int addrGosub /* OP_Gosub here to return each row */
dan680f6e82019-03-04 21:07:11 +00002473){
2474 Window *pMWin = p->pWin;
dan6c75b392019-03-08 20:02:52 +00002475 ExprList *pOrderBy = pMWin->pOrderBy;
dan680f6e82019-03-04 21:07:11 +00002476 Vdbe *v = sqlite3GetVdbe(pParse);
dana786e452019-03-11 18:17:04 +00002477 int csrWrite; /* Cursor used to write to eph. table */
2478 int csrInput = p->pSrc->a[0].iCursor; /* Cursor of sub-select */
2479 int nInput = p->pSrc->a[0].pTab->nCol; /* Number of cols returned by sub */
2480 int iInput; /* To iterate through sub cols */
danbf845152019-03-16 10:15:24 +00002481 int addrNe; /* Address of OP_Ne */
drhd4a591d2019-03-26 16:21:11 +00002482 int addrGosubFlush = 0; /* Address of OP_Gosub to flush: */
2483 int addrInteger = 0; /* Address of OP_Integer */
dand4461652019-03-13 08:28:51 +00002484 int addrEmpty; /* Address of OP_Rewind in flush: */
dan54975cd2019-03-07 20:47:46 +00002485 int regStart = 0; /* Value of <expr> PRECEDING */
2486 int regEnd = 0; /* Value of <expr> FOLLOWING */
dana786e452019-03-11 18:17:04 +00002487 int regNew; /* Array of registers holding new input row */
2488 int regRecord; /* regNew array in record form */
2489 int regRowid; /* Rowid for regRecord in eph table */
2490 int regNewPeer = 0; /* Peer values for new row (part of regNew) */
2491 int regPeer = 0; /* Peer values for current row */
dand4461652019-03-13 08:28:51 +00002492 int regFlushPart = 0; /* Register for "Gosub flush_partition" */
dana786e452019-03-11 18:17:04 +00002493 WindowCodeArg s; /* Context object for sub-routines */
dan935d9d82019-03-12 15:21:51 +00002494 int lblWhereEnd; /* Label just before sqlite3WhereEnd() code */
dan680f6e82019-03-04 21:07:11 +00002495
dan72b9fdc2019-03-09 20:49:17 +00002496 assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_CURRENT
2497 || pMWin->eStart==TK_FOLLOWING || pMWin->eStart==TK_UNBOUNDED
2498 );
2499 assert( pMWin->eEnd==TK_FOLLOWING || pMWin->eEnd==TK_CURRENT
2500 || pMWin->eEnd==TK_UNBOUNDED || pMWin->eEnd==TK_PRECEDING
2501 );
dan108e6b22019-03-18 18:55:35 +00002502 assert( pMWin->eExclude==0 || pMWin->eExclude==TK_CURRENT
2503 || pMWin->eExclude==TK_GROUP || pMWin->eExclude==TK_TIES
2504 || pMWin->eExclude==TK_NO
2505 );
dan72b9fdc2019-03-09 20:49:17 +00002506
dan935d9d82019-03-12 15:21:51 +00002507 lblWhereEnd = sqlite3VdbeMakeLabel(pParse);
dana786e452019-03-11 18:17:04 +00002508
2509 /* Fill in the context object */
dan00267b82019-03-06 21:04:11 +00002510 memset(&s, 0, sizeof(WindowCodeArg));
2511 s.pParse = pParse;
2512 s.pMWin = pMWin;
2513 s.pVdbe = v;
2514 s.regGosub = regGosub;
2515 s.addrGosub = addrGosub;
dan6c75b392019-03-08 20:02:52 +00002516 s.current.csr = pMWin->iEphCsr;
dana786e452019-03-11 18:17:04 +00002517 csrWrite = s.current.csr+1;
dan6c75b392019-03-08 20:02:52 +00002518 s.start.csr = s.current.csr+2;
2519 s.end.csr = s.current.csr+3;
danb33487b2019-03-06 17:12:32 +00002520
danb560a712019-03-13 15:29:14 +00002521 /* Figure out when rows may be deleted from the ephemeral table. There
2522 ** are four options - they may never be deleted (eDelete==0), they may
2523 ** be deleted as soon as they are no longer part of the window frame
2524 ** (eDelete==WINDOW_AGGINVERSE), they may be deleted as after the row
2525 ** has been returned to the caller (WINDOW_RETURN_ROW), or they may
2526 ** be deleted after they enter the frame (WINDOW_AGGSTEP). */
2527 switch( pMWin->eStart ){
dan725b1cf2019-03-26 16:47:17 +00002528 case TK_FOLLOWING:
drhfc15f4c2019-03-28 13:03:41 +00002529 if( pMWin->eFrmType!=TK_RANGE
2530 && windowExprGtZero(pParse, pMWin->pStart)
2531 ){
dan725b1cf2019-03-26 16:47:17 +00002532 s.eDelete = WINDOW_RETURN_ROW;
danb560a712019-03-13 15:29:14 +00002533 }
danb560a712019-03-13 15:29:14 +00002534 break;
danb560a712019-03-13 15:29:14 +00002535 case TK_UNBOUNDED:
2536 if( windowCacheFrame(pMWin)==0 ){
2537 if( pMWin->eEnd==TK_PRECEDING ){
drhfc15f4c2019-03-28 13:03:41 +00002538 if( pMWin->eFrmType!=TK_RANGE
2539 && windowExprGtZero(pParse, pMWin->pEnd)
2540 ){
dan725b1cf2019-03-26 16:47:17 +00002541 s.eDelete = WINDOW_AGGSTEP;
2542 }
danb560a712019-03-13 15:29:14 +00002543 }else{
2544 s.eDelete = WINDOW_RETURN_ROW;
2545 }
2546 }
2547 break;
2548 default:
2549 s.eDelete = WINDOW_AGGINVERSE;
2550 break;
2551 }
2552
dand4461652019-03-13 08:28:51 +00002553 /* Allocate registers for the array of values from the sub-query, the
2554 ** samve values in record form, and the rowid used to insert said record
2555 ** into the ephemeral table. */
dana786e452019-03-11 18:17:04 +00002556 regNew = pParse->nMem+1;
2557 pParse->nMem += nInput;
2558 regRecord = ++pParse->nMem;
2559 regRowid = ++pParse->nMem;
dan54975cd2019-03-07 20:47:46 +00002560
dana786e452019-03-11 18:17:04 +00002561 /* If the window frame contains an "<expr> PRECEDING" or "<expr> FOLLOWING"
2562 ** clause, allocate registers to store the results of evaluating each
2563 ** <expr>. */
dan54975cd2019-03-07 20:47:46 +00002564 if( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_FOLLOWING ){
2565 regStart = ++pParse->nMem;
2566 }
2567 if( pMWin->eEnd==TK_PRECEDING || pMWin->eEnd==TK_FOLLOWING ){
2568 regEnd = ++pParse->nMem;
2569 }
dan680f6e82019-03-04 21:07:11 +00002570
dan72b9fdc2019-03-09 20:49:17 +00002571 /* If this is not a "ROWS BETWEEN ..." frame, then allocate arrays of
dana786e452019-03-11 18:17:04 +00002572 ** registers to store copies of the ORDER BY expressions (peer values)
2573 ** for the main loop, and for each cursor (start, current and end). */
drhfc15f4c2019-03-28 13:03:41 +00002574 if( pMWin->eFrmType!=TK_ROWS ){
dan6c75b392019-03-08 20:02:52 +00002575 int nPeer = (pOrderBy ? pOrderBy->nExpr : 0);
dana786e452019-03-11 18:17:04 +00002576 regNewPeer = regNew + pMWin->nBufferCol;
dan6c75b392019-03-08 20:02:52 +00002577 if( pMWin->pPartition ) regNewPeer += pMWin->pPartition->nExpr;
dan6c75b392019-03-08 20:02:52 +00002578 regPeer = pParse->nMem+1; pParse->nMem += nPeer;
2579 s.start.reg = pParse->nMem+1; pParse->nMem += nPeer;
2580 s.current.reg = pParse->nMem+1; pParse->nMem += nPeer;
2581 s.end.reg = pParse->nMem+1; pParse->nMem += nPeer;
2582 }
2583
dan680f6e82019-03-04 21:07:11 +00002584 /* Load the column values for the row returned by the sub-select
dana786e452019-03-11 18:17:04 +00002585 ** into an array of registers starting at regNew. Assemble them into
2586 ** a record in register regRecord. */
2587 for(iInput=0; iInput<nInput; iInput++){
2588 sqlite3VdbeAddOp3(v, OP_Column, csrInput, iInput, regNew+iInput);
dan680f6e82019-03-04 21:07:11 +00002589 }
dana786e452019-03-11 18:17:04 +00002590 sqlite3VdbeAddOp3(v, OP_MakeRecord, regNew, nInput, regRecord);
dan680f6e82019-03-04 21:07:11 +00002591
danb33487b2019-03-06 17:12:32 +00002592 /* An input row has just been read into an array of registers starting
dana786e452019-03-11 18:17:04 +00002593 ** at regNew. If the window has a PARTITION clause, this block generates
danb33487b2019-03-06 17:12:32 +00002594 ** VM code to check if the input row is the start of a new partition.
2595 ** If so, it does an OP_Gosub to an address to be filled in later. The
dana786e452019-03-11 18:17:04 +00002596 ** address of the OP_Gosub is stored in local variable addrGosubFlush. */
dan680f6e82019-03-04 21:07:11 +00002597 if( pMWin->pPartition ){
2598 int addr;
2599 ExprList *pPart = pMWin->pPartition;
2600 int nPart = pPart->nExpr;
dana786e452019-03-11 18:17:04 +00002601 int regNewPart = regNew + pMWin->nBufferCol;
dan680f6e82019-03-04 21:07:11 +00002602 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pPart, 0, 0);
2603
dand4461652019-03-13 08:28:51 +00002604 regFlushPart = ++pParse->nMem;
dan680f6e82019-03-04 21:07:11 +00002605 addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPart, pMWin->regPart, nPart);
2606 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
danb33487b2019-03-06 17:12:32 +00002607 sqlite3VdbeAddOp3(v, OP_Jump, addr+2, addr+4, addr+2);
dan680f6e82019-03-04 21:07:11 +00002608 VdbeCoverageEqNe(v);
2609 addrGosubFlush = sqlite3VdbeAddOp1(v, OP_Gosub, regFlushPart);
2610 VdbeComment((v, "call flush_partition"));
danb33487b2019-03-06 17:12:32 +00002611 sqlite3VdbeAddOp3(v, OP_Copy, regNewPart, pMWin->regPart, nPart-1);
dan680f6e82019-03-04 21:07:11 +00002612 }
2613
2614 /* Insert the new row into the ephemeral table */
2615 sqlite3VdbeAddOp2(v, OP_NewRowid, csrWrite, regRowid);
2616 sqlite3VdbeAddOp3(v, OP_Insert, csrWrite, regRecord, regRowid);
danbf845152019-03-16 10:15:24 +00002617 addrNe = sqlite3VdbeAddOp3(v, OP_Ne, pMWin->regOne, 0, regRowid);
drh83c5bb92019-04-01 15:55:38 +00002618 VdbeCoverageNeverNull(v);
danb25a2142019-03-05 19:29:36 +00002619
danb33487b2019-03-06 17:12:32 +00002620 /* This block is run for the first row of each partition */
dana786e452019-03-11 18:17:04 +00002621 s.regArg = windowInitAccum(pParse, pMWin);
dan680f6e82019-03-04 21:07:11 +00002622
dan54975cd2019-03-07 20:47:46 +00002623 if( regStart ){
2624 sqlite3ExprCode(pParse, pMWin->pStart, regStart);
drhfc15f4c2019-03-28 13:03:41 +00002625 windowCheckValue(pParse, regStart, 0 + (pMWin->eFrmType==TK_RANGE ? 3 : 0));
dan54975cd2019-03-07 20:47:46 +00002626 }
2627 if( regEnd ){
2628 sqlite3ExprCode(pParse, pMWin->pEnd, regEnd);
drhfc15f4c2019-03-28 13:03:41 +00002629 windowCheckValue(pParse, regEnd, 1 + (pMWin->eFrmType==TK_RANGE ? 3 : 0));
dan54975cd2019-03-07 20:47:46 +00002630 }
danb25a2142019-03-05 19:29:36 +00002631
dan0525b6f2019-03-18 21:19:40 +00002632 if( pMWin->eStart==pMWin->eEnd && regStart ){
danb25a2142019-03-05 19:29:36 +00002633 int op = ((pMWin->eStart==TK_FOLLOWING) ? OP_Ge : OP_Le);
2634 int addrGe = sqlite3VdbeAddOp3(v, op, regStart, 0, regEnd);
drh495ed622019-04-01 16:23:21 +00002635 VdbeCoverageNeverNullIf(v, op==OP_Ge); /* NeverNull because bound <expr> */
2636 VdbeCoverageNeverNullIf(v, op==OP_Le); /* values previously checked */
danc782a812019-03-15 20:46:19 +00002637 windowAggFinal(&s, 0);
dancc7a8502019-03-11 19:50:54 +00002638 sqlite3VdbeAddOp2(v, OP_Rewind, s.current.csr, 1);
dan1d4b25f2019-03-19 16:49:15 +00002639 VdbeCoverageNeverTaken(v);
danc782a812019-03-15 20:46:19 +00002640 windowReturnOneRow(&s);
dancc7a8502019-03-11 19:50:54 +00002641 sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr);
dan935d9d82019-03-12 15:21:51 +00002642 sqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd);
danb25a2142019-03-05 19:29:36 +00002643 sqlite3VdbeJumpHere(v, addrGe);
2644 }
drhfc15f4c2019-03-28 13:03:41 +00002645 if( pMWin->eStart==TK_FOLLOWING && pMWin->eFrmType!=TK_RANGE && regEnd ){
dan54975cd2019-03-07 20:47:46 +00002646 assert( pMWin->eEnd==TK_FOLLOWING );
danb25a2142019-03-05 19:29:36 +00002647 sqlite3VdbeAddOp3(v, OP_Subtract, regStart, regEnd, regStart);
2648 }
2649
dan54975cd2019-03-07 20:47:46 +00002650 if( pMWin->eStart!=TK_UNBOUNDED ){
dan6c75b392019-03-08 20:02:52 +00002651 sqlite3VdbeAddOp2(v, OP_Rewind, s.start.csr, 1);
dan1d4b25f2019-03-19 16:49:15 +00002652 VdbeCoverageNeverTaken(v);
dan54975cd2019-03-07 20:47:46 +00002653 }
dan6c75b392019-03-08 20:02:52 +00002654 sqlite3VdbeAddOp2(v, OP_Rewind, s.current.csr, 1);
dan1d4b25f2019-03-19 16:49:15 +00002655 VdbeCoverageNeverTaken(v);
dan6c75b392019-03-08 20:02:52 +00002656 sqlite3VdbeAddOp2(v, OP_Rewind, s.end.csr, 1);
dan1d4b25f2019-03-19 16:49:15 +00002657 VdbeCoverageNeverTaken(v);
dan6c75b392019-03-08 20:02:52 +00002658 if( regPeer && pOrderBy ){
dancc7a8502019-03-11 19:50:54 +00002659 sqlite3VdbeAddOp3(v, OP_Copy, regNewPeer, regPeer, pOrderBy->nExpr-1);
dan6c75b392019-03-08 20:02:52 +00002660 sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.start.reg, pOrderBy->nExpr-1);
2661 sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.current.reg, pOrderBy->nExpr-1);
2662 sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.end.reg, pOrderBy->nExpr-1);
2663 }
danb25a2142019-03-05 19:29:36 +00002664
dan935d9d82019-03-12 15:21:51 +00002665 sqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd);
dan680f6e82019-03-04 21:07:11 +00002666
danbf845152019-03-16 10:15:24 +00002667 sqlite3VdbeJumpHere(v, addrNe);
dan3f49c322019-04-03 16:27:44 +00002668
2669 /* Beginning of the block executed for the second and subsequent rows. */
dan6c75b392019-03-08 20:02:52 +00002670 if( regPeer ){
dan935d9d82019-03-12 15:21:51 +00002671 windowIfNewPeer(pParse, pOrderBy, regNewPeer, regPeer, lblWhereEnd);
dan6c75b392019-03-08 20:02:52 +00002672 }
danb25a2142019-03-05 19:29:36 +00002673 if( pMWin->eStart==TK_FOLLOWING ){
dan6c75b392019-03-08 20:02:52 +00002674 windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
dan54975cd2019-03-07 20:47:46 +00002675 if( pMWin->eEnd!=TK_UNBOUNDED ){
drhfc15f4c2019-03-28 13:03:41 +00002676 if( pMWin->eFrmType==TK_RANGE ){
dan72b9fdc2019-03-09 20:49:17 +00002677 int lbl = sqlite3VdbeMakeLabel(pParse);
2678 int addrNext = sqlite3VdbeCurrentAddr(v);
2679 windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl);
2680 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2681 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
2682 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNext);
2683 sqlite3VdbeResolveLabel(v, lbl);
2684 }else{
2685 windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 0);
2686 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2687 }
dan54975cd2019-03-07 20:47:46 +00002688 }
danb25a2142019-03-05 19:29:36 +00002689 }else
2690 if( pMWin->eEnd==TK_PRECEDING ){
dan3f49c322019-04-03 16:27:44 +00002691 int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE);
dan6c75b392019-03-08 20:02:52 +00002692 windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0);
dan3f49c322019-04-03 16:27:44 +00002693 if( bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
dan6c75b392019-03-08 20:02:52 +00002694 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
dan3f49c322019-04-03 16:27:44 +00002695 if( !bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
danb25a2142019-03-05 19:29:36 +00002696 }else{
mistachkinba9ee092019-03-27 14:58:18 +00002697 int addr = 0;
dan6c75b392019-03-08 20:02:52 +00002698 windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
dan54975cd2019-03-07 20:47:46 +00002699 if( pMWin->eEnd!=TK_UNBOUNDED ){
drhfc15f4c2019-03-28 13:03:41 +00002700 if( pMWin->eFrmType==TK_RANGE ){
mistachkinba9ee092019-03-27 14:58:18 +00002701 int lbl = 0;
dan72b9fdc2019-03-09 20:49:17 +00002702 addr = sqlite3VdbeCurrentAddr(v);
2703 if( regEnd ){
2704 lbl = sqlite3VdbeMakeLabel(pParse);
2705 windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl);
2706 }
2707 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
2708 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2709 if( regEnd ){
2710 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
2711 sqlite3VdbeResolveLabel(v, lbl);
2712 }
2713 }else{
dan1d4b25f2019-03-19 16:49:15 +00002714 if( regEnd ){
2715 addr = sqlite3VdbeAddOp3(v, OP_IfPos, regEnd, 0, 1);
2716 VdbeCoverage(v);
2717 }
dan72b9fdc2019-03-09 20:49:17 +00002718 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
2719 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
2720 if( regEnd ) sqlite3VdbeJumpHere(v, addr);
2721 }
dan54975cd2019-03-07 20:47:46 +00002722 }
danb25a2142019-03-05 19:29:36 +00002723 }
dan680f6e82019-03-04 21:07:11 +00002724
dan680f6e82019-03-04 21:07:11 +00002725 /* End of the main input loop */
dan935d9d82019-03-12 15:21:51 +00002726 sqlite3VdbeResolveLabel(v, lblWhereEnd);
dancc7a8502019-03-11 19:50:54 +00002727 sqlite3WhereEnd(pWInfo);
dan680f6e82019-03-04 21:07:11 +00002728
2729 /* Fall through */
dancc7a8502019-03-11 19:50:54 +00002730 if( pMWin->pPartition ){
dan680f6e82019-03-04 21:07:11 +00002731 addrInteger = sqlite3VdbeAddOp2(v, OP_Integer, 0, regFlushPart);
2732 sqlite3VdbeJumpHere(v, addrGosubFlush);
2733 }
2734
danc8137502019-03-07 19:26:17 +00002735 addrEmpty = sqlite3VdbeAddOp1(v, OP_Rewind, csrWrite);
dan1d4b25f2019-03-19 16:49:15 +00002736 VdbeCoverage(v);
dan00267b82019-03-06 21:04:11 +00002737 if( pMWin->eEnd==TK_PRECEDING ){
dan3f49c322019-04-03 16:27:44 +00002738 int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE);
dan6c75b392019-03-08 20:02:52 +00002739 windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0);
dan3f49c322019-04-03 16:27:44 +00002740 if( bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
dan6c75b392019-03-08 20:02:52 +00002741 windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
danc8137502019-03-07 19:26:17 +00002742 }else if( pMWin->eStart==TK_FOLLOWING ){
2743 int addrStart;
2744 int addrBreak1;
2745 int addrBreak2;
2746 int addrBreak3;
dan6c75b392019-03-08 20:02:52 +00002747 windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
drhfc15f4c2019-03-28 13:03:41 +00002748 if( pMWin->eFrmType==TK_RANGE ){
dan72b9fdc2019-03-09 20:49:17 +00002749 addrStart = sqlite3VdbeCurrentAddr(v);
2750 addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1);
2751 addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
2752 }else
dan54975cd2019-03-07 20:47:46 +00002753 if( pMWin->eEnd==TK_UNBOUNDED ){
2754 addrStart = sqlite3VdbeCurrentAddr(v);
dan6c75b392019-03-08 20:02:52 +00002755 addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regStart, 1);
2756 addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, 0, 1);
dan54975cd2019-03-07 20:47:46 +00002757 }else{
2758 assert( pMWin->eEnd==TK_FOLLOWING );
2759 addrStart = sqlite3VdbeCurrentAddr(v);
dan6c75b392019-03-08 20:02:52 +00002760 addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 1);
2761 addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1);
dan54975cd2019-03-07 20:47:46 +00002762 }
danc8137502019-03-07 19:26:17 +00002763 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
2764 sqlite3VdbeJumpHere(v, addrBreak2);
2765 addrStart = sqlite3VdbeCurrentAddr(v);
dan6c75b392019-03-08 20:02:52 +00002766 addrBreak3 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
danc8137502019-03-07 19:26:17 +00002767 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
2768 sqlite3VdbeJumpHere(v, addrBreak1);
2769 sqlite3VdbeJumpHere(v, addrBreak3);
danb25a2142019-03-05 19:29:36 +00002770 }else{
dan00267b82019-03-06 21:04:11 +00002771 int addrBreak;
danc8137502019-03-07 19:26:17 +00002772 int addrStart;
dan6c75b392019-03-08 20:02:52 +00002773 windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
danc8137502019-03-07 19:26:17 +00002774 addrStart = sqlite3VdbeCurrentAddr(v);
dan6c75b392019-03-08 20:02:52 +00002775 addrBreak = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
2776 windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
dan00267b82019-03-06 21:04:11 +00002777 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
2778 sqlite3VdbeJumpHere(v, addrBreak);
danb25a2142019-03-05 19:29:36 +00002779 }
danc8137502019-03-07 19:26:17 +00002780 sqlite3VdbeJumpHere(v, addrEmpty);
2781
dan6c75b392019-03-08 20:02:52 +00002782 sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr);
dan680f6e82019-03-04 21:07:11 +00002783 if( pMWin->pPartition ){
dana0f6b832019-03-14 16:36:20 +00002784 if( pMWin->regStartRowid ){
2785 sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid);
2786 sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid);
2787 }
dan680f6e82019-03-04 21:07:11 +00002788 sqlite3VdbeChangeP1(v, addrInteger, sqlite3VdbeCurrentAddr(v));
2789 sqlite3VdbeAddOp1(v, OP_Return, regFlushPart);
2790 }
2791}
2792
dan67a9b8e2018-06-22 20:51:35 +00002793#endif /* SQLITE_OMIT_WINDOWFUNC */