blob: ce51de790f1d31190afa5079be1b663be2ca9a9a [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/*
dan9c277582018-06-20 09:23:49 +0000202** Implementation of built-in window function rank(). Assumes that
203** the window frame has been set to:
204**
205** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
dandfa552f2018-06-02 21:04:28 +0000206*/
207static void rankStepFunc(
208 sqlite3_context *pCtx,
209 int nArg,
210 sqlite3_value **apArg
211){
212 struct CallCount *p;
213 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
drh5d6374f2018-07-10 23:31:17 +0000214 if( p ){
dandfa552f2018-06-02 21:04:28 +0000215 p->nStep++;
216 if( p->nValue==0 ){
217 p->nValue = p->nStep;
218 }
219 }
drhc7bf5712018-07-09 22:49:01 +0000220 UNUSED_PARAMETER(nArg);
221 UNUSED_PARAMETER(apArg);
dandfa552f2018-06-02 21:04:28 +0000222}
dandfa552f2018-06-02 21:04:28 +0000223static void rankValueFunc(sqlite3_context *pCtx){
224 struct CallCount *p;
225 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
226 if( p ){
227 sqlite3_result_int64(pCtx, p->nValue);
228 p->nValue = 0;
229 }
230}
231
232/*
dan9c277582018-06-20 09:23:49 +0000233** Implementation of built-in window function percent_rank(). Assumes that
234** the window frame has been set to:
235**
236** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
dandfa552f2018-06-02 21:04:28 +0000237*/
238static void percent_rankStepFunc(
239 sqlite3_context *pCtx,
240 int nArg,
241 sqlite3_value **apArg
242){
243 struct CallCount *p;
drhc7bf5712018-07-09 22:49:01 +0000244 UNUSED_PARAMETER(nArg); assert( nArg==1 );
dandfa552f2018-06-02 21:04:28 +0000245
246 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
drh5d6374f2018-07-10 23:31:17 +0000247 if( p ){
dandfa552f2018-06-02 21:04:28 +0000248 if( p->nTotal==0 ){
249 p->nTotal = sqlite3_value_int64(apArg[0]);
250 }
251 p->nStep++;
252 if( p->nValue==0 ){
253 p->nValue = p->nStep;
254 }
255 }
256}
dandfa552f2018-06-02 21:04:28 +0000257static void percent_rankValueFunc(sqlite3_context *pCtx){
258 struct CallCount *p;
259 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
260 if( p ){
261 if( p->nTotal>1 ){
262 double r = (double)(p->nValue-1) / (double)(p->nTotal-1);
263 sqlite3_result_double(pCtx, r);
264 }else{
danb7306f62018-06-21 19:20:39 +0000265 sqlite3_result_double(pCtx, 0.0);
dandfa552f2018-06-02 21:04:28 +0000266 }
267 p->nValue = 0;
268 }
269}
270
dan9c277582018-06-20 09:23:49 +0000271/*
272** Implementation of built-in window function cume_dist(). Assumes that
273** the window frame has been set to:
274**
275** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
276*/
danf1abe362018-06-04 08:22:09 +0000277static void cume_distStepFunc(
278 sqlite3_context *pCtx,
279 int nArg,
280 sqlite3_value **apArg
281){
282 struct CallCount *p;
drhc7bf5712018-07-09 22:49:01 +0000283 assert( nArg==1 ); UNUSED_PARAMETER(nArg);
danf1abe362018-06-04 08:22:09 +0000284
285 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
drh5d6374f2018-07-10 23:31:17 +0000286 if( p ){
danf1abe362018-06-04 08:22:09 +0000287 if( p->nTotal==0 ){
288 p->nTotal = sqlite3_value_int64(apArg[0]);
289 }
290 p->nStep++;
291 }
292}
danf1abe362018-06-04 08:22:09 +0000293static void cume_distValueFunc(sqlite3_context *pCtx){
294 struct CallCount *p;
295 p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
dan660af932018-06-18 16:55:22 +0000296 if( p && p->nTotal ){
danf1abe362018-06-04 08:22:09 +0000297 double r = (double)(p->nStep) / (double)(p->nTotal);
298 sqlite3_result_double(pCtx, r);
299 }
300}
301
dan2a11bb22018-06-11 20:50:25 +0000302/*
303** Context object for ntile() window function.
304*/
dan6bc5c9e2018-06-04 18:55:11 +0000305struct NtileCtx {
306 i64 nTotal; /* Total rows in partition */
307 i64 nParam; /* Parameter passed to ntile(N) */
308 i64 iRow; /* Current row */
309};
310
311/*
312** Implementation of ntile(). This assumes that the window frame has
313** been coerced to:
314**
315** ROWS UNBOUNDED PRECEDING AND CURRENT ROW
dan6bc5c9e2018-06-04 18:55:11 +0000316*/
317static void ntileStepFunc(
318 sqlite3_context *pCtx,
319 int nArg,
320 sqlite3_value **apArg
321){
322 struct NtileCtx *p;
drhc7bf5712018-07-09 22:49:01 +0000323 assert( nArg==2 ); UNUSED_PARAMETER(nArg);
dan6bc5c9e2018-06-04 18:55:11 +0000324 p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
drh5d6374f2018-07-10 23:31:17 +0000325 if( p ){
dan6bc5c9e2018-06-04 18:55:11 +0000326 if( p->nTotal==0 ){
327 p->nParam = sqlite3_value_int64(apArg[0]);
328 p->nTotal = sqlite3_value_int64(apArg[1]);
329 if( p->nParam<=0 ){
330 sqlite3_result_error(
331 pCtx, "argument of ntile must be a positive integer", -1
332 );
333 }
334 }
335 p->iRow++;
336 }
337}
dan6bc5c9e2018-06-04 18:55:11 +0000338static void ntileValueFunc(sqlite3_context *pCtx){
339 struct NtileCtx *p;
340 p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
341 if( p && p->nParam>0 ){
342 int nSize = (p->nTotal / p->nParam);
343 if( nSize==0 ){
344 sqlite3_result_int64(pCtx, p->iRow);
345 }else{
346 i64 nLarge = p->nTotal - p->nParam*nSize;
347 i64 iSmall = nLarge*(nSize+1);
348 i64 iRow = p->iRow-1;
349
350 assert( (nLarge*(nSize+1) + (p->nParam-nLarge)*nSize)==p->nTotal );
351
352 if( iRow<iSmall ){
353 sqlite3_result_int64(pCtx, 1 + iRow/(nSize+1));
354 }else{
355 sqlite3_result_int64(pCtx, 1 + nLarge + (iRow-iSmall)/nSize);
356 }
357 }
358 }
359}
360
dan2a11bb22018-06-11 20:50:25 +0000361/*
362** Context object for last_value() window function.
363*/
dan1c5ed622018-06-05 16:16:17 +0000364struct LastValueCtx {
365 sqlite3_value *pVal;
366 int nVal;
367};
368
369/*
370** Implementation of last_value().
371*/
372static void last_valueStepFunc(
373 sqlite3_context *pCtx,
374 int nArg,
375 sqlite3_value **apArg
376){
377 struct LastValueCtx *p;
drhc7bf5712018-07-09 22:49:01 +0000378 UNUSED_PARAMETER(nArg);
dan9c277582018-06-20 09:23:49 +0000379 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
dan1c5ed622018-06-05 16:16:17 +0000380 if( p ){
381 sqlite3_value_free(p->pVal);
382 p->pVal = sqlite3_value_dup(apArg[0]);
dan6fde1792018-06-15 19:01:35 +0000383 if( p->pVal==0 ){
384 sqlite3_result_error_nomem(pCtx);
385 }else{
386 p->nVal++;
387 }
dan1c5ed622018-06-05 16:16:17 +0000388 }
389}
dan2a11bb22018-06-11 20:50:25 +0000390static void last_valueInvFunc(
dan1c5ed622018-06-05 16:16:17 +0000391 sqlite3_context *pCtx,
392 int nArg,
393 sqlite3_value **apArg
394){
395 struct LastValueCtx *p;
drhc7bf5712018-07-09 22:49:01 +0000396 UNUSED_PARAMETER(nArg);
397 UNUSED_PARAMETER(apArg);
dan9c277582018-06-20 09:23:49 +0000398 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
399 if( ALWAYS(p) ){
dan1c5ed622018-06-05 16:16:17 +0000400 p->nVal--;
401 if( p->nVal==0 ){
402 sqlite3_value_free(p->pVal);
403 p->pVal = 0;
404 }
405 }
406}
407static void last_valueValueFunc(sqlite3_context *pCtx){
408 struct LastValueCtx *p;
dan9c277582018-06-20 09:23:49 +0000409 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
dan1c5ed622018-06-05 16:16:17 +0000410 if( p && p->pVal ){
411 sqlite3_result_value(pCtx, p->pVal);
412 }
413}
414static void last_valueFinalizeFunc(sqlite3_context *pCtx){
415 struct LastValueCtx *p;
dan9c277582018-06-20 09:23:49 +0000416 p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
dan1c5ed622018-06-05 16:16:17 +0000417 if( p && p->pVal ){
418 sqlite3_result_value(pCtx, p->pVal);
419 sqlite3_value_free(p->pVal);
420 p->pVal = 0;
421 }
422}
423
dan2a11bb22018-06-11 20:50:25 +0000424/*
drh19dc4d42018-07-08 01:02:26 +0000425** Static names for the built-in window function names. These static
426** names are used, rather than string literals, so that FuncDef objects
427** can be associated with a particular window function by direct
428** comparison of the zName pointer. Example:
429**
430** if( pFuncDef->zName==row_valueName ){ ... }
dan2a11bb22018-06-11 20:50:25 +0000431*/
drh19dc4d42018-07-08 01:02:26 +0000432static const char row_numberName[] = "row_number";
433static const char dense_rankName[] = "dense_rank";
434static const char rankName[] = "rank";
435static const char percent_rankName[] = "percent_rank";
436static const char cume_distName[] = "cume_dist";
437static const char ntileName[] = "ntile";
438static const char last_valueName[] = "last_value";
439static const char nth_valueName[] = "nth_value";
440static const char first_valueName[] = "first_value";
441static const char leadName[] = "lead";
442static const char lagName[] = "lag";
danfe4e25a2018-06-07 20:08:59 +0000443
drh19dc4d42018-07-08 01:02:26 +0000444/*
445** No-op implementations of xStep() and xFinalize(). Used as place-holders
446** for built-in window functions that never call those interfaces.
447**
448** The noopValueFunc() is called but is expected to do nothing. The
449** noopStepFunc() is never called, and so it is marked with NO_TEST to
450** let the test coverage routine know not to expect this function to be
451** invoked.
452*/
453static void noopStepFunc( /*NO_TEST*/
454 sqlite3_context *p, /*NO_TEST*/
455 int n, /*NO_TEST*/
456 sqlite3_value **a /*NO_TEST*/
457){ /*NO_TEST*/
drhc7bf5712018-07-09 22:49:01 +0000458 UNUSED_PARAMETER(p); /*NO_TEST*/
459 UNUSED_PARAMETER(n); /*NO_TEST*/
460 UNUSED_PARAMETER(a); /*NO_TEST*/
drh19dc4d42018-07-08 01:02:26 +0000461 assert(0); /*NO_TEST*/
462} /*NO_TEST*/
drhc7bf5712018-07-09 22:49:01 +0000463static void noopValueFunc(sqlite3_context *p){ UNUSED_PARAMETER(p); /*no-op*/ }
dandfa552f2018-06-02 21:04:28 +0000464
drh19dc4d42018-07-08 01:02:26 +0000465/* Window functions that use all window interfaces: xStep, xFinal,
466** xValue, and xInverse */
467#define WINDOWFUNCALL(name,nArg,extra) { \
dan1c5ed622018-06-05 16:16:17 +0000468 nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
469 name ## StepFunc, name ## FinalizeFunc, name ## ValueFunc, \
drhc7bf5712018-07-09 22:49:01 +0000470 name ## InvFunc, name ## Name, {0} \
dan1c5ed622018-06-05 16:16:17 +0000471}
472
drh19dc4d42018-07-08 01:02:26 +0000473/* Window functions that are implemented using bytecode and thus have
474** no-op routines for their methods */
475#define WINDOWFUNCNOOP(name,nArg,extra) { \
476 nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
477 noopStepFunc, noopValueFunc, noopValueFunc, \
drhc7bf5712018-07-09 22:49:01 +0000478 noopStepFunc, name ## Name, {0} \
drh19dc4d42018-07-08 01:02:26 +0000479}
480
481/* Window functions that use all window interfaces: xStep, the
482** same routine for xFinalize and xValue and which never call
483** xInverse. */
484#define WINDOWFUNCX(name,nArg,extra) { \
485 nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
486 name ## StepFunc, name ## ValueFunc, name ## ValueFunc, \
drhc7bf5712018-07-09 22:49:01 +0000487 noopStepFunc, name ## Name, {0} \
drh19dc4d42018-07-08 01:02:26 +0000488}
489
490
dandfa552f2018-06-02 21:04:28 +0000491/*
492** Register those built-in window functions that are not also aggregates.
493*/
494void sqlite3WindowFunctions(void){
495 static FuncDef aWindowFuncs[] = {
drh19dc4d42018-07-08 01:02:26 +0000496 WINDOWFUNCX(row_number, 0, 0),
497 WINDOWFUNCX(dense_rank, 0, 0),
498 WINDOWFUNCX(rank, 0, 0),
499 WINDOWFUNCX(percent_rank, 0, SQLITE_FUNC_WINDOW_SIZE),
500 WINDOWFUNCX(cume_dist, 0, SQLITE_FUNC_WINDOW_SIZE),
501 WINDOWFUNCX(ntile, 1, SQLITE_FUNC_WINDOW_SIZE),
502 WINDOWFUNCALL(last_value, 1, 0),
503 WINDOWFUNCNOOP(nth_value, 2, 0),
504 WINDOWFUNCNOOP(first_value, 1, 0),
505 WINDOWFUNCNOOP(lead, 1, 0),
506 WINDOWFUNCNOOP(lead, 2, 0),
507 WINDOWFUNCNOOP(lead, 3, 0),
508 WINDOWFUNCNOOP(lag, 1, 0),
509 WINDOWFUNCNOOP(lag, 2, 0),
510 WINDOWFUNCNOOP(lag, 3, 0),
dandfa552f2018-06-02 21:04:28 +0000511 };
512 sqlite3InsertBuiltinFuncs(aWindowFuncs, ArraySize(aWindowFuncs));
513}
514
danc0bb4452018-06-12 20:53:38 +0000515/*
516** This function is called immediately after resolving the function name
517** for a window function within a SELECT statement. Argument pList is a
518** linked list of WINDOW definitions for the current SELECT statement.
519** Argument pFunc is the function definition just resolved and pWin
520** is the Window object representing the associated OVER clause. This
521** function updates the contents of pWin as follows:
522**
523** * If the OVER clause refered to a named window (as in "max(x) OVER win"),
524** search list pList for a matching WINDOW definition, and update pWin
525** accordingly. If no such WINDOW clause can be found, leave an error
526** in pParse.
527**
528** * If the function is a built-in window function that requires the
529** window to be coerced (see "BUILT-IN WINDOW FUNCTIONS" at the top
530** of this file), pWin is updated here.
531*/
dane3bf6322018-06-08 20:58:27 +0000532void sqlite3WindowUpdate(
533 Parse *pParse,
danc0bb4452018-06-12 20:53:38 +0000534 Window *pList, /* List of named windows for this SELECT */
535 Window *pWin, /* Window frame to update */
536 FuncDef *pFunc /* Window function definition */
dane3bf6322018-06-08 20:58:27 +0000537){
danc95f38d2018-06-18 20:34:43 +0000538 if( pWin->zName && pWin->eType==0 ){
dane3bf6322018-06-08 20:58:27 +0000539 Window *p;
540 for(p=pList; p; p=p->pNextWin){
541 if( sqlite3StrICmp(p->zName, pWin->zName)==0 ) break;
542 }
543 if( p==0 ){
544 sqlite3ErrorMsg(pParse, "no such window: %s", pWin->zName);
545 return;
546 }
547 pWin->pPartition = sqlite3ExprListDup(pParse->db, p->pPartition, 0);
548 pWin->pOrderBy = sqlite3ExprListDup(pParse->db, p->pOrderBy, 0);
549 pWin->pStart = sqlite3ExprDup(pParse->db, p->pStart, 0);
550 pWin->pEnd = sqlite3ExprDup(pParse->db, p->pEnd, 0);
551 pWin->eStart = p->eStart;
552 pWin->eEnd = p->eEnd;
danc95f38d2018-06-18 20:34:43 +0000553 pWin->eType = p->eType;
dane3bf6322018-06-08 20:58:27 +0000554 }
dandfa552f2018-06-02 21:04:28 +0000555 if( pFunc->funcFlags & SQLITE_FUNC_WINDOW ){
556 sqlite3 *db = pParse->db;
dan8b985602018-06-09 17:43:45 +0000557 if( pWin->pFilter ){
558 sqlite3ErrorMsg(pParse,
559 "FILTER clause may only be used with aggregate window functions"
560 );
561 }else
drh19dc4d42018-07-08 01:02:26 +0000562 if( pFunc->zName==row_numberName || pFunc->zName==ntileName ){
dandfa552f2018-06-02 21:04:28 +0000563 sqlite3ExprDelete(db, pWin->pStart);
564 sqlite3ExprDelete(db, pWin->pEnd);
565 pWin->pStart = pWin->pEnd = 0;
566 pWin->eType = TK_ROWS;
567 pWin->eStart = TK_UNBOUNDED;
568 pWin->eEnd = TK_CURRENT;
dan8b985602018-06-09 17:43:45 +0000569 }else
dandfa552f2018-06-02 21:04:28 +0000570
drh19dc4d42018-07-08 01:02:26 +0000571 if( pFunc->zName==dense_rankName || pFunc->zName==rankName
572 || pFunc->zName==percent_rankName || pFunc->zName==cume_distName
dandfa552f2018-06-02 21:04:28 +0000573 ){
574 sqlite3ExprDelete(db, pWin->pStart);
575 sqlite3ExprDelete(db, pWin->pEnd);
576 pWin->pStart = pWin->pEnd = 0;
577 pWin->eType = TK_RANGE;
578 pWin->eStart = TK_UNBOUNDED;
579 pWin->eEnd = TK_CURRENT;
580 }
581 }
dan2a11bb22018-06-11 20:50:25 +0000582 pWin->pFunc = pFunc;
dandfa552f2018-06-02 21:04:28 +0000583}
584
danc0bb4452018-06-12 20:53:38 +0000585/*
586** Context object passed through sqlite3WalkExprList() to
587** selectWindowRewriteExprCb() by selectWindowRewriteEList().
588*/
dandfa552f2018-06-02 21:04:28 +0000589typedef struct WindowRewrite WindowRewrite;
590struct WindowRewrite {
591 Window *pWin;
danb556f262018-07-10 17:26:12 +0000592 SrcList *pSrc;
dandfa552f2018-06-02 21:04:28 +0000593 ExprList *pSub;
danb556f262018-07-10 17:26:12 +0000594 Select *pSubSelect; /* Current sub-select, if any */
dandfa552f2018-06-02 21:04:28 +0000595};
596
danc0bb4452018-06-12 20:53:38 +0000597/*
598** Callback function used by selectWindowRewriteEList(). If necessary,
599** this function appends to the output expression-list and updates
600** expression (*ppExpr) in place.
601*/
dandfa552f2018-06-02 21:04:28 +0000602static int selectWindowRewriteExprCb(Walker *pWalker, Expr *pExpr){
603 struct WindowRewrite *p = pWalker->u.pRewrite;
604 Parse *pParse = pWalker->pParse;
605
danb556f262018-07-10 17:26:12 +0000606 /* If this function is being called from within a scalar sub-select
607 ** that used by the SELECT statement being processed, only process
608 ** TK_COLUMN expressions that refer to it (the outer SELECT). Do
609 ** not process aggregates or window functions at all, as they belong
610 ** to the scalar sub-select. */
611 if( p->pSubSelect ){
612 if( pExpr->op!=TK_COLUMN ){
613 return WRC_Continue;
614 }else{
615 int nSrc = p->pSrc->nSrc;
616 int i;
617 for(i=0; i<nSrc; i++){
618 if( pExpr->iTable==p->pSrc->a[i].iCursor ) break;
619 }
620 if( i==nSrc ) return WRC_Continue;
621 }
622 }
623
dandfa552f2018-06-02 21:04:28 +0000624 switch( pExpr->op ){
625
626 case TK_FUNCTION:
627 if( pExpr->pWin==0 ){
628 break;
629 }else{
630 Window *pWin;
631 for(pWin=p->pWin; pWin; pWin=pWin->pNextWin){
632 if( pExpr->pWin==pWin ){
dan2a11bb22018-06-11 20:50:25 +0000633 assert( pWin->pOwner==pExpr );
dandfa552f2018-06-02 21:04:28 +0000634 return WRC_Prune;
635 }
636 }
637 }
638 /* Fall through. */
639
dan73925692018-06-12 18:40:17 +0000640 case TK_AGG_FUNCTION:
dandfa552f2018-06-02 21:04:28 +0000641 case TK_COLUMN: {
642 Expr *pDup = sqlite3ExprDup(pParse->db, pExpr, 0);
643 p->pSub = sqlite3ExprListAppend(pParse, p->pSub, pDup);
644 if( p->pSub ){
645 assert( ExprHasProperty(pExpr, EP_Static)==0 );
646 ExprSetProperty(pExpr, EP_Static);
647 sqlite3ExprDelete(pParse->db, pExpr);
648 ExprClearProperty(pExpr, EP_Static);
649 memset(pExpr, 0, sizeof(Expr));
650
651 pExpr->op = TK_COLUMN;
652 pExpr->iColumn = p->pSub->nExpr-1;
653 pExpr->iTable = p->pWin->iEphCsr;
654 }
655
656 break;
657 }
658
659 default: /* no-op */
660 break;
661 }
662
663 return WRC_Continue;
664}
danc0bb4452018-06-12 20:53:38 +0000665static int selectWindowRewriteSelectCb(Walker *pWalker, Select *pSelect){
danb556f262018-07-10 17:26:12 +0000666 struct WindowRewrite *p = pWalker->u.pRewrite;
667 Select *pSave = p->pSubSelect;
668 if( pSave==pSelect ){
669 return WRC_Continue;
670 }else{
671 p->pSubSelect = pSelect;
672 sqlite3WalkSelect(pWalker, pSelect);
673 p->pSubSelect = pSave;
674 }
danc0bb4452018-06-12 20:53:38 +0000675 return WRC_Prune;
676}
dandfa552f2018-06-02 21:04:28 +0000677
danc0bb4452018-06-12 20:53:38 +0000678
679/*
680** Iterate through each expression in expression-list pEList. For each:
681**
682** * TK_COLUMN,
683** * aggregate function, or
684** * window function with a Window object that is not a member of the
danb556f262018-07-10 17:26:12 +0000685** Window list passed as the second argument (pWin).
danc0bb4452018-06-12 20:53:38 +0000686**
687** Append the node to output expression-list (*ppSub). And replace it
688** with a TK_COLUMN that reads the (N-1)th element of table
689** pWin->iEphCsr, where N is the number of elements in (*ppSub) after
690** appending the new one.
691*/
dan13b08bb2018-06-15 20:46:12 +0000692static void selectWindowRewriteEList(
dandfa552f2018-06-02 21:04:28 +0000693 Parse *pParse,
694 Window *pWin,
danb556f262018-07-10 17:26:12 +0000695 SrcList *pSrc,
dandfa552f2018-06-02 21:04:28 +0000696 ExprList *pEList, /* Rewrite expressions in this list */
697 ExprList **ppSub /* IN/OUT: Sub-select expression-list */
698){
699 Walker sWalker;
700 WindowRewrite sRewrite;
dandfa552f2018-06-02 21:04:28 +0000701
702 memset(&sWalker, 0, sizeof(Walker));
703 memset(&sRewrite, 0, sizeof(WindowRewrite));
704
705 sRewrite.pSub = *ppSub;
706 sRewrite.pWin = pWin;
danb556f262018-07-10 17:26:12 +0000707 sRewrite.pSrc = pSrc;
dandfa552f2018-06-02 21:04:28 +0000708
709 sWalker.pParse = pParse;
710 sWalker.xExprCallback = selectWindowRewriteExprCb;
711 sWalker.xSelectCallback = selectWindowRewriteSelectCb;
712 sWalker.u.pRewrite = &sRewrite;
713
dan13b08bb2018-06-15 20:46:12 +0000714 (void)sqlite3WalkExprList(&sWalker, pEList);
dandfa552f2018-06-02 21:04:28 +0000715
716 *ppSub = sRewrite.pSub;
dandfa552f2018-06-02 21:04:28 +0000717}
718
danc0bb4452018-06-12 20:53:38 +0000719/*
720** Append a copy of each expression in expression-list pAppend to
721** expression list pList. Return a pointer to the result list.
722*/
dandfa552f2018-06-02 21:04:28 +0000723static ExprList *exprListAppendList(
724 Parse *pParse, /* Parsing context */
725 ExprList *pList, /* List to which to append. Might be NULL */
726 ExprList *pAppend /* List of values to append. Might be NULL */
727){
728 if( pAppend ){
729 int i;
730 int nInit = pList ? pList->nExpr : 0;
731 for(i=0; i<pAppend->nExpr; i++){
732 Expr *pDup = sqlite3ExprDup(pParse->db, pAppend->a[i].pExpr, 0);
733 pList = sqlite3ExprListAppend(pParse, pList, pDup);
734 if( pList ) pList->a[nInit+i].sortOrder = pAppend->a[i].sortOrder;
735 }
736 }
737 return pList;
738}
739
740/*
741** If the SELECT statement passed as the second argument does not invoke
742** any SQL window functions, this function is a no-op. Otherwise, it
743** rewrites the SELECT statement so that window function xStep functions
danc0bb4452018-06-12 20:53:38 +0000744** are invoked in the correct order as described under "SELECT REWRITING"
745** at the top of this file.
dandfa552f2018-06-02 21:04:28 +0000746*/
747int sqlite3WindowRewrite(Parse *pParse, Select *p){
748 int rc = SQLITE_OK;
749 if( p->pWin ){
750 Vdbe *v = sqlite3GetVdbe(pParse);
dandfa552f2018-06-02 21:04:28 +0000751 sqlite3 *db = pParse->db;
752 Select *pSub = 0; /* The subquery */
753 SrcList *pSrc = p->pSrc;
754 Expr *pWhere = p->pWhere;
755 ExprList *pGroupBy = p->pGroupBy;
756 Expr *pHaving = p->pHaving;
757 ExprList *pSort = 0;
758
759 ExprList *pSublist = 0; /* Expression list for sub-query */
760 Window *pMWin = p->pWin; /* Master window object */
761 Window *pWin; /* Window object iterator */
762
763 p->pSrc = 0;
764 p->pWhere = 0;
765 p->pGroupBy = 0;
766 p->pHaving = 0;
767
danf02cdd32018-06-27 19:48:50 +0000768 /* Create the ORDER BY clause for the sub-select. This is the concatenation
769 ** of the window PARTITION and ORDER BY clauses. Then, if this makes it
770 ** redundant, remove the ORDER BY from the parent SELECT. */
771 pSort = sqlite3ExprListDup(db, pMWin->pPartition, 0);
772 pSort = exprListAppendList(pParse, pSort, pMWin->pOrderBy);
773 if( pSort && p->pOrderBy ){
774 if( sqlite3ExprListCompare(pSort, p->pOrderBy, -1)==0 ){
775 sqlite3ExprListDelete(db, p->pOrderBy);
776 p->pOrderBy = 0;
777 }
778 }
779
dandfa552f2018-06-02 21:04:28 +0000780 /* Assign a cursor number for the ephemeral table used to buffer rows.
781 ** The OpenEphemeral instruction is coded later, after it is known how
782 ** many columns the table will have. */
783 pMWin->iEphCsr = pParse->nTab++;
784
danb556f262018-07-10 17:26:12 +0000785 selectWindowRewriteEList(pParse, pMWin, pSrc, p->pEList, &pSublist);
786 selectWindowRewriteEList(pParse, pMWin, pSrc, p->pOrderBy, &pSublist);
dandfa552f2018-06-02 21:04:28 +0000787 pMWin->nBufferCol = (pSublist ? pSublist->nExpr : 0);
788
danf02cdd32018-06-27 19:48:50 +0000789 /* Append the PARTITION BY and ORDER BY expressions to the to the
790 ** sub-select expression list. They are required to figure out where
791 ** boundaries for partitions and sets of peer rows lie. */
792 pSublist = exprListAppendList(pParse, pSublist, pMWin->pPartition);
793 pSublist = exprListAppendList(pParse, pSublist, pMWin->pOrderBy);
dandfa552f2018-06-02 21:04:28 +0000794
795 /* Append the arguments passed to each window function to the
796 ** sub-select expression list. Also allocate two registers for each
797 ** window function - one for the accumulator, another for interim
798 ** results. */
799 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
800 pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);
801 pSublist = exprListAppendList(pParse, pSublist, pWin->pOwner->x.pList);
dan8b985602018-06-09 17:43:45 +0000802 if( pWin->pFilter ){
803 Expr *pFilter = sqlite3ExprDup(db, pWin->pFilter, 0);
804 pSublist = sqlite3ExprListAppend(pParse, pSublist, pFilter);
805 }
dandfa552f2018-06-02 21:04:28 +0000806 pWin->regAccum = ++pParse->nMem;
807 pWin->regResult = ++pParse->nMem;
808 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
809 }
810
dan9c277582018-06-20 09:23:49 +0000811 /* If there is no ORDER BY or PARTITION BY clause, and the window
812 ** function accepts zero arguments, and there are no other columns
813 ** selected (e.g. "SELECT row_number() OVER () FROM t1"), it is possible
814 ** that pSublist is still NULL here. Add a constant expression here to
815 ** keep everything legal in this case.
816 */
817 if( pSublist==0 ){
818 pSublist = sqlite3ExprListAppend(pParse, 0,
819 sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0)
820 );
821 }
822
dandfa552f2018-06-02 21:04:28 +0000823 pSub = sqlite3SelectNew(
824 pParse, pSublist, pSrc, pWhere, pGroupBy, pHaving, pSort, 0, 0
825 );
826 p->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
dan6fde1792018-06-15 19:01:35 +0000827 assert( p->pSrc || db->mallocFailed );
dandfa552f2018-06-02 21:04:28 +0000828 if( p->pSrc ){
dandfa552f2018-06-02 21:04:28 +0000829 p->pSrc->a[0].pSelect = pSub;
830 sqlite3SrcListAssignCursors(pParse, p->pSrc);
831 if( sqlite3ExpandSubquery(pParse, &p->pSrc->a[0]) ){
832 rc = SQLITE_NOMEM;
833 }else{
834 pSub->selFlags |= SF_Expanded;
dan73925692018-06-12 18:40:17 +0000835 p->selFlags &= ~SF_Aggregate;
836 sqlite3SelectPrep(pParse, pSub, 0);
dandfa552f2018-06-02 21:04:28 +0000837 }
dandfa552f2018-06-02 21:04:28 +0000838
dan6fde1792018-06-15 19:01:35 +0000839 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pMWin->iEphCsr, pSublist->nExpr);
840 }else{
841 sqlite3SelectDelete(db, pSub);
842 }
843 if( db->mallocFailed ) rc = SQLITE_NOMEM;
dandfa552f2018-06-02 21:04:28 +0000844 }
845
846 return rc;
847}
848
danc0bb4452018-06-12 20:53:38 +0000849/*
850** Free the Window object passed as the second argument.
851*/
dan86fb6e12018-05-16 20:58:07 +0000852void sqlite3WindowDelete(sqlite3 *db, Window *p){
853 if( p ){
854 sqlite3ExprDelete(db, p->pFilter);
855 sqlite3ExprListDelete(db, p->pPartition);
856 sqlite3ExprListDelete(db, p->pOrderBy);
857 sqlite3ExprDelete(db, p->pEnd);
858 sqlite3ExprDelete(db, p->pStart);
dane3bf6322018-06-08 20:58:27 +0000859 sqlite3DbFree(db, p->zName);
dan86fb6e12018-05-16 20:58:07 +0000860 sqlite3DbFree(db, p);
861 }
862}
863
danc0bb4452018-06-12 20:53:38 +0000864/*
865** Free the linked list of Window objects starting at the second argument.
866*/
dane3bf6322018-06-08 20:58:27 +0000867void sqlite3WindowListDelete(sqlite3 *db, Window *p){
868 while( p ){
869 Window *pNext = p->pNextWin;
870 sqlite3WindowDelete(db, p);
871 p = pNext;
872 }
873}
874
danc0bb4452018-06-12 20:53:38 +0000875/*
drhe4984a22018-07-06 17:19:20 +0000876** The argument expression is an PRECEDING or FOLLOWING offset. The
877** value should be a non-negative integer. If the value is not a
878** constant, change it to NULL. The fact that it is then a non-negative
879** integer will be caught later. But it is important not to leave
880** variable values in the expression tree.
881*/
882static Expr *sqlite3WindowOffsetExpr(Parse *pParse, Expr *pExpr){
883 if( 0==sqlite3ExprIsConstant(pExpr) ){
884 sqlite3ExprDelete(pParse->db, pExpr);
885 pExpr = sqlite3ExprAlloc(pParse->db, TK_NULL, 0, 0);
886 }
887 return pExpr;
888}
889
890/*
891** Allocate and return a new Window object describing a Window Definition.
danc0bb4452018-06-12 20:53:38 +0000892*/
dan86fb6e12018-05-16 20:58:07 +0000893Window *sqlite3WindowAlloc(
drhe4984a22018-07-06 17:19:20 +0000894 Parse *pParse, /* Parsing context */
895 int eType, /* Frame type. TK_RANGE or TK_ROWS */
896 int eStart, /* Start type: CURRENT, PRECEDING, FOLLOWING, UNBOUNDED */
897 Expr *pStart, /* Start window size if TK_PRECEDING or FOLLOWING */
898 int eEnd, /* End type: CURRENT, FOLLOWING, TK_UNBOUNDED, PRECEDING */
899 Expr *pEnd /* End window size if TK_FOLLOWING or PRECEDING */
dan86fb6e12018-05-16 20:58:07 +0000900){
dan7a606e12018-07-05 18:34:53 +0000901 Window *pWin = 0;
902
drhe4984a22018-07-06 17:19:20 +0000903 /* Parser assures the following: */
904 assert( eType==TK_RANGE || eType==TK_ROWS );
905 assert( eStart==TK_CURRENT || eStart==TK_PRECEDING
906 || eStart==TK_UNBOUNDED || eStart==TK_FOLLOWING );
907 assert( eEnd==TK_CURRENT || eEnd==TK_FOLLOWING
908 || eEnd==TK_UNBOUNDED || eEnd==TK_PRECEDING );
909 assert( (eStart==TK_PRECEDING || eStart==TK_FOLLOWING)==(pStart!=0) );
910 assert( (eEnd==TK_FOLLOWING || eEnd==TK_PRECEDING)==(pEnd!=0) );
911
912
dan5d764ac2018-07-06 14:15:49 +0000913 /* If a frame is declared "RANGE" (not "ROWS"), then it may not use
drhe4984a22018-07-06 17:19:20 +0000914 ** either "<expr> PRECEDING" or "<expr> FOLLOWING".
915 */
916 if( eType==TK_RANGE && (pStart!=0 || pEnd!=0) ){
917 sqlite3ErrorMsg(pParse, "RANGE must use only UNBOUNDED or CURRENT ROW");
918 goto windowAllocErr;
919 }
920
921 /* Additionally, the
dan5d764ac2018-07-06 14:15:49 +0000922 ** starting boundary type may not occur earlier in the following list than
923 ** the ending boundary type:
924 **
925 ** UNBOUNDED PRECEDING
926 ** <expr> PRECEDING
927 ** CURRENT ROW
928 ** <expr> FOLLOWING
929 ** UNBOUNDED FOLLOWING
930 **
931 ** The parser ensures that "UNBOUNDED PRECEDING" cannot be used as an ending
932 ** boundary, and than "UNBOUNDED FOLLOWING" cannot be used as a starting
933 ** frame boundary.
934 */
drhe4984a22018-07-06 17:19:20 +0000935 if( (eStart==TK_CURRENT && eEnd==TK_PRECEDING)
dan5d764ac2018-07-06 14:15:49 +0000936 || (eStart==TK_FOLLOWING && (eEnd==TK_PRECEDING || eEnd==TK_CURRENT))
937 ){
drhe4984a22018-07-06 17:19:20 +0000938 sqlite3ErrorMsg(pParse, "unsupported frame delimiter for ROWS");
939 goto windowAllocErr;
dan7a606e12018-07-05 18:34:53 +0000940 }
dan86fb6e12018-05-16 20:58:07 +0000941
drhe4984a22018-07-06 17:19:20 +0000942 pWin = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
943 if( pWin==0 ) goto windowAllocErr;
944 pWin->eType = eType;
945 pWin->eStart = eStart;
946 pWin->eEnd = eEnd;
947 pWin->pEnd = sqlite3WindowOffsetExpr(pParse, pEnd);
948 pWin->pStart = sqlite3WindowOffsetExpr(pParse, pStart);
dan86fb6e12018-05-16 20:58:07 +0000949 return pWin;
drhe4984a22018-07-06 17:19:20 +0000950
951windowAllocErr:
952 sqlite3ExprDelete(pParse->db, pEnd);
953 sqlite3ExprDelete(pParse->db, pStart);
954 return 0;
dan86fb6e12018-05-16 20:58:07 +0000955}
956
danc0bb4452018-06-12 20:53:38 +0000957/*
958** Attach window object pWin to expression p.
959*/
dan86fb6e12018-05-16 20:58:07 +0000960void sqlite3WindowAttach(Parse *pParse, Expr *p, Window *pWin){
961 if( p ){
drh954733b2018-07-27 23:33:16 +0000962 /* This routine is only called for the parser. If pWin was not
963 ** allocated due to an OOM, then the parser would fail before ever
964 ** invoking this routine */
965 if( ALWAYS(pWin) ){
dane33f6e72018-07-06 07:42:42 +0000966 p->pWin = pWin;
967 pWin->pOwner = p;
968 if( p->flags & EP_Distinct ){
drhe4984a22018-07-06 17:19:20 +0000969 sqlite3ErrorMsg(pParse,
970 "DISTINCT is not supported for window functions");
dane33f6e72018-07-06 07:42:42 +0000971 }
972 }
dan86fb6e12018-05-16 20:58:07 +0000973 }else{
974 sqlite3WindowDelete(pParse->db, pWin);
975 }
976}
dane2f781b2018-05-17 19:24:08 +0000977
978/*
979** Return 0 if the two window objects are identical, or non-zero otherwise.
dan13078ca2018-06-13 20:29:38 +0000980** Identical window objects can be processed in a single scan.
dane2f781b2018-05-17 19:24:08 +0000981*/
982int sqlite3WindowCompare(Parse *pParse, Window *p1, Window *p2){
983 if( p1->eType!=p2->eType ) return 1;
984 if( p1->eStart!=p2->eStart ) return 1;
985 if( p1->eEnd!=p2->eEnd ) return 1;
986 if( sqlite3ExprCompare(pParse, p1->pStart, p2->pStart, -1) ) return 1;
987 if( sqlite3ExprCompare(pParse, p1->pEnd, p2->pEnd, -1) ) return 1;
988 if( sqlite3ExprListCompare(p1->pPartition, p2->pPartition, -1) ) return 1;
989 if( sqlite3ExprListCompare(p1->pOrderBy, p2->pOrderBy, -1) ) return 1;
990 return 0;
991}
992
dan13078ca2018-06-13 20:29:38 +0000993
994/*
995** This is called by code in select.c before it calls sqlite3WhereBegin()
996** to begin iterating through the sub-query results. It is used to allocate
997** and initialize registers and cursors used by sqlite3WindowCodeStep().
998*/
999void sqlite3WindowCodeInit(Parse *pParse, Window *pMWin){
danc9a86682018-05-30 20:44:58 +00001000 Window *pWin;
dan13078ca2018-06-13 20:29:38 +00001001 Vdbe *v = sqlite3GetVdbe(pParse);
1002 int nPart = (pMWin->pPartition ? pMWin->pPartition->nExpr : 0);
1003 nPart += (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);
1004 if( nPart ){
1005 pMWin->regPart = pParse->nMem+1;
1006 pParse->nMem += nPart;
1007 sqlite3VdbeAddOp3(v, OP_Null, 0, pMWin->regPart, pMWin->regPart+nPart-1);
1008 }
1009
danc9a86682018-05-30 20:44:58 +00001010 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
danec891fd2018-06-06 20:51:02 +00001011 FuncDef *p = pWin->pFunc;
1012 if( (p->funcFlags & SQLITE_FUNC_MINMAX) && pWin->eStart!=TK_UNBOUNDED ){
dan9a947222018-06-14 19:06:36 +00001013 /* The inline versions of min() and max() require a single ephemeral
1014 ** table and 3 registers. The registers are used as follows:
1015 **
1016 ** regApp+0: slot to copy min()/max() argument to for MakeRecord
1017 ** regApp+1: integer value used to ensure keys are unique
1018 ** regApp+2: output of MakeRecord
1019 */
danc9a86682018-05-30 20:44:58 +00001020 ExprList *pList = pWin->pOwner->x.pList;
1021 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pList, 0, 0);
danc9a86682018-05-30 20:44:58 +00001022 pWin->csrApp = pParse->nTab++;
1023 pWin->regApp = pParse->nMem+1;
1024 pParse->nMem += 3;
1025 if( pKeyInfo && pWin->pFunc->zName[1]=='i' ){
1026 assert( pKeyInfo->aSortOrder[0]==0 );
1027 pKeyInfo->aSortOrder[0] = 1;
1028 }
1029 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pWin->csrApp, 2);
1030 sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
1031 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
1032 }
drh19dc4d42018-07-08 01:02:26 +00001033 else if( p->zName==nth_valueName || p->zName==first_valueName ){
danec891fd2018-06-06 20:51:02 +00001034 /* Allocate two registers at pWin->regApp. These will be used to
1035 ** store the start and end index of the current frame. */
1036 assert( pMWin->iEphCsr );
1037 pWin->regApp = pParse->nMem+1;
1038 pWin->csrApp = pParse->nTab++;
1039 pParse->nMem += 2;
danec891fd2018-06-06 20:51:02 +00001040 sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
1041 }
drh19dc4d42018-07-08 01:02:26 +00001042 else if( p->zName==leadName || p->zName==lagName ){
danfe4e25a2018-06-07 20:08:59 +00001043 assert( pMWin->iEphCsr );
1044 pWin->csrApp = pParse->nTab++;
1045 sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
1046 }
danc9a86682018-05-30 20:44:58 +00001047 }
1048}
1049
dan13078ca2018-06-13 20:29:38 +00001050/*
dana1a7e112018-07-09 13:31:18 +00001051** A "PRECEDING <expr>" (eCond==0) or "FOLLOWING <expr>" (eCond==1) or the
1052** value of the second argument to nth_value() (eCond==2) has just been
1053** evaluated and the result left in register reg. This function generates VM
1054** code to check that the value is a non-negative integer and throws an
1055** exception if it is not.
dan13078ca2018-06-13 20:29:38 +00001056*/
dana1a7e112018-07-09 13:31:18 +00001057static void windowCheckIntValue(Parse *pParse, int reg, int eCond){
danc3a20c12018-05-23 20:55:37 +00001058 static const char *azErr[] = {
1059 "frame starting offset must be a non-negative integer",
dana1a7e112018-07-09 13:31:18 +00001060 "frame ending offset must be a non-negative integer",
1061 "second argument to nth_value must be a positive integer"
danc3a20c12018-05-23 20:55:37 +00001062 };
dana1a7e112018-07-09 13:31:18 +00001063 static int aOp[] = { OP_Ge, OP_Ge, OP_Gt };
danc3a20c12018-05-23 20:55:37 +00001064 Vdbe *v = sqlite3GetVdbe(pParse);
dan13078ca2018-06-13 20:29:38 +00001065 int regZero = sqlite3GetTempReg(pParse);
dana1a7e112018-07-09 13:31:18 +00001066 assert( eCond==0 || eCond==1 || eCond==2 );
danc3a20c12018-05-23 20:55:37 +00001067 sqlite3VdbeAddOp2(v, OP_Integer, 0, regZero);
1068 sqlite3VdbeAddOp2(v, OP_MustBeInt, reg, sqlite3VdbeCurrentAddr(v)+2);
drh0b3b0dd2018-07-10 05:11:03 +00001069 VdbeCoverageIf(v, eCond==0);
1070 VdbeCoverageIf(v, eCond==1);
1071 VdbeCoverageIf(v, eCond==2);
dana1a7e112018-07-09 13:31:18 +00001072 sqlite3VdbeAddOp3(v, aOp[eCond], regZero, sqlite3VdbeCurrentAddr(v)+2, reg);
drh6ccbd272018-07-10 17:10:44 +00001073 VdbeCoverageNeverNullIf(v, eCond==0);
1074 VdbeCoverageNeverNullIf(v, eCond==1);
1075 VdbeCoverageNeverNullIf(v, eCond==2);
danc3a20c12018-05-23 20:55:37 +00001076 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_ERROR, OE_Abort);
dana1a7e112018-07-09 13:31:18 +00001077 sqlite3VdbeAppendP4(v, (void*)azErr[eCond], P4_STATIC);
dan13078ca2018-06-13 20:29:38 +00001078 sqlite3ReleaseTempReg(pParse, regZero);
danc3a20c12018-05-23 20:55:37 +00001079}
1080
dan13078ca2018-06-13 20:29:38 +00001081/*
1082** Return the number of arguments passed to the window-function associated
1083** with the object passed as the only argument to this function.
1084*/
dan2a11bb22018-06-11 20:50:25 +00001085static int windowArgCount(Window *pWin){
1086 ExprList *pList = pWin->pOwner->x.pList;
1087 return (pList ? pList->nExpr : 0);
1088}
1089
danc9a86682018-05-30 20:44:58 +00001090/*
1091** Generate VM code to invoke either xStep() (if bInverse is 0) or
1092** xInverse (if bInverse is non-zero) for each window function in the
dan13078ca2018-06-13 20:29:38 +00001093** linked list starting at pMWin. Or, for built-in window functions
1094** that do not use the standard function API, generate the required
1095** inline VM code.
1096**
1097** If argument csr is greater than or equal to 0, then argument reg is
1098** the first register in an array of registers guaranteed to be large
1099** enough to hold the array of arguments for each function. In this case
1100** the arguments are extracted from the current row of csr into the
drh8f26da62018-07-05 21:22:57 +00001101** array of registers before invoking OP_AggStep or OP_AggInverse
dan13078ca2018-06-13 20:29:38 +00001102**
1103** Or, if csr is less than zero, then the array of registers at reg is
1104** already populated with all columns from the current row of the sub-query.
1105**
1106** If argument regPartSize is non-zero, then it is a register containing the
1107** number of rows in the current partition.
danc9a86682018-05-30 20:44:58 +00001108*/
dan31f56392018-05-24 21:10:57 +00001109static void windowAggStep(
1110 Parse *pParse,
dan13078ca2018-06-13 20:29:38 +00001111 Window *pMWin, /* Linked list of window functions */
1112 int csr, /* Read arguments from this cursor */
1113 int bInverse, /* True to invoke xInverse instead of xStep */
1114 int reg, /* Array of registers */
dandfa552f2018-06-02 21:04:28 +00001115 int regPartSize /* Register containing size of partition */
dan31f56392018-05-24 21:10:57 +00001116){
1117 Vdbe *v = sqlite3GetVdbe(pParse);
1118 Window *pWin;
1119 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
dandfa552f2018-06-02 21:04:28 +00001120 int flags = pWin->pFunc->funcFlags;
danc9a86682018-05-30 20:44:58 +00001121 int regArg;
dan2a11bb22018-06-11 20:50:25 +00001122 int nArg = windowArgCount(pWin);
dandfa552f2018-06-02 21:04:28 +00001123
dan6bc5c9e2018-06-04 18:55:11 +00001124 if( csr>=0 ){
danc9a86682018-05-30 20:44:58 +00001125 int i;
dan2a11bb22018-06-11 20:50:25 +00001126 for(i=0; i<nArg; i++){
danc9a86682018-05-30 20:44:58 +00001127 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+i, reg+i);
1128 }
1129 regArg = reg;
dan6bc5c9e2018-06-04 18:55:11 +00001130 if( flags & SQLITE_FUNC_WINDOW_SIZE ){
1131 if( nArg==0 ){
1132 regArg = regPartSize;
1133 }else{
1134 sqlite3VdbeAddOp2(v, OP_SCopy, regPartSize, reg+nArg);
1135 }
1136 nArg++;
1137 }
danc9a86682018-05-30 20:44:58 +00001138 }else{
dan6bc5c9e2018-06-04 18:55:11 +00001139 assert( !(flags & SQLITE_FUNC_WINDOW_SIZE) );
danc9a86682018-05-30 20:44:58 +00001140 regArg = reg + pWin->iArgCol;
dan31f56392018-05-24 21:10:57 +00001141 }
danc9a86682018-05-30 20:44:58 +00001142
danec891fd2018-06-06 20:51:02 +00001143 if( (pWin->pFunc->funcFlags & SQLITE_FUNC_MINMAX)
1144 && pWin->eStart!=TK_UNBOUNDED
1145 ){
dand4fc49f2018-07-07 17:30:44 +00001146 int addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regArg);
1147 VdbeCoverage(v);
danc9a86682018-05-30 20:44:58 +00001148 if( bInverse==0 ){
1149 sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1, 1);
1150 sqlite3VdbeAddOp2(v, OP_SCopy, regArg, pWin->regApp);
1151 sqlite3VdbeAddOp3(v, OP_MakeRecord, pWin->regApp, 2, pWin->regApp+2);
1152 sqlite3VdbeAddOp2(v, OP_IdxInsert, pWin->csrApp, pWin->regApp+2);
1153 }else{
1154 sqlite3VdbeAddOp4Int(v, OP_SeekGE, pWin->csrApp, 0, regArg, 1);
drh93419162018-07-11 03:27:52 +00001155 VdbeCoverageNeverTaken(v);
danc9a86682018-05-30 20:44:58 +00001156 sqlite3VdbeAddOp1(v, OP_Delete, pWin->csrApp);
1157 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
1158 }
dand4fc49f2018-07-07 17:30:44 +00001159 sqlite3VdbeJumpHere(v, addrIsNull);
danec891fd2018-06-06 20:51:02 +00001160 }else if( pWin->regApp ){
drh19dc4d42018-07-08 01:02:26 +00001161 assert( pWin->pFunc->zName==nth_valueName
1162 || pWin->pFunc->zName==first_valueName
dan7095c002018-06-07 17:45:22 +00001163 );
danec891fd2018-06-06 20:51:02 +00001164 assert( bInverse==0 || bInverse==1 );
1165 sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1-bInverse, 1);
drh19dc4d42018-07-08 01:02:26 +00001166 }else if( pWin->pFunc->zName==leadName
1167 || pWin->pFunc->zName==lagName
danfe4e25a2018-06-07 20:08:59 +00001168 ){
1169 /* no-op */
danc9a86682018-05-30 20:44:58 +00001170 }else{
dan8b985602018-06-09 17:43:45 +00001171 int addrIf = 0;
1172 if( pWin->pFilter ){
1173 int regTmp;
danf5e8e312018-07-09 06:51:36 +00001174 assert( nArg==0 || nArg==pWin->pOwner->x.pList->nExpr );
1175 assert( nArg || pWin->pOwner->x.pList==0 );
dan8b985602018-06-09 17:43:45 +00001176 if( csr>0 ){
1177 regTmp = sqlite3GetTempReg(pParse);
dan2a11bb22018-06-11 20:50:25 +00001178 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+nArg,regTmp);
dan8b985602018-06-09 17:43:45 +00001179 }else{
dan2a11bb22018-06-11 20:50:25 +00001180 regTmp = regArg + nArg;
dan8b985602018-06-09 17:43:45 +00001181 }
1182 addrIf = sqlite3VdbeAddOp3(v, OP_IfNot, regTmp, 0, 1);
dan01e12292018-06-27 20:24:59 +00001183 VdbeCoverage(v);
dan8b985602018-06-09 17:43:45 +00001184 if( csr>0 ){
1185 sqlite3ReleaseTempReg(pParse, regTmp);
1186 }
1187 }
danc9a86682018-05-30 20:44:58 +00001188 if( pWin->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
1189 CollSeq *pColl;
danf5e8e312018-07-09 06:51:36 +00001190 assert( nArg>0 );
dan8b985602018-06-09 17:43:45 +00001191 pColl = sqlite3ExprNNCollSeq(pParse, pWin->pOwner->x.pList->a[0].pExpr);
danc9a86682018-05-30 20:44:58 +00001192 sqlite3VdbeAddOp4(v, OP_CollSeq, 0,0,0, (const char*)pColl, P4_COLLSEQ);
1193 }
drh8f26da62018-07-05 21:22:57 +00001194 sqlite3VdbeAddOp3(v, bInverse? OP_AggInverse : OP_AggStep,
1195 bInverse, regArg, pWin->regAccum);
danc9a86682018-05-30 20:44:58 +00001196 sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
dandfa552f2018-06-02 21:04:28 +00001197 sqlite3VdbeChangeP5(v, (u8)nArg);
dan8b985602018-06-09 17:43:45 +00001198 if( addrIf ) sqlite3VdbeJumpHere(v, addrIf);
danc9a86682018-05-30 20:44:58 +00001199 }
dan31f56392018-05-24 21:10:57 +00001200 }
1201}
1202
dan13078ca2018-06-13 20:29:38 +00001203/*
1204** Generate VM code to invoke either xValue() (bFinal==0) or xFinalize()
1205** (bFinal==1) for each window function in the linked list starting at
1206** pMWin. Or, for built-in window-functions that do not use the standard
1207** API, generate the equivalent VM code.
1208*/
dand6f784e2018-05-28 18:30:45 +00001209static void windowAggFinal(Parse *pParse, Window *pMWin, int bFinal){
1210 Vdbe *v = sqlite3GetVdbe(pParse);
1211 Window *pWin;
1212
1213 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
danec891fd2018-06-06 20:51:02 +00001214 if( (pWin->pFunc->funcFlags & SQLITE_FUNC_MINMAX)
1215 && pWin->eStart!=TK_UNBOUNDED
1216 ){
dand6f784e2018-05-28 18:30:45 +00001217 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
danc9a86682018-05-30 20:44:58 +00001218 sqlite3VdbeAddOp1(v, OP_Last, pWin->csrApp);
dan01e12292018-06-27 20:24:59 +00001219 VdbeCoverage(v);
danc9a86682018-05-30 20:44:58 +00001220 sqlite3VdbeAddOp3(v, OP_Column, pWin->csrApp, 0, pWin->regResult);
1221 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
1222 if( bFinal ){
1223 sqlite3VdbeAddOp1(v, OP_ResetSorter, pWin->csrApp);
1224 }
danec891fd2018-06-06 20:51:02 +00001225 }else if( pWin->regApp ){
dand6f784e2018-05-28 18:30:45 +00001226 }else{
danc9a86682018-05-30 20:44:58 +00001227 if( bFinal ){
drh8f26da62018-07-05 21:22:57 +00001228 sqlite3VdbeAddOp2(v, OP_AggFinal, pWin->regAccum, windowArgCount(pWin));
1229 sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
danc9a86682018-05-30 20:44:58 +00001230 sqlite3VdbeAddOp2(v, OP_Copy, pWin->regAccum, pWin->regResult);
dan8b985602018-06-09 17:43:45 +00001231 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
danc9a86682018-05-30 20:44:58 +00001232 }else{
drh8f26da62018-07-05 21:22:57 +00001233 sqlite3VdbeAddOp3(v, OP_AggValue, pWin->regAccum, windowArgCount(pWin),
1234 pWin->regResult);
1235 sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
danc9a86682018-05-30 20:44:58 +00001236 }
dand6f784e2018-05-28 18:30:45 +00001237 }
1238 }
1239}
1240
dan13078ca2018-06-13 20:29:38 +00001241/*
1242** This function generates VM code to invoke the sub-routine at address
1243** lblFlushPart once for each partition with the entire partition cached in
1244** the Window.iEphCsr temp table.
1245*/
danf690b572018-06-01 21:00:08 +00001246static void windowPartitionCache(
1247 Parse *pParse,
dan13078ca2018-06-13 20:29:38 +00001248 Select *p, /* The rewritten SELECT statement */
1249 WhereInfo *pWInfo, /* WhereInfo to call WhereEnd() on */
1250 int regFlushPart, /* Register to use with Gosub lblFlushPart */
1251 int lblFlushPart, /* Subroutine to Gosub to */
1252 int *pRegSize /* OUT: Register containing partition size */
danf690b572018-06-01 21:00:08 +00001253){
1254 Window *pMWin = p->pWin;
1255 Vdbe *v = sqlite3GetVdbe(pParse);
danf690b572018-06-01 21:00:08 +00001256 int iSubCsr = p->pSrc->a[0].iCursor;
1257 int nSub = p->pSrc->a[0].pTab->nCol;
1258 int k;
1259
1260 int reg = pParse->nMem+1;
1261 int regRecord = reg+nSub;
1262 int regRowid = regRecord+1;
1263
dandfa552f2018-06-02 21:04:28 +00001264 *pRegSize = regRowid;
danf690b572018-06-01 21:00:08 +00001265 pParse->nMem += nSub + 2;
1266
drhb0225bc2018-07-10 20:50:27 +00001267 /* Load the column values for the row returned by the sub-select
1268 ** into an array of registers starting at reg. */
danf690b572018-06-01 21:00:08 +00001269 for(k=0; k<nSub; k++){
1270 sqlite3VdbeAddOp3(v, OP_Column, iSubCsr, k, reg+k);
1271 }
1272 sqlite3VdbeAddOp3(v, OP_MakeRecord, reg, nSub, regRecord);
1273
1274 /* Check if this is the start of a new partition. If so, call the
1275 ** flush_partition sub-routine. */
1276 if( pMWin->pPartition ){
1277 int addr;
1278 ExprList *pPart = pMWin->pPartition;
dane0a5e202018-06-15 16:10:44 +00001279 int nPart = pPart->nExpr;
danf690b572018-06-01 21:00:08 +00001280 int regNewPart = reg + pMWin->nBufferCol;
1281 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pPart, 0, 0);
1282
1283 addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPart, pMWin->regPart,nPart);
1284 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
1285 sqlite3VdbeAddOp3(v, OP_Jump, addr+2, addr+4, addr+2);
drh93419162018-07-11 03:27:52 +00001286 VdbeCoverageEqNe(v);
danf690b572018-06-01 21:00:08 +00001287 sqlite3VdbeAddOp3(v, OP_Copy, regNewPart, pMWin->regPart, nPart-1);
1288 sqlite3VdbeAddOp2(v, OP_Gosub, regFlushPart, lblFlushPart);
drh0b3b0dd2018-07-10 05:11:03 +00001289 VdbeComment((v, "call flush_partition"));
danf690b572018-06-01 21:00:08 +00001290 }
1291
1292 /* Buffer the current row in the ephemeral table. */
1293 sqlite3VdbeAddOp2(v, OP_NewRowid, pMWin->iEphCsr, regRowid);
1294 sqlite3VdbeAddOp3(v, OP_Insert, pMWin->iEphCsr, regRecord, regRowid);
1295
1296 /* End of the input loop */
1297 sqlite3WhereEnd(pWInfo);
1298
1299 /* Invoke "flush_partition" to deal with the final (or only) partition */
1300 sqlite3VdbeAddOp2(v, OP_Gosub, regFlushPart, lblFlushPart);
drh0b3b0dd2018-07-10 05:11:03 +00001301 VdbeComment((v, "call flush_partition"));
danf690b572018-06-01 21:00:08 +00001302}
dand6f784e2018-05-28 18:30:45 +00001303
dan13078ca2018-06-13 20:29:38 +00001304/*
1305** Invoke the sub-routine at regGosub (generated by code in select.c) to
1306** return the current row of Window.iEphCsr. If all window functions are
1307** aggregate window functions that use the standard API, a single
1308** OP_Gosub instruction is all that this routine generates. Extra VM code
1309** for per-row processing is only generated for the following built-in window
1310** functions:
1311**
1312** nth_value()
1313** first_value()
1314** lag()
1315** lead()
1316*/
danec891fd2018-06-06 20:51:02 +00001317static void windowReturnOneRow(
1318 Parse *pParse,
1319 Window *pMWin,
1320 int regGosub,
1321 int addrGosub
1322){
1323 Vdbe *v = sqlite3GetVdbe(pParse);
1324 Window *pWin;
1325 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
1326 FuncDef *pFunc = pWin->pFunc;
drh19dc4d42018-07-08 01:02:26 +00001327 if( pFunc->zName==nth_valueName
1328 || pFunc->zName==first_valueName
dan7095c002018-06-07 17:45:22 +00001329 ){
danec891fd2018-06-06 20:51:02 +00001330 int csr = pWin->csrApp;
1331 int lbl = sqlite3VdbeMakeLabel(v);
1332 int tmpReg = sqlite3GetTempReg(pParse);
1333 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
dan7095c002018-06-07 17:45:22 +00001334
drh19dc4d42018-07-08 01:02:26 +00001335 if( pFunc->zName==nth_valueName ){
dan6fde1792018-06-15 19:01:35 +00001336 sqlite3VdbeAddOp3(v, OP_Column, pMWin->iEphCsr, pWin->iArgCol+1,tmpReg);
dana1a7e112018-07-09 13:31:18 +00001337 windowCheckIntValue(pParse, tmpReg, 2);
dan7095c002018-06-07 17:45:22 +00001338 }else{
1339 sqlite3VdbeAddOp2(v, OP_Integer, 1, tmpReg);
1340 }
danec891fd2018-06-06 20:51:02 +00001341 sqlite3VdbeAddOp3(v, OP_Add, tmpReg, pWin->regApp, tmpReg);
1342 sqlite3VdbeAddOp3(v, OP_Gt, pWin->regApp+1, lbl, tmpReg);
drh6ccbd272018-07-10 17:10:44 +00001343 VdbeCoverageNeverNull(v);
drh93419162018-07-11 03:27:52 +00001344 sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, 0, tmpReg);
1345 VdbeCoverageNeverTaken(v);
danec891fd2018-06-06 20:51:02 +00001346 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
1347 sqlite3VdbeResolveLabel(v, lbl);
1348 sqlite3ReleaseTempReg(pParse, tmpReg);
1349 }
drh19dc4d42018-07-08 01:02:26 +00001350 else if( pFunc->zName==leadName || pFunc->zName==lagName ){
dan2a11bb22018-06-11 20:50:25 +00001351 int nArg = pWin->pOwner->x.pList->nExpr;
dane0a5e202018-06-15 16:10:44 +00001352 int iEph = pMWin->iEphCsr;
danfe4e25a2018-06-07 20:08:59 +00001353 int csr = pWin->csrApp;
1354 int lbl = sqlite3VdbeMakeLabel(v);
1355 int tmpReg = sqlite3GetTempReg(pParse);
1356
dan2a11bb22018-06-11 20:50:25 +00001357 if( nArg<3 ){
danfe4e25a2018-06-07 20:08:59 +00001358 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
1359 }else{
1360 sqlite3VdbeAddOp3(v, OP_Column, iEph, pWin->iArgCol+2, pWin->regResult);
1361 }
1362 sqlite3VdbeAddOp2(v, OP_Rowid, iEph, tmpReg);
dan2a11bb22018-06-11 20:50:25 +00001363 if( nArg<2 ){
drh19dc4d42018-07-08 01:02:26 +00001364 int val = (pFunc->zName==leadName ? 1 : -1);
danfe4e25a2018-06-07 20:08:59 +00001365 sqlite3VdbeAddOp2(v, OP_AddImm, tmpReg, val);
1366 }else{
drh19dc4d42018-07-08 01:02:26 +00001367 int op = (pFunc->zName==leadName ? OP_Add : OP_Subtract);
danfe4e25a2018-06-07 20:08:59 +00001368 int tmpReg2 = sqlite3GetTempReg(pParse);
1369 sqlite3VdbeAddOp3(v, OP_Column, iEph, pWin->iArgCol+1, tmpReg2);
1370 sqlite3VdbeAddOp3(v, op, tmpReg2, tmpReg, tmpReg);
1371 sqlite3ReleaseTempReg(pParse, tmpReg2);
1372 }
1373
1374 sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, lbl, tmpReg);
dan01e12292018-06-27 20:24:59 +00001375 VdbeCoverage(v);
danfe4e25a2018-06-07 20:08:59 +00001376 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
1377 sqlite3VdbeResolveLabel(v, lbl);
1378 sqlite3ReleaseTempReg(pParse, tmpReg);
1379 }
danec891fd2018-06-06 20:51:02 +00001380 }
1381 sqlite3VdbeAddOp2(v, OP_Gosub, regGosub, addrGosub);
1382}
1383
dan13078ca2018-06-13 20:29:38 +00001384/*
1385** Invoke the code generated by windowReturnOneRow() and, optionally, the
1386** xInverse() function for each window function, for one or more rows
1387** from the Window.iEphCsr temp table. This routine generates VM code
1388** similar to:
1389**
1390** while( regCtr>0 ){
1391** regCtr--;
1392** windowReturnOneRow()
1393** if( bInverse ){
drh8f26da62018-07-05 21:22:57 +00001394** AggInverse
dan13078ca2018-06-13 20:29:38 +00001395** }
1396** Next (Window.iEphCsr)
1397** }
1398*/
danec891fd2018-06-06 20:51:02 +00001399static void windowReturnRows(
1400 Parse *pParse,
dan13078ca2018-06-13 20:29:38 +00001401 Window *pMWin, /* List of window functions */
1402 int regCtr, /* Register containing number of rows */
1403 int regGosub, /* Register for Gosub addrGosub */
1404 int addrGosub, /* Address of sub-routine for ReturnOneRow */
1405 int regInvArg, /* Array of registers for xInverse args */
1406 int regInvSize /* Register containing size of partition */
danec891fd2018-06-06 20:51:02 +00001407){
1408 int addr;
1409 Vdbe *v = sqlite3GetVdbe(pParse);
1410 windowAggFinal(pParse, pMWin, 0);
1411 addr = sqlite3VdbeAddOp3(v, OP_IfPos, regCtr, sqlite3VdbeCurrentAddr(v)+2 ,1);
dan01e12292018-06-27 20:24:59 +00001412 VdbeCoverage(v);
danec891fd2018-06-06 20:51:02 +00001413 sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
1414 windowReturnOneRow(pParse, pMWin, regGosub, addrGosub);
1415 if( regInvArg ){
1416 windowAggStep(pParse, pMWin, pMWin->iEphCsr, 1, regInvArg, regInvSize);
1417 }
1418 sqlite3VdbeAddOp2(v, OP_Next, pMWin->iEphCsr, addr);
dan01e12292018-06-27 20:24:59 +00001419 VdbeCoverage(v);
danec891fd2018-06-06 20:51:02 +00001420 sqlite3VdbeJumpHere(v, addr+1); /* The OP_Goto */
1421}
1422
dan54a9ab32018-06-14 14:27:05 +00001423/*
1424** Generate code to set the accumulator register for each window function
1425** in the linked list passed as the second argument to NULL. And perform
1426** any equivalent initialization required by any built-in window functions
1427** in the list.
1428*/
dan2e605682018-06-07 15:54:26 +00001429static int windowInitAccum(Parse *pParse, Window *pMWin){
1430 Vdbe *v = sqlite3GetVdbe(pParse);
1431 int regArg;
1432 int nArg = 0;
1433 Window *pWin;
1434 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
dan9a947222018-06-14 19:06:36 +00001435 FuncDef *pFunc = pWin->pFunc;
dan2e605682018-06-07 15:54:26 +00001436 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
dan2a11bb22018-06-11 20:50:25 +00001437 nArg = MAX(nArg, windowArgCount(pWin));
drh19dc4d42018-07-08 01:02:26 +00001438 if( pFunc->zName==nth_valueName
1439 || pFunc->zName==first_valueName
dan7095c002018-06-07 17:45:22 +00001440 ){
dan2e605682018-06-07 15:54:26 +00001441 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp);
1442 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
1443 }
dan9a947222018-06-14 19:06:36 +00001444
1445 if( (pFunc->funcFlags & SQLITE_FUNC_MINMAX) && pWin->csrApp ){
1446 assert( pWin->eStart!=TK_UNBOUNDED );
1447 sqlite3VdbeAddOp1(v, OP_ResetSorter, pWin->csrApp);
1448 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
1449 }
dan2e605682018-06-07 15:54:26 +00001450 }
1451 regArg = pParse->nMem+1;
1452 pParse->nMem += nArg;
1453 return regArg;
1454}
1455
1456
dan99652dd2018-05-24 17:49:14 +00001457/*
dan54a9ab32018-06-14 14:27:05 +00001458** This function does the work of sqlite3WindowCodeStep() for all "ROWS"
1459** window frame types except for "BETWEEN UNBOUNDED PRECEDING AND CURRENT
1460** ROW". Pseudo-code for each follows.
1461**
dan09590aa2018-05-25 20:30:17 +00001462** ROWS BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
dan09590aa2018-05-25 20:30:17 +00001463**
1464** ...
1465** if( new partition ){
1466** Gosub flush_partition
1467** }
1468** Insert (record in eph-table)
1469** sqlite3WhereEnd()
1470** Gosub flush_partition
1471**
1472** flush_partition:
1473** Once {
1474** OpenDup (iEphCsr -> csrStart)
1475** OpenDup (iEphCsr -> csrEnd)
dan99652dd2018-05-24 17:49:14 +00001476** }
dan09590aa2018-05-25 20:30:17 +00001477** regStart = <expr1> // PRECEDING expression
1478** regEnd = <expr2> // FOLLOWING expression
1479** if( regStart<0 || regEnd<0 ){ error! }
1480** Rewind (csr,csrStart,csrEnd) // if EOF goto flush_partition_done
1481** Next(csrEnd) // if EOF skip Aggstep
1482** Aggstep (csrEnd)
1483** if( (regEnd--)<=0 ){
1484** AggFinal (xValue)
1485** Gosub addrGosub
1486** Next(csr) // if EOF goto flush_partition_done
1487** if( (regStart--)<=0 ){
drh8f26da62018-07-05 21:22:57 +00001488** AggInverse (csrStart)
dan09590aa2018-05-25 20:30:17 +00001489** Next(csrStart)
1490** }
1491** }
1492** flush_partition_done:
1493** ResetSorter (csr)
1494** Return
dan99652dd2018-05-24 17:49:14 +00001495**
dan09590aa2018-05-25 20:30:17 +00001496** ROWS BETWEEN <expr> PRECEDING AND CURRENT ROW
1497** ROWS BETWEEN CURRENT ROW AND <expr> FOLLOWING
1498** ROWS BETWEEN UNBOUNDED PRECEDING AND <expr> FOLLOWING
1499**
1500** These are similar to the above. For "CURRENT ROW", intialize the
1501** register to 0. For "UNBOUNDED PRECEDING" to infinity.
1502**
1503** ROWS BETWEEN <expr> PRECEDING AND UNBOUNDED FOLLOWING
1504** ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
1505**
1506** Rewind (csr,csrStart,csrEnd) // if EOF goto flush_partition_done
1507** while( 1 ){
1508** Next(csrEnd) // Exit while(1) at EOF
1509** Aggstep (csrEnd)
1510** }
1511** while( 1 ){
dan99652dd2018-05-24 17:49:14 +00001512** AggFinal (xValue)
1513** Gosub addrGosub
dan09590aa2018-05-25 20:30:17 +00001514** Next(csr) // if EOF goto flush_partition_done
dan31f56392018-05-24 21:10:57 +00001515** if( (regStart--)<=0 ){
drh8f26da62018-07-05 21:22:57 +00001516** AggInverse (csrStart)
dan31f56392018-05-24 21:10:57 +00001517** Next(csrStart)
dan99652dd2018-05-24 17:49:14 +00001518** }
1519** }
dan99652dd2018-05-24 17:49:14 +00001520**
dan09590aa2018-05-25 20:30:17 +00001521** For the "CURRENT ROW AND UNBOUNDED FOLLOWING" case, the final if()
1522** condition is always true (as if regStart were initialized to 0).
dan99652dd2018-05-24 17:49:14 +00001523**
dan09590aa2018-05-25 20:30:17 +00001524** RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
1525**
1526** This is the only RANGE case handled by this routine. It modifies the
1527** second while( 1 ) loop in "ROWS BETWEEN CURRENT ... UNBOUNDED..." to
1528** be:
1529**
1530** while( 1 ){
1531** AggFinal (xValue)
1532** while( 1 ){
1533** regPeer++
1534** Gosub addrGosub
1535** Next(csr) // if EOF goto flush_partition_done
1536** if( new peer ) break;
1537** }
1538** while( (regPeer--)>0 ){
drh8f26da62018-07-05 21:22:57 +00001539** AggInverse (csrStart)
dan09590aa2018-05-25 20:30:17 +00001540** Next(csrStart)
1541** }
1542** }
dan99652dd2018-05-24 17:49:14 +00001543**
dan31f56392018-05-24 21:10:57 +00001544** ROWS BETWEEN <expr> FOLLOWING AND <expr> FOLLOWING
1545**
1546** regEnd = regEnd - regStart
1547** Rewind (csr,csrStart,csrEnd) // if EOF goto flush_partition_done
1548** Aggstep (csrEnd)
1549** Next(csrEnd) // if EOF fall-through
1550** if( (regEnd--)<=0 ){
dan31f56392018-05-24 21:10:57 +00001551** if( (regStart--)<=0 ){
1552** AggFinal (xValue)
1553** Gosub addrGosub
1554** Next(csr) // if EOF goto flush_partition_done
1555** }
drh8f26da62018-07-05 21:22:57 +00001556** AggInverse (csrStart)
dane105dd72018-05-25 09:29:11 +00001557** Next (csrStart)
dan31f56392018-05-24 21:10:57 +00001558** }
1559**
1560** ROWS BETWEEN <expr> PRECEDING AND <expr> PRECEDING
1561**
1562** Replace the bit after "Rewind" in the above with:
1563**
1564** if( (regEnd--)<=0 ){
1565** AggStep (csrEnd)
1566** Next (csrEnd)
1567** }
1568** AggFinal (xValue)
1569** Gosub addrGosub
1570** Next(csr) // if EOF goto flush_partition_done
1571** if( (regStart--)<=0 ){
drh8f26da62018-07-05 21:22:57 +00001572** AggInverse (csr2)
dan31f56392018-05-24 21:10:57 +00001573** Next (csr2)
1574** }
1575**
dan99652dd2018-05-24 17:49:14 +00001576*/
danc3a20c12018-05-23 20:55:37 +00001577static void windowCodeRowExprStep(
1578 Parse *pParse,
1579 Select *p,
1580 WhereInfo *pWInfo,
1581 int regGosub,
1582 int addrGosub
1583){
1584 Window *pMWin = p->pWin;
1585 Vdbe *v = sqlite3GetVdbe(pParse);
danc3a20c12018-05-23 20:55:37 +00001586 int regFlushPart; /* Register for "Gosub flush_partition" */
dan31f56392018-05-24 21:10:57 +00001587 int lblFlushPart; /* Label for "Gosub flush_partition" */
1588 int lblFlushDone; /* Label for "Gosub flush_partition_done" */
danc3a20c12018-05-23 20:55:37 +00001589
danf690b572018-06-01 21:00:08 +00001590 int regArg;
danc3a20c12018-05-23 20:55:37 +00001591 int addr;
dan31f56392018-05-24 21:10:57 +00001592 int csrStart = pParse->nTab++;
1593 int csrEnd = pParse->nTab++;
1594 int regStart; /* Value of <expr> PRECEDING */
1595 int regEnd; /* Value of <expr> FOLLOWING */
danc3a20c12018-05-23 20:55:37 +00001596 int addrGoto;
dan31f56392018-05-24 21:10:57 +00001597 int addrTop;
drhc7bf5712018-07-09 22:49:01 +00001598 int addrIfPos1 = 0;
1599 int addrIfPos2 = 0;
dandfa552f2018-06-02 21:04:28 +00001600 int regSize = 0;
dan09590aa2018-05-25 20:30:17 +00001601
dan99652dd2018-05-24 17:49:14 +00001602 assert( pMWin->eStart==TK_PRECEDING
1603 || pMWin->eStart==TK_CURRENT
dane105dd72018-05-25 09:29:11 +00001604 || pMWin->eStart==TK_FOLLOWING
dan99652dd2018-05-24 17:49:14 +00001605 || pMWin->eStart==TK_UNBOUNDED
1606 );
1607 assert( pMWin->eEnd==TK_FOLLOWING
1608 || pMWin->eEnd==TK_CURRENT
1609 || pMWin->eEnd==TK_UNBOUNDED
dan31f56392018-05-24 21:10:57 +00001610 || pMWin->eEnd==TK_PRECEDING
dan99652dd2018-05-24 17:49:14 +00001611 );
1612
danc3a20c12018-05-23 20:55:37 +00001613 /* Allocate register and label for the "flush_partition" sub-routine. */
1614 regFlushPart = ++pParse->nMem;
dan31f56392018-05-24 21:10:57 +00001615 lblFlushPart = sqlite3VdbeMakeLabel(v);
1616 lblFlushDone = sqlite3VdbeMakeLabel(v);
danc3a20c12018-05-23 20:55:37 +00001617
dan31f56392018-05-24 21:10:57 +00001618 regStart = ++pParse->nMem;
1619 regEnd = ++pParse->nMem;
danc3a20c12018-05-23 20:55:37 +00001620
dandfa552f2018-06-02 21:04:28 +00001621 windowPartitionCache(pParse, p, pWInfo, regFlushPart, lblFlushPart, &regSize);
danc3a20c12018-05-23 20:55:37 +00001622
danc3a20c12018-05-23 20:55:37 +00001623 addrGoto = sqlite3VdbeAddOp0(v, OP_Goto);
1624
danc9a86682018-05-30 20:44:58 +00001625 /* Start of "flush_partition" */
dan31f56392018-05-24 21:10:57 +00001626 sqlite3VdbeResolveLabel(v, lblFlushPart);
danc3a20c12018-05-23 20:55:37 +00001627 sqlite3VdbeAddOp2(v, OP_Once, 0, sqlite3VdbeCurrentAddr(v)+3);
dan01e12292018-06-27 20:24:59 +00001628 VdbeCoverage(v);
drh0b3b0dd2018-07-10 05:11:03 +00001629 VdbeComment((v, "Flush_partition subroutine"));
dan31f56392018-05-24 21:10:57 +00001630 sqlite3VdbeAddOp2(v, OP_OpenDup, csrStart, pMWin->iEphCsr);
1631 sqlite3VdbeAddOp2(v, OP_OpenDup, csrEnd, pMWin->iEphCsr);
danc3a20c12018-05-23 20:55:37 +00001632
dan31f56392018-05-24 21:10:57 +00001633 /* If either regStart or regEnd are not non-negative integers, throw
dan99652dd2018-05-24 17:49:14 +00001634 ** an exception. */
1635 if( pMWin->pStart ){
dan31f56392018-05-24 21:10:57 +00001636 sqlite3ExprCode(pParse, pMWin->pStart, regStart);
dana1a7e112018-07-09 13:31:18 +00001637 windowCheckIntValue(pParse, regStart, 0);
dan99652dd2018-05-24 17:49:14 +00001638 }
1639 if( pMWin->pEnd ){
dan31f56392018-05-24 21:10:57 +00001640 sqlite3ExprCode(pParse, pMWin->pEnd, regEnd);
dana1a7e112018-07-09 13:31:18 +00001641 windowCheckIntValue(pParse, regEnd, 1);
dan99652dd2018-05-24 17:49:14 +00001642 }
danc3a20c12018-05-23 20:55:37 +00001643
danc9a86682018-05-30 20:44:58 +00001644 /* If this is "ROWS <expr1> FOLLOWING AND ROWS <expr2> FOLLOWING", do:
1645 **
dan26522d12018-06-11 18:16:51 +00001646 ** if( regEnd<regStart ){
1647 ** // The frame always consists of 0 rows
1648 ** regStart = regSize;
1649 ** }
danc9a86682018-05-30 20:44:58 +00001650 ** regEnd = regEnd - regStart;
1651 */
drh7999cc42018-07-09 17:33:24 +00001652 if( pMWin->pEnd && pMWin->eStart==TK_FOLLOWING ){
1653 assert( pMWin->pStart!=0 );
danc9a86682018-05-30 20:44:58 +00001654 assert( pMWin->eEnd==TK_FOLLOWING );
dan26522d12018-06-11 18:16:51 +00001655 sqlite3VdbeAddOp3(v, OP_Ge, regStart, sqlite3VdbeCurrentAddr(v)+2, regEnd);
drh6ccbd272018-07-10 17:10:44 +00001656 VdbeCoverageNeverNull(v);
dan26522d12018-06-11 18:16:51 +00001657 sqlite3VdbeAddOp2(v, OP_Copy, regSize, regStart);
danc9a86682018-05-30 20:44:58 +00001658 sqlite3VdbeAddOp3(v, OP_Subtract, regStart, regEnd, regEnd);
1659 }
1660
drh7999cc42018-07-09 17:33:24 +00001661 if( pMWin->pStart && pMWin->eEnd==TK_PRECEDING ){
1662 assert( pMWin->pEnd!=0 );
dan26522d12018-06-11 18:16:51 +00001663 assert( pMWin->eStart==TK_PRECEDING );
1664 sqlite3VdbeAddOp3(v, OP_Le, regStart, sqlite3VdbeCurrentAddr(v)+3, regEnd);
drh6ccbd272018-07-10 17:10:44 +00001665 VdbeCoverageNeverNull(v);
dan26522d12018-06-11 18:16:51 +00001666 sqlite3VdbeAddOp2(v, OP_Copy, regSize, regStart);
1667 sqlite3VdbeAddOp2(v, OP_Copy, regSize, regEnd);
1668 }
1669
danc9a86682018-05-30 20:44:58 +00001670 /* Initialize the accumulator register for each window function to NULL */
dan2e605682018-06-07 15:54:26 +00001671 regArg = windowInitAccum(pParse, pMWin);
danc3a20c12018-05-23 20:55:37 +00001672
dan31f56392018-05-24 21:10:57 +00001673 sqlite3VdbeAddOp2(v, OP_Rewind, pMWin->iEphCsr, lblFlushDone);
dan01e12292018-06-27 20:24:59 +00001674 VdbeCoverage(v);
dan31f56392018-05-24 21:10:57 +00001675 sqlite3VdbeAddOp2(v, OP_Rewind, csrStart, lblFlushDone);
dan01e12292018-06-27 20:24:59 +00001676 VdbeCoverageNeverTaken(v);
danc3a20c12018-05-23 20:55:37 +00001677 sqlite3VdbeChangeP5(v, 1);
dan31f56392018-05-24 21:10:57 +00001678 sqlite3VdbeAddOp2(v, OP_Rewind, csrEnd, lblFlushDone);
dan01e12292018-06-27 20:24:59 +00001679 VdbeCoverageNeverTaken(v);
danc3a20c12018-05-23 20:55:37 +00001680 sqlite3VdbeChangeP5(v, 1);
1681
1682 /* Invoke AggStep function for each window function using the row that
dan31f56392018-05-24 21:10:57 +00001683 ** csrEnd currently points to. Or, if csrEnd is already at EOF,
danc3a20c12018-05-23 20:55:37 +00001684 ** do nothing. */
dan31f56392018-05-24 21:10:57 +00001685 addrTop = sqlite3VdbeCurrentAddr(v);
1686 if( pMWin->eEnd==TK_PRECEDING ){
1687 addrIfPos1 = sqlite3VdbeAddOp3(v, OP_IfPos, regEnd, 0 , 1);
dan01e12292018-06-27 20:24:59 +00001688 VdbeCoverage(v);
danc3a20c12018-05-23 20:55:37 +00001689 }
dan31f56392018-05-24 21:10:57 +00001690 sqlite3VdbeAddOp2(v, OP_Next, csrEnd, sqlite3VdbeCurrentAddr(v)+2);
dan01e12292018-06-27 20:24:59 +00001691 VdbeCoverage(v);
dan31f56392018-05-24 21:10:57 +00001692 addr = sqlite3VdbeAddOp0(v, OP_Goto);
dandfa552f2018-06-02 21:04:28 +00001693 windowAggStep(pParse, pMWin, csrEnd, 0, regArg, regSize);
dan99652dd2018-05-24 17:49:14 +00001694 if( pMWin->eEnd==TK_UNBOUNDED ){
dan31f56392018-05-24 21:10:57 +00001695 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
1696 sqlite3VdbeJumpHere(v, addr);
1697 addrTop = sqlite3VdbeCurrentAddr(v);
dan99652dd2018-05-24 17:49:14 +00001698 }else{
dan31f56392018-05-24 21:10:57 +00001699 sqlite3VdbeJumpHere(v, addr);
1700 if( pMWin->eEnd==TK_PRECEDING ){
1701 sqlite3VdbeJumpHere(v, addrIfPos1);
1702 }
dan99652dd2018-05-24 17:49:14 +00001703 }
danc3a20c12018-05-23 20:55:37 +00001704
dan99652dd2018-05-24 17:49:14 +00001705 if( pMWin->eEnd==TK_FOLLOWING ){
dan31f56392018-05-24 21:10:57 +00001706 addrIfPos1 = sqlite3VdbeAddOp3(v, OP_IfPos, regEnd, 0 , 1);
dan01e12292018-06-27 20:24:59 +00001707 VdbeCoverage(v);
dan99652dd2018-05-24 17:49:14 +00001708 }
dane105dd72018-05-25 09:29:11 +00001709 if( pMWin->eStart==TK_FOLLOWING ){
1710 addrIfPos2 = sqlite3VdbeAddOp3(v, OP_IfPos, regStart, 0 , 1);
dan01e12292018-06-27 20:24:59 +00001711 VdbeCoverage(v);
dane105dd72018-05-25 09:29:11 +00001712 }
dand6f784e2018-05-28 18:30:45 +00001713 windowAggFinal(pParse, pMWin, 0);
danec891fd2018-06-06 20:51:02 +00001714 windowReturnOneRow(pParse, pMWin, regGosub, addrGosub);
danc3a20c12018-05-23 20:55:37 +00001715 sqlite3VdbeAddOp2(v, OP_Next, pMWin->iEphCsr, sqlite3VdbeCurrentAddr(v)+2);
dan01e12292018-06-27 20:24:59 +00001716 VdbeCoverage(v);
dan31f56392018-05-24 21:10:57 +00001717 sqlite3VdbeAddOp2(v, OP_Goto, 0, lblFlushDone);
dane105dd72018-05-25 09:29:11 +00001718 if( pMWin->eStart==TK_FOLLOWING ){
1719 sqlite3VdbeJumpHere(v, addrIfPos2);
1720 }
danc3a20c12018-05-23 20:55:37 +00001721
dane105dd72018-05-25 09:29:11 +00001722 if( pMWin->eStart==TK_CURRENT
1723 || pMWin->eStart==TK_PRECEDING
1724 || pMWin->eStart==TK_FOLLOWING
1725 ){
dan7262ca92018-07-02 12:07:32 +00001726 int lblSkipInverse = sqlite3VdbeMakeLabel(v);;
dan99652dd2018-05-24 17:49:14 +00001727 if( pMWin->eStart==TK_PRECEDING ){
dan7262ca92018-07-02 12:07:32 +00001728 sqlite3VdbeAddOp3(v, OP_IfPos, regStart, lblSkipInverse, 1);
dan01e12292018-06-27 20:24:59 +00001729 VdbeCoverage(v);
dan09590aa2018-05-25 20:30:17 +00001730 }
dan7262ca92018-07-02 12:07:32 +00001731 if( pMWin->eStart==TK_FOLLOWING ){
1732 sqlite3VdbeAddOp2(v, OP_Next, csrStart, sqlite3VdbeCurrentAddr(v)+2);
1733 VdbeCoverage(v);
1734 sqlite3VdbeAddOp2(v, OP_Goto, 0, lblSkipInverse);
1735 }else{
1736 sqlite3VdbeAddOp2(v, OP_Next, csrStart, sqlite3VdbeCurrentAddr(v)+1);
drh93419162018-07-11 03:27:52 +00001737 VdbeCoverageAlwaysTaken(v);
dan99652dd2018-05-24 17:49:14 +00001738 }
dan7262ca92018-07-02 12:07:32 +00001739 windowAggStep(pParse, pMWin, csrStart, 1, regArg, regSize);
1740 sqlite3VdbeResolveLabel(v, lblSkipInverse);
danc3a20c12018-05-23 20:55:37 +00001741 }
dan99652dd2018-05-24 17:49:14 +00001742 if( pMWin->eEnd==TK_FOLLOWING ){
1743 sqlite3VdbeJumpHere(v, addrIfPos1);
1744 }
dan31f56392018-05-24 21:10:57 +00001745 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
danc3a20c12018-05-23 20:55:37 +00001746
1747 /* flush_partition_done: */
dan31f56392018-05-24 21:10:57 +00001748 sqlite3VdbeResolveLabel(v, lblFlushDone);
danc3a20c12018-05-23 20:55:37 +00001749 sqlite3VdbeAddOp1(v, OP_ResetSorter, pMWin->iEphCsr);
1750 sqlite3VdbeAddOp1(v, OP_Return, regFlushPart);
drh0b3b0dd2018-07-10 05:11:03 +00001751 VdbeComment((v, "end flush_partition subroutine"));
danc3a20c12018-05-23 20:55:37 +00001752
1753 /* Jump to here to skip over flush_partition */
1754 sqlite3VdbeJumpHere(v, addrGoto);
1755}
1756
dan79d45442018-05-26 21:17:29 +00001757/*
dan54a9ab32018-06-14 14:27:05 +00001758** This function does the work of sqlite3WindowCodeStep() for cases that
1759** would normally be handled by windowCodeDefaultStep() when there are
1760** one or more built-in window-functions that require the entire partition
1761** to be cached in a temp table before any rows can be returned. Additionally.
1762** "RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING" is always handled by
1763** this function.
1764**
1765** Pseudo-code corresponding to the VM code generated by this function
1766** for each type of window follows.
1767**
dan79d45442018-05-26 21:17:29 +00001768** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
1769**
danf690b572018-06-01 21:00:08 +00001770** flush_partition:
1771** Once {
1772** OpenDup (iEphCsr -> csrLead)
1773** }
1774** Integer ctr 0
1775** foreach row (csrLead){
1776** if( new peer ){
1777** AggFinal (xValue)
1778** for(i=0; i<ctr; i++){
1779** Gosub addrGosub
1780** Next iEphCsr
1781** }
1782** Integer ctr 0
1783** }
1784** AggStep (csrLead)
1785** Incr ctr
1786** }
1787**
1788** AggFinal (xFinalize)
1789** for(i=0; i<ctr; i++){
1790** Gosub addrGosub
1791** Next iEphCsr
1792** }
1793**
1794** ResetSorter (csr)
1795** Return
1796**
1797** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
dan54a9ab32018-06-14 14:27:05 +00001798**
1799** As above, except that the "if( new peer )" branch is always taken.
1800**
danf690b572018-06-01 21:00:08 +00001801** RANGE BETWEEN CURRENT ROW AND CURRENT ROW
dan54a9ab32018-06-14 14:27:05 +00001802**
1803** As above, except that each of the for() loops becomes:
1804**
1805** for(i=0; i<ctr; i++){
1806** Gosub addrGosub
drh8f26da62018-07-05 21:22:57 +00001807** AggInverse (iEphCsr)
dan54a9ab32018-06-14 14:27:05 +00001808** Next iEphCsr
1809** }
1810**
1811** RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
1812**
1813** flush_partition:
1814** Once {
1815** OpenDup (iEphCsr -> csrLead)
1816** }
1817** foreach row (csrLead) {
1818** AggStep (csrLead)
1819** }
1820** foreach row (iEphCsr) {
1821** Gosub addrGosub
1822** }
1823**
1824** RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
1825**
1826** flush_partition:
1827** Once {
1828** OpenDup (iEphCsr -> csrLead)
1829** }
1830** foreach row (csrLead){
1831** AggStep (csrLead)
1832** }
1833** Rewind (csrLead)
1834** Integer ctr 0
1835** foreach row (csrLead){
1836** if( new peer ){
1837** AggFinal (xValue)
1838** for(i=0; i<ctr; i++){
1839** Gosub addrGosub
drh8f26da62018-07-05 21:22:57 +00001840** AggInverse (iEphCsr)
dan54a9ab32018-06-14 14:27:05 +00001841** Next iEphCsr
1842** }
1843** Integer ctr 0
1844** }
1845** Incr ctr
1846** }
1847**
1848** AggFinal (xFinalize)
1849** for(i=0; i<ctr; i++){
1850** Gosub addrGosub
1851** Next iEphCsr
1852** }
1853**
1854** ResetSorter (csr)
1855** Return
danf690b572018-06-01 21:00:08 +00001856*/
1857static void windowCodeCacheStep(
1858 Parse *pParse,
1859 Select *p,
1860 WhereInfo *pWInfo,
1861 int regGosub,
1862 int addrGosub
1863){
1864 Window *pMWin = p->pWin;
1865 Vdbe *v = sqlite3GetVdbe(pParse);
danf690b572018-06-01 21:00:08 +00001866 int k;
1867 int addr;
1868 ExprList *pPart = pMWin->pPartition;
1869 ExprList *pOrderBy = pMWin->pOrderBy;
dan54a9ab32018-06-14 14:27:05 +00001870 int nPeer = pOrderBy ? pOrderBy->nExpr : 0;
danf690b572018-06-01 21:00:08 +00001871 int regNewPeer;
1872
1873 int addrGoto; /* Address of Goto used to jump flush_par.. */
dan13078ca2018-06-13 20:29:38 +00001874 int addrNext; /* Jump here for next iteration of loop */
danf690b572018-06-01 21:00:08 +00001875 int regFlushPart;
1876 int lblFlushPart;
1877 int csrLead;
1878 int regCtr;
1879 int regArg; /* Register array to martial function args */
dandfa552f2018-06-02 21:04:28 +00001880 int regSize;
dan13078ca2018-06-13 20:29:38 +00001881 int lblEmpty;
dan54a9ab32018-06-14 14:27:05 +00001882 int bReverse = pMWin->pOrderBy && pMWin->eStart==TK_CURRENT
1883 && pMWin->eEnd==TK_UNBOUNDED;
danf690b572018-06-01 21:00:08 +00001884
1885 assert( (pMWin->eStart==TK_UNBOUNDED && pMWin->eEnd==TK_CURRENT)
danec891fd2018-06-06 20:51:02 +00001886 || (pMWin->eStart==TK_UNBOUNDED && pMWin->eEnd==TK_UNBOUNDED)
1887 || (pMWin->eStart==TK_CURRENT && pMWin->eEnd==TK_CURRENT)
dan13078ca2018-06-13 20:29:38 +00001888 || (pMWin->eStart==TK_CURRENT && pMWin->eEnd==TK_UNBOUNDED)
danf690b572018-06-01 21:00:08 +00001889 );
1890
dan13078ca2018-06-13 20:29:38 +00001891 lblEmpty = sqlite3VdbeMakeLabel(v);
danf690b572018-06-01 21:00:08 +00001892 regNewPeer = pParse->nMem+1;
1893 pParse->nMem += nPeer;
1894
1895 /* Allocate register and label for the "flush_partition" sub-routine. */
1896 regFlushPart = ++pParse->nMem;
1897 lblFlushPart = sqlite3VdbeMakeLabel(v);
1898
1899 csrLead = pParse->nTab++;
1900 regCtr = ++pParse->nMem;
1901
dandfa552f2018-06-02 21:04:28 +00001902 windowPartitionCache(pParse, p, pWInfo, regFlushPart, lblFlushPart, &regSize);
danf690b572018-06-01 21:00:08 +00001903 addrGoto = sqlite3VdbeAddOp0(v, OP_Goto);
1904
1905 /* Start of "flush_partition" */
1906 sqlite3VdbeResolveLabel(v, lblFlushPart);
1907 sqlite3VdbeAddOp2(v, OP_Once, 0, sqlite3VdbeCurrentAddr(v)+2);
dan01e12292018-06-27 20:24:59 +00001908 VdbeCoverage(v);
danf690b572018-06-01 21:00:08 +00001909 sqlite3VdbeAddOp2(v, OP_OpenDup, csrLead, pMWin->iEphCsr);
1910
1911 /* Initialize the accumulator register for each window function to NULL */
dan2e605682018-06-07 15:54:26 +00001912 regArg = windowInitAccum(pParse, pMWin);
danf690b572018-06-01 21:00:08 +00001913
1914 sqlite3VdbeAddOp2(v, OP_Integer, 0, regCtr);
dan13078ca2018-06-13 20:29:38 +00001915 sqlite3VdbeAddOp2(v, OP_Rewind, csrLead, lblEmpty);
dan01e12292018-06-27 20:24:59 +00001916 VdbeCoverage(v);
dan13078ca2018-06-13 20:29:38 +00001917 sqlite3VdbeAddOp2(v, OP_Rewind, pMWin->iEphCsr, lblEmpty);
dan01e12292018-06-27 20:24:59 +00001918 VdbeCoverageNeverTaken(v);
danf690b572018-06-01 21:00:08 +00001919
dan13078ca2018-06-13 20:29:38 +00001920 if( bReverse ){
drhc7bf5712018-07-09 22:49:01 +00001921 int addr2 = sqlite3VdbeCurrentAddr(v);
dan13078ca2018-06-13 20:29:38 +00001922 windowAggStep(pParse, pMWin, csrLead, 0, regArg, regSize);
drhc7bf5712018-07-09 22:49:01 +00001923 sqlite3VdbeAddOp2(v, OP_Next, csrLead, addr2);
dan01e12292018-06-27 20:24:59 +00001924 VdbeCoverage(v);
dan13078ca2018-06-13 20:29:38 +00001925 sqlite3VdbeAddOp2(v, OP_Rewind, csrLead, lblEmpty);
dan01e12292018-06-27 20:24:59 +00001926 VdbeCoverageNeverTaken(v);
dan13078ca2018-06-13 20:29:38 +00001927 }
1928 addrNext = sqlite3VdbeCurrentAddr(v);
1929
1930 if( pOrderBy && (pMWin->eEnd==TK_CURRENT || pMWin->eStart==TK_CURRENT) ){
1931 int bCurrent = (pMWin->eStart==TK_CURRENT);
danec891fd2018-06-06 20:51:02 +00001932 int addrJump = 0; /* Address of OP_Jump below */
1933 if( pMWin->eType==TK_RANGE ){
1934 int iOff = pMWin->nBufferCol + (pPart ? pPart->nExpr : 0);
1935 int regPeer = pMWin->regPart + (pPart ? pPart->nExpr : 0);
1936 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pOrderBy, 0, 0);
1937 for(k=0; k<nPeer; k++){
1938 sqlite3VdbeAddOp3(v, OP_Column, csrLead, iOff+k, regNewPeer+k);
1939 }
1940 addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPeer, regPeer, nPeer);
1941 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
1942 addrJump = sqlite3VdbeAddOp3(v, OP_Jump, addr+2, 0, addr+2);
dan01e12292018-06-27 20:24:59 +00001943 VdbeCoverage(v);
danec891fd2018-06-06 20:51:02 +00001944 sqlite3VdbeAddOp3(v, OP_Copy, regNewPeer, regPeer, nPeer-1);
danf690b572018-06-01 21:00:08 +00001945 }
1946
dan13078ca2018-06-13 20:29:38 +00001947 windowReturnRows(pParse, pMWin, regCtr, regGosub, addrGosub,
danec891fd2018-06-06 20:51:02 +00001948 (bCurrent ? regArg : 0), (bCurrent ? regSize : 0)
1949 );
1950 if( addrJump ) sqlite3VdbeJumpHere(v, addrJump);
danf690b572018-06-01 21:00:08 +00001951 }
1952
dan13078ca2018-06-13 20:29:38 +00001953 if( bReverse==0 ){
1954 windowAggStep(pParse, pMWin, csrLead, 0, regArg, regSize);
1955 }
danf690b572018-06-01 21:00:08 +00001956 sqlite3VdbeAddOp2(v, OP_AddImm, regCtr, 1);
dan13078ca2018-06-13 20:29:38 +00001957 sqlite3VdbeAddOp2(v, OP_Next, csrLead, addrNext);
dan01e12292018-06-27 20:24:59 +00001958 VdbeCoverage(v);
danf690b572018-06-01 21:00:08 +00001959
dan13078ca2018-06-13 20:29:38 +00001960 windowReturnRows(pParse, pMWin, regCtr, regGosub, addrGosub, 0, 0);
danf690b572018-06-01 21:00:08 +00001961
dan13078ca2018-06-13 20:29:38 +00001962 sqlite3VdbeResolveLabel(v, lblEmpty);
danf690b572018-06-01 21:00:08 +00001963 sqlite3VdbeAddOp1(v, OP_ResetSorter, pMWin->iEphCsr);
1964 sqlite3VdbeAddOp1(v, OP_Return, regFlushPart);
1965
1966 /* Jump to here to skip over flush_partition */
1967 sqlite3VdbeJumpHere(v, addrGoto);
1968}
1969
1970
1971/*
1972** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
1973**
dan79d45442018-05-26 21:17:29 +00001974** ...
1975** if( new partition ){
1976** AggFinal (xFinalize)
1977** Gosub addrGosub
1978** ResetSorter eph-table
1979** }
1980** else if( new peer ){
1981** AggFinal (xValue)
1982** Gosub addrGosub
1983** ResetSorter eph-table
1984** }
1985** AggStep
1986** Insert (record into eph-table)
1987** sqlite3WhereEnd()
1988** AggFinal (xFinalize)
1989** Gosub addrGosub
danf690b572018-06-01 21:00:08 +00001990**
1991** RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
1992**
1993** As above, except take no action for a "new peer". Invoke
1994** the sub-routine once only for each partition.
1995**
1996** RANGE BETWEEN CURRENT ROW AND CURRENT ROW
1997**
1998** As above, except that the "new peer" condition is handled in the
1999** same way as "new partition" (so there is no "else if" block).
2000**
2001** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
2002**
2003** As above, except assume every row is a "new peer".
dan79d45442018-05-26 21:17:29 +00002004*/
danc3a20c12018-05-23 20:55:37 +00002005static void windowCodeDefaultStep(
2006 Parse *pParse,
2007 Select *p,
2008 WhereInfo *pWInfo,
2009 int regGosub,
2010 int addrGosub
2011){
2012 Window *pMWin = p->pWin;
2013 Vdbe *v = sqlite3GetVdbe(pParse);
danc3a20c12018-05-23 20:55:37 +00002014 int k;
2015 int iSubCsr = p->pSrc->a[0].iCursor;
2016 int nSub = p->pSrc->a[0].pTab->nCol;
2017 int reg = pParse->nMem+1;
2018 int regRecord = reg+nSub;
2019 int regRowid = regRecord+1;
2020 int addr;
dand6f784e2018-05-28 18:30:45 +00002021 ExprList *pPart = pMWin->pPartition;
2022 ExprList *pOrderBy = pMWin->pOrderBy;
danc3a20c12018-05-23 20:55:37 +00002023
dan79d45442018-05-26 21:17:29 +00002024 assert( pMWin->eType==TK_RANGE
2025 || (pMWin->eStart==TK_UNBOUNDED && pMWin->eEnd==TK_CURRENT)
2026 );
2027
dand6f784e2018-05-28 18:30:45 +00002028 assert( (pMWin->eStart==TK_UNBOUNDED && pMWin->eEnd==TK_CURRENT)
2029 || (pMWin->eStart==TK_UNBOUNDED && pMWin->eEnd==TK_UNBOUNDED)
2030 || (pMWin->eStart==TK_CURRENT && pMWin->eEnd==TK_CURRENT)
2031 || (pMWin->eStart==TK_CURRENT && pMWin->eEnd==TK_UNBOUNDED && !pOrderBy)
2032 );
2033
2034 if( pMWin->eEnd==TK_UNBOUNDED ){
2035 pOrderBy = 0;
2036 }
2037
danc3a20c12018-05-23 20:55:37 +00002038 pParse->nMem += nSub + 2;
2039
drhb0225bc2018-07-10 20:50:27 +00002040 /* Load the individual column values of the row returned by
2041 ** the sub-select into an array of registers. */
danc3a20c12018-05-23 20:55:37 +00002042 for(k=0; k<nSub; k++){
2043 sqlite3VdbeAddOp3(v, OP_Column, iSubCsr, k, reg+k);
2044 }
2045
2046 /* Check if this is the start of a new partition or peer group. */
dand6f784e2018-05-28 18:30:45 +00002047 if( pPart || pOrderBy ){
danc3a20c12018-05-23 20:55:37 +00002048 int nPart = (pPart ? pPart->nExpr : 0);
danc3a20c12018-05-23 20:55:37 +00002049 int addrGoto = 0;
2050 int addrJump = 0;
dand6f784e2018-05-28 18:30:45 +00002051 int nPeer = (pOrderBy ? pOrderBy->nExpr : 0);
danc3a20c12018-05-23 20:55:37 +00002052
2053 if( pPart ){
2054 int regNewPart = reg + pMWin->nBufferCol;
2055 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pPart, 0, 0);
2056 addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPart, pMWin->regPart,nPart);
2057 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
2058 addrJump = sqlite3VdbeAddOp3(v, OP_Jump, addr+2, 0, addr+2);
drh93419162018-07-11 03:27:52 +00002059 VdbeCoverageEqNe(v);
dand6f784e2018-05-28 18:30:45 +00002060 windowAggFinal(pParse, pMWin, 1);
danc3a20c12018-05-23 20:55:37 +00002061 if( pOrderBy ){
2062 addrGoto = sqlite3VdbeAddOp0(v, OP_Goto);
2063 }
2064 }
2065
2066 if( pOrderBy ){
2067 int regNewPeer = reg + pMWin->nBufferCol + nPart;
2068 int regPeer = pMWin->regPart + nPart;
2069
danc3a20c12018-05-23 20:55:37 +00002070 if( addrJump ) sqlite3VdbeJumpHere(v, addrJump);
dan79d45442018-05-26 21:17:29 +00002071 if( pMWin->eType==TK_RANGE ){
2072 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pOrderBy, 0, 0);
2073 addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPeer, regPeer, nPeer);
2074 sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
2075 addrJump = sqlite3VdbeAddOp3(v, OP_Jump, addr+2, 0, addr+2);
dan01e12292018-06-27 20:24:59 +00002076 VdbeCoverage(v);
dan79d45442018-05-26 21:17:29 +00002077 }else{
2078 addrJump = 0;
2079 }
dand6f784e2018-05-28 18:30:45 +00002080 windowAggFinal(pParse, pMWin, pMWin->eStart==TK_CURRENT);
danc3a20c12018-05-23 20:55:37 +00002081 if( addrGoto ) sqlite3VdbeJumpHere(v, addrGoto);
2082 }
2083
dandacf1de2018-06-08 16:11:55 +00002084 sqlite3VdbeAddOp2(v, OP_Rewind, pMWin->iEphCsr,sqlite3VdbeCurrentAddr(v)+3);
dan01e12292018-06-27 20:24:59 +00002085 VdbeCoverage(v);
danc3a20c12018-05-23 20:55:37 +00002086 sqlite3VdbeAddOp2(v, OP_Gosub, regGosub, addrGosub);
dandacf1de2018-06-08 16:11:55 +00002087 sqlite3VdbeAddOp2(v, OP_Next, pMWin->iEphCsr, sqlite3VdbeCurrentAddr(v)-1);
dan01e12292018-06-27 20:24:59 +00002088 VdbeCoverage(v);
dandacf1de2018-06-08 16:11:55 +00002089
danc3a20c12018-05-23 20:55:37 +00002090 sqlite3VdbeAddOp1(v, OP_ResetSorter, pMWin->iEphCsr);
2091 sqlite3VdbeAddOp3(
2092 v, OP_Copy, reg+pMWin->nBufferCol, pMWin->regPart, nPart+nPeer-1
2093 );
2094
dan79d45442018-05-26 21:17:29 +00002095 if( addrJump ) sqlite3VdbeJumpHere(v, addrJump);
danc3a20c12018-05-23 20:55:37 +00002096 }
2097
2098 /* Invoke step function for window functions */
dandfa552f2018-06-02 21:04:28 +00002099 windowAggStep(pParse, pMWin, -1, 0, reg, 0);
danc3a20c12018-05-23 20:55:37 +00002100
2101 /* Buffer the current row in the ephemeral table. */
2102 if( pMWin->nBufferCol>0 ){
2103 sqlite3VdbeAddOp3(v, OP_MakeRecord, reg, pMWin->nBufferCol, regRecord);
2104 }else{
2105 sqlite3VdbeAddOp2(v, OP_Blob, 0, regRecord);
2106 sqlite3VdbeAppendP4(v, (void*)"", 0);
2107 }
2108 sqlite3VdbeAddOp2(v, OP_NewRowid, pMWin->iEphCsr, regRowid);
2109 sqlite3VdbeAddOp3(v, OP_Insert, pMWin->iEphCsr, regRecord, regRowid);
2110
2111 /* End the database scan loop. */
2112 sqlite3WhereEnd(pWInfo);
2113
dand6f784e2018-05-28 18:30:45 +00002114 windowAggFinal(pParse, pMWin, 1);
dandacf1de2018-06-08 16:11:55 +00002115 sqlite3VdbeAddOp2(v, OP_Rewind, pMWin->iEphCsr,sqlite3VdbeCurrentAddr(v)+3);
dan01e12292018-06-27 20:24:59 +00002116 VdbeCoverage(v);
danc3a20c12018-05-23 20:55:37 +00002117 sqlite3VdbeAddOp2(v, OP_Gosub, regGosub, addrGosub);
dandacf1de2018-06-08 16:11:55 +00002118 sqlite3VdbeAddOp2(v, OP_Next, pMWin->iEphCsr, sqlite3VdbeCurrentAddr(v)-1);
dan01e12292018-06-27 20:24:59 +00002119 VdbeCoverage(v);
danc3a20c12018-05-23 20:55:37 +00002120}
2121
dan13078ca2018-06-13 20:29:38 +00002122/*
2123** Allocate and return a duplicate of the Window object indicated by the
2124** third argument. Set the Window.pOwner field of the new object to
2125** pOwner.
2126*/
dan2a11bb22018-06-11 20:50:25 +00002127Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p){
dandacf1de2018-06-08 16:11:55 +00002128 Window *pNew = 0;
2129 if( p ){
2130 pNew = sqlite3DbMallocZero(db, sizeof(Window));
2131 if( pNew ){
danc95f38d2018-06-18 20:34:43 +00002132 pNew->zName = sqlite3DbStrDup(db, p->zName);
dandacf1de2018-06-08 16:11:55 +00002133 pNew->pFilter = sqlite3ExprDup(db, p->pFilter, 0);
2134 pNew->pPartition = sqlite3ExprListDup(db, p->pPartition, 0);
2135 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, 0);
2136 pNew->eType = p->eType;
2137 pNew->eEnd = p->eEnd;
2138 pNew->eStart = p->eStart;
dan303451a2018-06-14 20:52:08 +00002139 pNew->pStart = sqlite3ExprDup(db, p->pStart, 0);
2140 pNew->pEnd = sqlite3ExprDup(db, p->pEnd, 0);
dan2a11bb22018-06-11 20:50:25 +00002141 pNew->pOwner = pOwner;
dandacf1de2018-06-08 16:11:55 +00002142 }
2143 }
2144 return pNew;
2145}
danc3a20c12018-05-23 20:55:37 +00002146
danf9eae182018-05-21 19:45:11 +00002147/*
danc95f38d2018-06-18 20:34:43 +00002148** Return a copy of the linked list of Window objects passed as the
2149** second argument.
2150*/
2151Window *sqlite3WindowListDup(sqlite3 *db, Window *p){
2152 Window *pWin;
2153 Window *pRet = 0;
2154 Window **pp = &pRet;
2155
2156 for(pWin=p; pWin; pWin=pWin->pNextWin){
2157 *pp = sqlite3WindowDup(db, 0, pWin);
2158 if( *pp==0 ) break;
2159 pp = &((*pp)->pNextWin);
2160 }
2161
2162 return pRet;
2163}
2164
2165/*
dan2a11bb22018-06-11 20:50:25 +00002166** sqlite3WhereBegin() has already been called for the SELECT statement
2167** passed as the second argument when this function is invoked. It generates
2168** code to populate the Window.regResult register for each window function and
2169** invoke the sub-routine at instruction addrGosub once for each row.
2170** This function calls sqlite3WhereEnd() before returning.
danf9eae182018-05-21 19:45:11 +00002171*/
2172void sqlite3WindowCodeStep(
dan2a11bb22018-06-11 20:50:25 +00002173 Parse *pParse, /* Parse context */
2174 Select *p, /* Rewritten SELECT statement */
2175 WhereInfo *pWInfo, /* Context returned by sqlite3WhereBegin() */
2176 int regGosub, /* Register for OP_Gosub */
2177 int addrGosub /* OP_Gosub here to return each row */
danf9eae182018-05-21 19:45:11 +00002178){
danf9eae182018-05-21 19:45:11 +00002179 Window *pMWin = p->pWin;
danf9eae182018-05-21 19:45:11 +00002180
dan54a9ab32018-06-14 14:27:05 +00002181 /* There are three different functions that may be used to do the work
2182 ** of this one, depending on the window frame and the specific built-in
2183 ** window functions used (if any).
2184 **
2185 ** windowCodeRowExprStep() handles all "ROWS" window frames, except for:
dan26522d12018-06-11 18:16:51 +00002186 **
dan13078ca2018-06-13 20:29:38 +00002187 ** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
dan54a9ab32018-06-14 14:27:05 +00002188 **
2189 ** The exception is because windowCodeRowExprStep() implements all window
2190 ** frame types by caching the entire partition in a temp table, and
2191 ** "ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW" is easy enough to
2192 ** implement without such a cache.
2193 **
2194 ** windowCodeCacheStep() is used for:
2195 **
2196 ** RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
2197 **
2198 ** It is also used for anything not handled by windowCodeRowExprStep()
2199 ** that invokes a built-in window function that requires the entire
2200 ** partition to be cached in a temp table before any rows are returned
2201 ** (e.g. nth_value() or percent_rank()).
2202 **
2203 ** Finally, assuming there is no built-in window function that requires
2204 ** the partition to be cached, windowCodeDefaultStep() is used for:
2205 **
2206 ** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
2207 ** RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
2208 ** RANGE BETWEEN CURRENT ROW AND CURRENT ROW
2209 ** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
2210 **
2211 ** windowCodeDefaultStep() is the only one of the three functions that
2212 ** does not cache each partition in a temp table before beginning to
2213 ** return rows.
dan26522d12018-06-11 18:16:51 +00002214 */
dan54a9ab32018-06-14 14:27:05 +00002215 if( pMWin->eType==TK_ROWS
2216 && (pMWin->eStart!=TK_UNBOUNDED||pMWin->eEnd!=TK_CURRENT||!pMWin->pOrderBy)
dan09590aa2018-05-25 20:30:17 +00002217 ){
drhc3649412018-07-10 22:24:14 +00002218 VdbeModuleComment((pParse->pVdbe, "Begin RowExprStep()"));
danc3a20c12018-05-23 20:55:37 +00002219 windowCodeRowExprStep(pParse, p, pWInfo, regGosub, addrGosub);
dan13078ca2018-06-13 20:29:38 +00002220 }else{
2221 Window *pWin;
dan54a9ab32018-06-14 14:27:05 +00002222 int bCache = 0; /* True to use CacheStep() */
danf9eae182018-05-21 19:45:11 +00002223
dan54a9ab32018-06-14 14:27:05 +00002224 if( pMWin->eStart==TK_CURRENT && pMWin->eEnd==TK_UNBOUNDED ){
dan13078ca2018-06-13 20:29:38 +00002225 bCache = 1;
2226 }else{
dan13078ca2018-06-13 20:29:38 +00002227 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
2228 FuncDef *pFunc = pWin->pFunc;
2229 if( (pFunc->funcFlags & SQLITE_FUNC_WINDOW_SIZE)
drh19dc4d42018-07-08 01:02:26 +00002230 || (pFunc->zName==nth_valueName)
2231 || (pFunc->zName==first_valueName)
2232 || (pFunc->zName==leadName)
2233 || (pFunc->zName==lagName)
dan54a9ab32018-06-14 14:27:05 +00002234 ){
dan13078ca2018-06-13 20:29:38 +00002235 bCache = 1;
2236 break;
2237 }
2238 }
2239 }
2240
2241 /* Otherwise, call windowCodeDefaultStep(). */
2242 if( bCache ){
drhc3649412018-07-10 22:24:14 +00002243 VdbeModuleComment((pParse->pVdbe, "Begin CacheStep()"));
dandfa552f2018-06-02 21:04:28 +00002244 windowCodeCacheStep(pParse, p, pWInfo, regGosub, addrGosub);
dan13078ca2018-06-13 20:29:38 +00002245 }else{
drhc3649412018-07-10 22:24:14 +00002246 VdbeModuleComment((pParse->pVdbe, "Begin DefaultStep()"));
dan13078ca2018-06-13 20:29:38 +00002247 windowCodeDefaultStep(pParse, p, pWInfo, regGosub, addrGosub);
dandfa552f2018-06-02 21:04:28 +00002248 }
danf690b572018-06-01 21:00:08 +00002249 }
danf9eae182018-05-21 19:45:11 +00002250}
2251
dan67a9b8e2018-06-22 20:51:35 +00002252#endif /* SQLITE_OMIT_WINDOWFUNC */