Fossil SCM

Pull in all the latest trunk changes.

drh 2013-06-20 11:02 UTC ticket-967cedbf20 merge
Commit 6ec8818ff19e194b106daf8c74722f81d4fb4310
--- .fossil-settings/ignore-glob
+++ .fossil-settings/ignore-glob
@@ -1,4 +1,4 @@
1
-compat/openssl-1.0.1e/*
2
-compat/tcl-8.6/*
1
+compat/openssl*
2
+compat/tcl*
33
fossil
44
fossil.exe
55
--- .fossil-settings/ignore-glob
+++ .fossil-settings/ignore-glob
@@ -1,4 +1,4 @@
1 compat/openssl-1.0.1e/*
2 compat/tcl-8.6/*
3 fossil
4 fossil.exe
5
--- .fossil-settings/ignore-glob
+++ .fossil-settings/ignore-glob
@@ -1,4 +1,4 @@
1 compat/openssl*
2 compat/tcl*
3 fossil
4 fossil.exe
5
--- .fossil-settings/keep-glob
+++ .fossil-settings/keep-glob
@@ -1,2 +1,4 @@
1
+compat/openssl*
2
+compat/tcl*
13
fossil
24
fossil.exe
35
--- .fossil-settings/keep-glob
+++ .fossil-settings/keep-glob
@@ -1,2 +1,4 @@
 
 
1 fossil
2 fossil.exe
3
--- .fossil-settings/keep-glob
+++ .fossil-settings/keep-glob
@@ -1,2 +1,4 @@
1 compat/openssl*
2 compat/tcl*
3 fossil
4 fossil.exe
5
+67 -23
--- src/shell.c
+++ src/shell.c
@@ -1521,25 +1521,18 @@
15211521
}
15221522
z[j] = 0;
15231523
}
15241524
15251525
/*
1526
-** Interpret zArg as a boolean value. Return either 0 or 1.
1526
+** Return the value of a hexadecimal digit. Return -1 if the input
1527
+** is not a hex digit.
15271528
*/
1528
-static int booleanValue(char *zArg){
1529
- int i;
1530
- for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
1531
- if( i>0 && zArg[i]==0 ) return atoi(zArg);
1532
- if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
1533
- return 1;
1534
- }
1535
- if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
1536
- return 0;
1537
- }
1538
- fprintf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
1539
- zArg);
1540
- return 0;
1529
+static int hexDigitValue(char c){
1530
+ if( c>='0' && c<='9' ) return c - '0';
1531
+ if( c>='a' && c<='f' ) return c - 'a' + 10;
1532
+ if( c>='A' && c<='F' ) return c - 'A' + 10;
1533
+ return -1;
15411534
}
15421535
15431536
/*
15441537
** Interpret zArg as an integer value, possibly with suffixes.
15451538
*/
@@ -1562,22 +1555,54 @@
15621555
isNeg = 1;
15631556
zArg++;
15641557
}else if( zArg[0]=='+' ){
15651558
zArg++;
15661559
}
1567
- while( isdigit(zArg[0]) ){
1568
- v = v*10 + zArg[0] - '0';
1569
- zArg++;
1560
+ if( zArg[0]=='0' && zArg[1]=='x' ){
1561
+ int x;
1562
+ zArg += 2;
1563
+ while( (x = hexDigitValue(zArg[0]))>=0 ){
1564
+ v = (v<<4) + x;
1565
+ zArg++;
1566
+ }
1567
+ }else{
1568
+ while( IsDigit(zArg[0]) ){
1569
+ v = v*10 + zArg[0] - '0';
1570
+ zArg++;
1571
+ }
15701572
}
1571
- for(i=0; i<sizeof(aMult)/sizeof(aMult[0]); i++){
1573
+ for(i=0; i<ArraySize(aMult); i++){
15721574
if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
15731575
v *= aMult[i].iMult;
15741576
break;
15751577
}
15761578
}
15771579
return isNeg? -v : v;
15781580
}
1581
+
1582
+/*
1583
+** Interpret zArg as either an integer or a boolean value. Return 1 or 0
1584
+** for TRUE and FALSE. Return the integer value if appropriate.
1585
+*/
1586
+static int booleanValue(char *zArg){
1587
+ int i;
1588
+ if( zArg[0]=='0' && zArg[1]=='x' ){
1589
+ for(i=2; hexDigitValue(zArg[i])>=0; i++){}
1590
+ }else{
1591
+ for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
1592
+ }
1593
+ if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
1594
+ if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
1595
+ return 1;
1596
+ }
1597
+ if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
1598
+ return 0;
1599
+ }
1600
+ fprintf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
1601
+ zArg);
1602
+ return 0;
1603
+}
15791604
15801605
/*
15811606
** Close an output file, assuming it is not stderr or stdout
15821607
*/
15831608
static void output_file_close(FILE *f){
@@ -1806,11 +1831,11 @@
18061831
if( c=='e' && strncmp(azArg[0], "echo", n)==0 && nArg>1 && nArg<3 ){
18071832
p->echoOn = booleanValue(azArg[1]);
18081833
}else
18091834
18101835
if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
1811
- if( nArg>1 && (rc = atoi(azArg[1]))!=0 ) exit(rc);
1836
+ if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
18121837
rc = 2;
18131838
}else
18141839
18151840
if( c=='e' && strncmp(azArg[0], "explain", n)==0 && nArg<3 ){
18161841
int val = nArg>=2 ? booleanValue(azArg[1]) : 1;
@@ -2302,10 +2327,29 @@
23022327
rc = 1;
23032328
}else{
23042329
rc = 0;
23052330
}
23062331
}else
2332
+
2333
+ /* Undocumented commands for internal testing. Subject to change
2334
+ ** without notice. */
2335
+ if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
2336
+ if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
2337
+ int i, v;
2338
+ for(i=1; i<nArg; i++){
2339
+ v = booleanValue(azArg[i]);
2340
+ fprintf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
2341
+ }
2342
+ }
2343
+ if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
2344
+ int i; sqlite3_int64 v;
2345
+ for(i=1; i<nArg; i++){
2346
+ v = integerValue(azArg[i]);
2347
+ fprintf(p->out, "%s: %lld 0x%llx\n", azArg[i], v, v);
2348
+ }
2349
+ }
2350
+ }else
23072351
23082352
if( c=='s' && strncmp(azArg[0], "separator", n)==0 && nArg==2 ){
23092353
sqlite3_snprintf(sizeof(p->separator), p->separator,
23102354
"%.*s", (int)sizeof(p->separator)-1, azArg[1]);
23112355
}else
@@ -2456,11 +2500,11 @@
24562500
testctrl = -1;
24572501
break;
24582502
}
24592503
}
24602504
}
2461
- if( testctrl<0 ) testctrl = atoi(azArg[1]);
2505
+ if( testctrl<0 ) testctrl = (int)integerValue(azArg[1]);
24622506
if( (testctrl<SQLITE_TESTCTRL_FIRST) || (testctrl>SQLITE_TESTCTRL_LAST) ){
24632507
fprintf(stderr,"Error: invalid testctrl option: %s\n", azArg[1]);
24642508
}else{
24652509
switch(testctrl){
24662510
@@ -2503,11 +2547,11 @@
25032547
25042548
/* sqlite3_test_control(int, int) */
25052549
case SQLITE_TESTCTRL_ASSERT:
25062550
case SQLITE_TESTCTRL_ALWAYS:
25072551
if( nArg==3 ){
2508
- int opt = atoi(azArg[2]);
2552
+ int opt = booleanValue(azArg[2]);
25092553
rc = sqlite3_test_control(testctrl, opt);
25102554
fprintf(p->out, "%d (0x%08x)\n", rc, rc);
25112555
} else {
25122556
fprintf(stderr,"Error: testctrl %s takes a single int option\n",
25132557
azArg[1]);
@@ -2540,11 +2584,11 @@
25402584
}
25412585
}else
25422586
25432587
if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 && nArg==2 ){
25442588
open_db(p);
2545
- sqlite3_busy_timeout(p->db, atoi(azArg[1]));
2589
+ sqlite3_busy_timeout(p->db, (int)integerValue(azArg[1]));
25462590
}else
25472591
25482592
if( HAS_TIMER && c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0
25492593
&& nArg==2
25502594
){
@@ -2590,11 +2634,11 @@
25902634
25912635
if( c=='w' && strncmp(azArg[0], "width", n)==0 && nArg>1 ){
25922636
int j;
25932637
assert( nArg<=ArraySize(azArg) );
25942638
for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
2595
- p->colWidth[j-1] = atoi(azArg[j]);
2639
+ p->colWidth[j-1] = (int)integerValue(azArg[j]);
25962640
}
25972641
}else
25982642
25992643
{
26002644
fprintf(stderr, "Error: unknown command or invalid arguments: "
26012645
--- src/shell.c
+++ src/shell.c
@@ -1521,25 +1521,18 @@
1521 }
1522 z[j] = 0;
1523 }
1524
1525 /*
1526 ** Interpret zArg as a boolean value. Return either 0 or 1.
 
1527 */
1528 static int booleanValue(char *zArg){
1529 int i;
1530 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
1531 if( i>0 && zArg[i]==0 ) return atoi(zArg);
1532 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
1533 return 1;
1534 }
1535 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
1536 return 0;
1537 }
1538 fprintf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
1539 zArg);
1540 return 0;
1541 }
1542
1543 /*
1544 ** Interpret zArg as an integer value, possibly with suffixes.
1545 */
@@ -1562,22 +1555,54 @@
1562 isNeg = 1;
1563 zArg++;
1564 }else if( zArg[0]=='+' ){
1565 zArg++;
1566 }
1567 while( isdigit(zArg[0]) ){
1568 v = v*10 + zArg[0] - '0';
1569 zArg++;
 
 
 
 
 
 
 
 
 
1570 }
1571 for(i=0; i<sizeof(aMult)/sizeof(aMult[0]); i++){
1572 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
1573 v *= aMult[i].iMult;
1574 break;
1575 }
1576 }
1577 return isNeg? -v : v;
1578 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1579
1580 /*
1581 ** Close an output file, assuming it is not stderr or stdout
1582 */
1583 static void output_file_close(FILE *f){
@@ -1806,11 +1831,11 @@
1806 if( c=='e' && strncmp(azArg[0], "echo", n)==0 && nArg>1 && nArg<3 ){
1807 p->echoOn = booleanValue(azArg[1]);
1808 }else
1809
1810 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
1811 if( nArg>1 && (rc = atoi(azArg[1]))!=0 ) exit(rc);
1812 rc = 2;
1813 }else
1814
1815 if( c=='e' && strncmp(azArg[0], "explain", n)==0 && nArg<3 ){
1816 int val = nArg>=2 ? booleanValue(azArg[1]) : 1;
@@ -2302,10 +2327,29 @@
2302 rc = 1;
2303 }else{
2304 rc = 0;
2305 }
2306 }else
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2307
2308 if( c=='s' && strncmp(azArg[0], "separator", n)==0 && nArg==2 ){
2309 sqlite3_snprintf(sizeof(p->separator), p->separator,
2310 "%.*s", (int)sizeof(p->separator)-1, azArg[1]);
2311 }else
@@ -2456,11 +2500,11 @@
2456 testctrl = -1;
2457 break;
2458 }
2459 }
2460 }
2461 if( testctrl<0 ) testctrl = atoi(azArg[1]);
2462 if( (testctrl<SQLITE_TESTCTRL_FIRST) || (testctrl>SQLITE_TESTCTRL_LAST) ){
2463 fprintf(stderr,"Error: invalid testctrl option: %s\n", azArg[1]);
2464 }else{
2465 switch(testctrl){
2466
@@ -2503,11 +2547,11 @@
2503
2504 /* sqlite3_test_control(int, int) */
2505 case SQLITE_TESTCTRL_ASSERT:
2506 case SQLITE_TESTCTRL_ALWAYS:
2507 if( nArg==3 ){
2508 int opt = atoi(azArg[2]);
2509 rc = sqlite3_test_control(testctrl, opt);
2510 fprintf(p->out, "%d (0x%08x)\n", rc, rc);
2511 } else {
2512 fprintf(stderr,"Error: testctrl %s takes a single int option\n",
2513 azArg[1]);
@@ -2540,11 +2584,11 @@
2540 }
2541 }else
2542
2543 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 && nArg==2 ){
2544 open_db(p);
2545 sqlite3_busy_timeout(p->db, atoi(azArg[1]));
2546 }else
2547
2548 if( HAS_TIMER && c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0
2549 && nArg==2
2550 ){
@@ -2590,11 +2634,11 @@
2590
2591 if( c=='w' && strncmp(azArg[0], "width", n)==0 && nArg>1 ){
2592 int j;
2593 assert( nArg<=ArraySize(azArg) );
2594 for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
2595 p->colWidth[j-1] = atoi(azArg[j]);
2596 }
2597 }else
2598
2599 {
2600 fprintf(stderr, "Error: unknown command or invalid arguments: "
2601
--- src/shell.c
+++ src/shell.c
@@ -1521,25 +1521,18 @@
1521 }
1522 z[j] = 0;
1523 }
1524
1525 /*
1526 ** Return the value of a hexadecimal digit. Return -1 if the input
1527 ** is not a hex digit.
1528 */
1529 static int hexDigitValue(char c){
1530 if( c>='0' && c<='9' ) return c - '0';
1531 if( c>='a' && c<='f' ) return c - 'a' + 10;
1532 if( c>='A' && c<='F' ) return c - 'A' + 10;
1533 return -1;
 
 
 
 
 
 
 
 
1534 }
1535
1536 /*
1537 ** Interpret zArg as an integer value, possibly with suffixes.
1538 */
@@ -1562,22 +1555,54 @@
1555 isNeg = 1;
1556 zArg++;
1557 }else if( zArg[0]=='+' ){
1558 zArg++;
1559 }
1560 if( zArg[0]=='0' && zArg[1]=='x' ){
1561 int x;
1562 zArg += 2;
1563 while( (x = hexDigitValue(zArg[0]))>=0 ){
1564 v = (v<<4) + x;
1565 zArg++;
1566 }
1567 }else{
1568 while( IsDigit(zArg[0]) ){
1569 v = v*10 + zArg[0] - '0';
1570 zArg++;
1571 }
1572 }
1573 for(i=0; i<ArraySize(aMult); i++){
1574 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
1575 v *= aMult[i].iMult;
1576 break;
1577 }
1578 }
1579 return isNeg? -v : v;
1580 }
1581
1582 /*
1583 ** Interpret zArg as either an integer or a boolean value. Return 1 or 0
1584 ** for TRUE and FALSE. Return the integer value if appropriate.
1585 */
1586 static int booleanValue(char *zArg){
1587 int i;
1588 if( zArg[0]=='0' && zArg[1]=='x' ){
1589 for(i=2; hexDigitValue(zArg[i])>=0; i++){}
1590 }else{
1591 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
1592 }
1593 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
1594 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
1595 return 1;
1596 }
1597 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
1598 return 0;
1599 }
1600 fprintf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
1601 zArg);
1602 return 0;
1603 }
1604
1605 /*
1606 ** Close an output file, assuming it is not stderr or stdout
1607 */
1608 static void output_file_close(FILE *f){
@@ -1806,11 +1831,11 @@
1831 if( c=='e' && strncmp(azArg[0], "echo", n)==0 && nArg>1 && nArg<3 ){
1832 p->echoOn = booleanValue(azArg[1]);
1833 }else
1834
1835 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
1836 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
1837 rc = 2;
1838 }else
1839
1840 if( c=='e' && strncmp(azArg[0], "explain", n)==0 && nArg<3 ){
1841 int val = nArg>=2 ? booleanValue(azArg[1]) : 1;
@@ -2302,10 +2327,29 @@
2327 rc = 1;
2328 }else{
2329 rc = 0;
2330 }
2331 }else
2332
2333 /* Undocumented commands for internal testing. Subject to change
2334 ** without notice. */
2335 if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
2336 if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
2337 int i, v;
2338 for(i=1; i<nArg; i++){
2339 v = booleanValue(azArg[i]);
2340 fprintf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
2341 }
2342 }
2343 if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
2344 int i; sqlite3_int64 v;
2345 for(i=1; i<nArg; i++){
2346 v = integerValue(azArg[i]);
2347 fprintf(p->out, "%s: %lld 0x%llx\n", azArg[i], v, v);
2348 }
2349 }
2350 }else
2351
2352 if( c=='s' && strncmp(azArg[0], "separator", n)==0 && nArg==2 ){
2353 sqlite3_snprintf(sizeof(p->separator), p->separator,
2354 "%.*s", (int)sizeof(p->separator)-1, azArg[1]);
2355 }else
@@ -2456,11 +2500,11 @@
2500 testctrl = -1;
2501 break;
2502 }
2503 }
2504 }
2505 if( testctrl<0 ) testctrl = (int)integerValue(azArg[1]);
2506 if( (testctrl<SQLITE_TESTCTRL_FIRST) || (testctrl>SQLITE_TESTCTRL_LAST) ){
2507 fprintf(stderr,"Error: invalid testctrl option: %s\n", azArg[1]);
2508 }else{
2509 switch(testctrl){
2510
@@ -2503,11 +2547,11 @@
2547
2548 /* sqlite3_test_control(int, int) */
2549 case SQLITE_TESTCTRL_ASSERT:
2550 case SQLITE_TESTCTRL_ALWAYS:
2551 if( nArg==3 ){
2552 int opt = booleanValue(azArg[2]);
2553 rc = sqlite3_test_control(testctrl, opt);
2554 fprintf(p->out, "%d (0x%08x)\n", rc, rc);
2555 } else {
2556 fprintf(stderr,"Error: testctrl %s takes a single int option\n",
2557 azArg[1]);
@@ -2540,11 +2584,11 @@
2584 }
2585 }else
2586
2587 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 && nArg==2 ){
2588 open_db(p);
2589 sqlite3_busy_timeout(p->db, (int)integerValue(azArg[1]));
2590 }else
2591
2592 if( HAS_TIMER && c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0
2593 && nArg==2
2594 ){
@@ -2590,11 +2634,11 @@
2634
2635 if( c=='w' && strncmp(azArg[0], "width", n)==0 && nArg>1 ){
2636 int j;
2637 assert( nArg<=ArraySize(azArg) );
2638 for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
2639 p->colWidth[j-1] = (int)integerValue(azArg[j]);
2640 }
2641 }else
2642
2643 {
2644 fprintf(stderr, "Error: unknown command or invalid arguments: "
2645
+2642 -2445
--- src/sqlite3.c
+++ src/sqlite3.c
@@ -352,11 +352,11 @@
352352
353353
/*
354354
** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
355355
** 0 means mutexes are permanently disable and the library is never
356356
** threadsafe. 1 means the library is serialized which is the highest
357
-** level of threadsafety. 2 means the libary is multithreaded - multiple
357
+** level of threadsafety. 2 means the library is multithreaded - multiple
358358
** threads can use SQLite as long as no two threads try to use the same
359359
** database connection at the same time.
360360
**
361361
** Older versions of SQLite used an optional THREADSAFE macro.
362362
** We support that for legacy.
@@ -431,24 +431,16 @@
431431
# define SQLITE_MALLOC_SOFT_LIMIT 1024
432432
#endif
433433
434434
/*
435435
** We need to define _XOPEN_SOURCE as follows in order to enable
436
-** recursive mutexes on most Unix systems. But Mac OS X is different.
437
-** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
438
-** so it is omitted there. See ticket #2673.
439
-**
440
-** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
441
-** implemented on some systems. So we avoid defining it at all
442
-** if it is already defined or if it is unneeded because we are
443
-** not doing a threadsafe build. Ticket #2681.
444
-**
445
-** See also ticket #2741.
436
+** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
437
+** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
438
+** it.
446439
*/
447
-#if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) \
448
- && !defined(__APPLE__) && SQLITE_THREADSAFE
449
-# define _XOPEN_SOURCE 500 /* Needed to enable pthread recursive mutexes */
440
+#if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
441
+# define _XOPEN_SOURCE 600
450442
#endif
451443
452444
/*
453445
** The TCL headers are only needed when compiling the TCL bindings.
454446
*/
@@ -678,11 +670,11 @@
678670
** [sqlite3_libversion_number()], [sqlite3_sourceid()],
679671
** [sqlite_version()] and [sqlite_source_id()].
680672
*/
681673
#define SQLITE_VERSION "3.7.17"
682674
#define SQLITE_VERSION_NUMBER 3007017
683
-#define SQLITE_SOURCE_ID "2013-05-15 18:34:17 00231fb0127960d700de3549e34e82f8ec1b5819"
675
+#define SQLITE_SOURCE_ID "2013-06-19 23:48:35 bf5764067ab848e19e5971cbdf892c633495e325"
684676
685677
/*
686678
** CAPI3REF: Run-Time Library Version Numbers
687679
** KEYWORDS: sqlite3_version, sqlite3_sourceid
688680
**
@@ -5087,10 +5079,15 @@
50875079
*/
50885080
SQLITE_API int sqlite3_key(
50895081
sqlite3 *db, /* Database to be rekeyed */
50905082
const void *pKey, int nKey /* The key */
50915083
);
5084
+SQLITE_API int sqlite3_key_v2(
5085
+ sqlite3 *db, /* Database to be rekeyed */
5086
+ const char *zDbName, /* Name of the database */
5087
+ const void *pKey, int nKey /* The key */
5088
+);
50925089
50935090
/*
50945091
** Change the key on an open database. If the current database is not
50955092
** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
50965093
** database is decrypted.
@@ -5100,10 +5097,15 @@
51005097
*/
51015098
SQLITE_API int sqlite3_rekey(
51025099
sqlite3 *db, /* Database to be rekeyed */
51035100
const void *pKey, int nKey /* The new key */
51045101
);
5102
+SQLITE_API int sqlite3_rekey_v2(
5103
+ sqlite3 *db, /* Database to be rekeyed */
5104
+ const char *zDbName, /* Name of the database */
5105
+ const void *pKey, int nKey /* The new key */
5106
+);
51055107
51065108
/*
51075109
** Specify the activation key for a SEE database. Unless
51085110
** activated, none of the SEE routines will work.
51095111
*/
@@ -8151,10 +8153,16 @@
81518153
*/
81528154
#ifndef offsetof
81538155
#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
81548156
#endif
81558157
8158
+/*
8159
+** Macros to compute minimum and maximum of two numbers.
8160
+*/
8161
+#define MIN(A,B) ((A)<(B)?(A):(B))
8162
+#define MAX(A,B) ((A)>(B)?(A):(B))
8163
+
81568164
/*
81578165
** Check to see if this machine uses EBCDIC. (Yes, believe it or
81588166
** not, there are still machines out there that use EBCDIC.)
81598167
*/
81608168
#if 'A' == '\301'
@@ -8476,13 +8484,11 @@
84768484
typedef struct TriggerStep TriggerStep;
84778485
typedef struct UnpackedRecord UnpackedRecord;
84788486
typedef struct VTable VTable;
84798487
typedef struct VtabCtx VtabCtx;
84808488
typedef struct Walker Walker;
8481
-typedef struct WherePlan WherePlan;
84828489
typedef struct WhereInfo WhereInfo;
8483
-typedef struct WhereLevel WhereLevel;
84848490
84858491
/*
84868492
** Defer sourcing vdbe.h and btree.h until after the "u8" and
84878493
** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
84888494
** pointer types (i.e. FuncDef) defined above.
@@ -9915,11 +9921,10 @@
99159921
** databases may be attached.
99169922
*/
99179923
struct Db {
99189924
char *zName; /* Name of this database */
99199925
Btree *pBt; /* The B*Tree structure for this database file */
9920
- u8 inTrans; /* 0: not writable. 1: Transaction. 2: Checkpoint */
99219926
u8 safety_level; /* How aggressive at syncing data to disk */
99229927
Schema *pSchema; /* Pointer to database schema (possibly shared) */
99239928
};
99249929
99259930
/*
@@ -10713,10 +10718,11 @@
1071310718
int tnum; /* DB Page containing root of this index */
1071410719
u16 nColumn; /* Number of columns in table used by this index */
1071510720
u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
1071610721
unsigned autoIndex:2; /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
1071710722
unsigned bUnordered:1; /* Use this index for == or IN queries only */
10723
+ unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */
1071810724
#ifdef SQLITE_ENABLE_STAT3
1071910725
int nSample; /* Number of elements in aSample[] */
1072010726
tRowcnt avgEq; /* Average nEq value for key values not in aSample */
1072110727
IndexSample *aSample; /* Samples of the left-most key */
1072210728
#endif
@@ -11058,10 +11064,15 @@
1105811064
/*
1105911065
** The number of bits in a Bitmask. "BMS" means "BitMask Size".
1106011066
*/
1106111067
#define BMS ((int)(sizeof(Bitmask)*8))
1106211068
11069
+/*
11070
+** A bit in a Bitmask
11071
+*/
11072
+#define MASKBIT(n) (((Bitmask)1)<<(n))
11073
+
1106311074
/*
1106411075
** The following structure describes the FROM clause of a SELECT statement.
1106511076
** Each table or subquery in the FROM clause is a separate element of
1106611077
** the SrcList.a[] array.
1106711078
**
@@ -11078,12 +11089,12 @@
1107811089
**
1107911090
** In the colUsed field, the high-order bit (bit 63) is set if the table
1108011091
** contains more than 63 columns and the 64-th or later column is used.
1108111092
*/
1108211093
struct SrcList {
11083
- i16 nSrc; /* Number of tables or subqueries in the FROM clause */
11084
- i16 nAlloc; /* Number of entries allocated in a[] below */
11094
+ u8 nSrc; /* Number of tables or subqueries in the FROM clause */
11095
+ u8 nAlloc; /* Number of entries allocated in a[] below */
1108511096
struct SrcList_item {
1108611097
Schema *pSchema; /* Schema to which this item is fixed */
1108711098
char *zDatabase; /* Name of database holding this table */
1108811099
char *zName; /* Name of the table */
1108911100
char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
@@ -11117,83 +11128,10 @@
1111711128
#define JT_RIGHT 0x0010 /* Right outer join */
1111811129
#define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
1111911130
#define JT_ERROR 0x0040 /* unknown or unsupported join type */
1112011131
1112111132
11122
-/*
11123
-** A WherePlan object holds information that describes a lookup
11124
-** strategy.
11125
-**
11126
-** This object is intended to be opaque outside of the where.c module.
11127
-** It is included here only so that that compiler will know how big it
11128
-** is. None of the fields in this object should be used outside of
11129
-** the where.c module.
11130
-**
11131
-** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
11132
-** pTerm is only used when wsFlags&WHERE_MULTI_OR is true. And pVtabIdx
11133
-** is only used when wsFlags&WHERE_VIRTUALTABLE is true. It is never the
11134
-** case that more than one of these conditions is true.
11135
-*/
11136
-struct WherePlan {
11137
- u32 wsFlags; /* WHERE_* flags that describe the strategy */
11138
- u16 nEq; /* Number of == constraints */
11139
- u16 nOBSat; /* Number of ORDER BY terms satisfied */
11140
- double nRow; /* Estimated number of rows (for EQP) */
11141
- union {
11142
- Index *pIdx; /* Index when WHERE_INDEXED is true */
11143
- struct WhereTerm *pTerm; /* WHERE clause term for OR-search */
11144
- sqlite3_index_info *pVtabIdx; /* Virtual table index to use */
11145
- } u;
11146
-};
11147
-
11148
-/*
11149
-** For each nested loop in a WHERE clause implementation, the WhereInfo
11150
-** structure contains a single instance of this structure. This structure
11151
-** is intended to be private to the where.c module and should not be
11152
-** access or modified by other modules.
11153
-**
11154
-** The pIdxInfo field is used to help pick the best index on a
11155
-** virtual table. The pIdxInfo pointer contains indexing
11156
-** information for the i-th table in the FROM clause before reordering.
11157
-** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
11158
-** All other information in the i-th WhereLevel object for the i-th table
11159
-** after FROM clause ordering.
11160
-*/
11161
-struct WhereLevel {
11162
- WherePlan plan; /* query plan for this element of the FROM clause */
11163
- int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
11164
- int iTabCur; /* The VDBE cursor used to access the table */
11165
- int iIdxCur; /* The VDBE cursor used to access pIdx */
11166
- int addrBrk; /* Jump here to break out of the loop */
11167
- int addrNxt; /* Jump here to start the next IN combination */
11168
- int addrCont; /* Jump here to continue with the next loop cycle */
11169
- int addrFirst; /* First instruction of interior of the loop */
11170
- u8 iFrom; /* Which entry in the FROM clause */
11171
- u8 op, p5; /* Opcode and P5 of the opcode that ends the loop */
11172
- int p1, p2; /* Operands of the opcode used to ends the loop */
11173
- union { /* Information that depends on plan.wsFlags */
11174
- struct {
11175
- int nIn; /* Number of entries in aInLoop[] */
11176
- struct InLoop {
11177
- int iCur; /* The VDBE cursor used by this IN operator */
11178
- int addrInTop; /* Top of the IN loop */
11179
- u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
11180
- } *aInLoop; /* Information about each nested IN operator */
11181
- } in; /* Used when plan.wsFlags&WHERE_IN_ABLE */
11182
- Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
11183
- } u;
11184
- double rOptCost; /* "Optimal" cost for this level */
11185
-
11186
- /* The following field is really not part of the current level. But
11187
- ** we need a place to cache virtual table index information for each
11188
- ** virtual table in the FROM clause and the WhereLevel structure is
11189
- ** a convenient place since there is one WhereLevel for each FROM clause
11190
- ** element.
11191
- */
11192
- sqlite3_index_info *pIdxInfo; /* Index info for n-th source table */
11193
-};
11194
-
1119511133
/*
1119611134
** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
1119711135
** and the WhereInfo.wctrlFlags member.
1119811136
*/
1119911137
#define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
@@ -11203,37 +11141,15 @@
1120311141
#define WHERE_DUPLICATES_OK 0x0008 /* Ok to return a row more than once */
1120411142
#define WHERE_OMIT_OPEN_CLOSE 0x0010 /* Table cursors are already open */
1120511143
#define WHERE_FORCE_TABLE 0x0020 /* Do not use an index-only search */
1120611144
#define WHERE_ONETABLE_ONLY 0x0040 /* Only code the 1st table in pTabList */
1120711145
#define WHERE_AND_ONLY 0x0080 /* Don't use indices for OR terms */
11208
-
11209
-/*
11210
-** The WHERE clause processing routine has two halves. The
11211
-** first part does the start of the WHERE loop and the second
11212
-** half does the tail of the WHERE loop. An instance of
11213
-** this structure is returned by the first half and passed
11214
-** into the second half to give some continuity.
11215
-*/
11216
-struct WhereInfo {
11217
- Parse *pParse; /* Parsing and code generating context */
11218
- SrcList *pTabList; /* List of tables in the join */
11219
- u16 nOBSat; /* Number of ORDER BY terms satisfied by indices */
11220
- u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
11221
- u8 okOnePass; /* Ok to use one-pass algorithm for UPDATE/DELETE */
11222
- u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
11223
- u8 eDistinct; /* One of the WHERE_DISTINCT_* values below */
11224
- int iTop; /* The very beginning of the WHERE loop */
11225
- int iContinue; /* Jump here to continue with next record */
11226
- int iBreak; /* Jump here to break out of the loop */
11227
- int nLevel; /* Number of nested loop */
11228
- struct WhereClause *pWC; /* Decomposition of the WHERE clause */
11229
- double savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
11230
- double nRowOut; /* Estimated number of output rows */
11231
- WhereLevel a[1]; /* Information about each nest loop in WHERE */
11232
-};
11233
-
11234
-/* Allowed values for WhereInfo.eDistinct and DistinctCtx.eTnctType */
11146
+#define WHERE_GROUPBY 0x0100 /* pOrderBy is really a GROUP BY */
11147
+#define WHERE_DISTINCTBY 0x0200 /* pOrderby is really a DISTINCT clause */
11148
+
11149
+/* Allowed return values from sqlite3WhereIsDistinct()
11150
+*/
1123511151
#define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
1123611152
#define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
1123711153
#define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */
1123811154
#define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */
1123911155
@@ -11303,11 +11219,11 @@
1130311219
ExprList *pEList; /* The fields of the result */
1130411220
u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
1130511221
u16 selFlags; /* Various SF_* values */
1130611222
int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
1130711223
int addrOpenEphm[3]; /* OP_OpenEphem opcodes related to this select */
11308
- double nSelectRow; /* Estimated number of result rows */
11224
+ u64 nSelectRow; /* Estimated number of result rows */
1130911225
SrcList *pSrc; /* The FROM clause */
1131011226
Expr *pWhere; /* The WHERE clause */
1131111227
ExprList *pGroupBy; /* The GROUP BY clause */
1131211228
Expr *pHaving; /* The HAVING clause */
1131311229
ExprList *pOrderBy; /* The ORDER BY clause */
@@ -11487,11 +11403,11 @@
1148711403
AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
1148811404
1148911405
/* Information used while coding trigger programs. */
1149011406
Parse *pToplevel; /* Parse structure for main program (or NULL) */
1149111407
Table *pTriggerTab; /* Table triggers are being coded for */
11492
- double nQueryLoop; /* Estimated number of iterations of a query */
11408
+ u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */
1149311409
u32 oldmask; /* Mask of old.* columns referenced */
1149411410
u32 newmask; /* Mask of new.* columns referenced */
1149511411
u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
1149611412
u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
1149711413
u8 disableTriggers; /* True to disable triggers */
@@ -12057,10 +11973,16 @@
1205711973
#endif
1205811974
SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
1205911975
SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
1206011976
SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
1206111977
SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
11978
+SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo*);
11979
+SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
11980
+SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
11981
+SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
11982
+SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
11983
+SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*);
1206211984
SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
1206311985
SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
1206411986
SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
1206511987
SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
1206611988
SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
@@ -19960,17 +19882,11 @@
1996019882
if( flag_plussign ) prefix = '+';
1996119883
else if( flag_blanksign ) prefix = ' ';
1996219884
else prefix = 0;
1996319885
}
1996419886
if( xtype==etGENERIC && precision>0 ) precision--;
19965
-#if 0
19966
- /* Rounding works like BSD when the constant 0.4999 is used. Wierd! */
19967
- for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
19968
-#else
19969
- /* It makes more sense to use 0.5 */
1997019887
for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
19971
-#endif
1997219888
if( xtype==etFLOAT ) realvalue += rounder;
1997319889
/* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
1997419890
exp = 0;
1997519891
if( sqlite3IsNaN((double)realvalue) ){
1997619892
bufpt = "NaN";
@@ -22931,12 +22847,11 @@
2293122847
*/
2293222848
#if SQLITE_OS_UNIX /* This file is used on unix only */
2293322849
2293422850
/* Use posix_fallocate() if it is available
2293522851
*/
22936
-#if !defined(HAVE_POSIX_FALLOCATE) \
22937
- && (_XOPEN_SOURCE >= 600 || _POSIX_C_SOURCE >= 200112L)
22852
+#if !defined(HAVE_POSIX_FALLOCATE) && defined(__linux__)
2293822853
# define HAVE_POSIX_FALLOCATE 1
2293922854
#endif
2294022855
2294122856
/*
2294222857
** There are various methods for file locking used for concurrency
@@ -26866,19 +26781,23 @@
2686626781
}
2686726782
return SQLITE_OK;
2686826783
}
2686926784
case SQLITE_FCNTL_MMAP_SIZE: {
2687026785
i64 newLimit = *(i64*)pArg;
26786
+ int rc = SQLITE_OK;
2687126787
if( newLimit>sqlite3GlobalConfig.mxMmap ){
2687226788
newLimit = sqlite3GlobalConfig.mxMmap;
2687326789
}
2687426790
*(i64*)pArg = pFile->mmapSizeMax;
26875
- if( newLimit>=0 ){
26791
+ if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
2687626792
pFile->mmapSizeMax = newLimit;
26877
- if( newLimit<pFile->mmapSize ) pFile->mmapSize = newLimit;
26793
+ if( pFile->mmapSize>0 ){
26794
+ unixUnmapfile(pFile);
26795
+ rc = unixMapfile(pFile, -1);
26796
+ }
2687826797
}
26879
- return SQLITE_OK;
26798
+ return rc;
2688026799
}
2688126800
#ifdef SQLITE_DEBUG
2688226801
/* The pager calls this method to signal that it has done
2688326802
** a rollback and that the database is therefore unchanged and
2688426803
** it hence it is OK for the transaction change counter to be
@@ -28244,11 +28163,11 @@
2824428163
OSTRACE(("OPEN %-3d %s\n", h, zFilename));
2824528164
pNew->h = h;
2824628165
pNew->pVfs = pVfs;
2824728166
pNew->zPath = zFilename;
2824828167
pNew->ctrlFlags = (u8)ctrlFlags;
28249
- pNew->mmapSizeMax = sqlite3GlobalConfig.mxMmap;
28168
+ pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
2825028169
if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
2825128170
"psow", SQLITE_POWERSAFE_OVERWRITE) ){
2825228171
pNew->ctrlFlags |= UNIXFILE_PSOW;
2825328172
}
2825428173
if( strcmp(pVfs->zName,"unix-excl")==0 ){
@@ -30799,17 +30718,10 @@
3079930718
** This file mapping API is common to both Win32 and WinRT.
3080030719
*/
3080130720
WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
3080230721
#endif /* SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL) */
3080330722
30804
-/*
30805
-** Macro to find the minimum of two numeric values.
30806
-*/
30807
-#ifndef MIN
30808
-# define MIN(x,y) ((x)<(y)?(x):(y))
30809
-#endif
30810
-
3081130723
/*
3081230724
** Some Microsoft compilers lack this definition.
3081330725
*/
3081430726
#ifndef INVALID_FILE_ATTRIBUTES
3081530727
# define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
@@ -33531,10 +33443,13 @@
3353133443
}
3353233444
}
3353333445
3353433446
/* Forward declaration */
3353533447
static int getTempname(int nBuf, char *zBuf);
33448
+#if SQLITE_MAX_MMAP_SIZE>0
33449
+static int winMapfile(winFile*, sqlite3_int64);
33450
+#endif
3353633451
3353733452
/*
3353833453
** Control and query of the open file handle.
3353933454
*/
3354033455
static int winFileControl(sqlite3_file *id, int op, void *pArg){
@@ -33614,17 +33529,24 @@
3361433529
return SQLITE_OK;
3361533530
}
3361633531
#if SQLITE_MAX_MMAP_SIZE>0
3361733532
case SQLITE_FCNTL_MMAP_SIZE: {
3361833533
i64 newLimit = *(i64*)pArg;
33534
+ int rc = SQLITE_OK;
3361933535
if( newLimit>sqlite3GlobalConfig.mxMmap ){
3362033536
newLimit = sqlite3GlobalConfig.mxMmap;
3362133537
}
3362233538
*(i64*)pArg = pFile->mmapSizeMax;
33623
- if( newLimit>=0 ) pFile->mmapSizeMax = newLimit;
33624
- OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
33625
- return SQLITE_OK;
33539
+ if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
33540
+ pFile->mmapSizeMax = newLimit;
33541
+ if( pFile->mmapSize>0 ){
33542
+ (void)winUnmapfile(pFile);
33543
+ rc = winMapfile(pFile, -1);
33544
+ }
33545
+ }
33546
+ OSTRACE(("FCNTL file=%p, rc=%d\n", pFile->h, rc));
33547
+ return rc;
3362633548
}
3362733549
#endif
3362833550
}
3362933551
OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
3363033552
return SQLITE_NOTFOUND;
@@ -33652,19 +33574,19 @@
3365233574
winFile *p = (winFile*)id;
3365333575
return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
3365433576
((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
3365533577
}
3365633578
33657
-#ifndef SQLITE_OMIT_WAL
33658
-
3365933579
/*
3366033580
** Windows will only let you create file view mappings
3366133581
** on allocation size granularity boundaries.
3366233582
** During sqlite3_os_init() we do a GetSystemInfo()
3366333583
** to get the granularity size.
3366433584
*/
3366533585
SYSTEM_INFO winSysInfo;
33586
+
33587
+#ifndef SQLITE_OMIT_WAL
3366633588
3366733589
/*
3366833590
** Helper functions to obtain and relinquish the global mutex. The
3366933591
** global mutex is used to protect the winLockInfo objects used by
3367033592
** this file, all of which may be shared by multiple threads.
@@ -34961,11 +34883,11 @@
3496134883
#if SQLITE_MAX_MMAP_SIZE>0
3496234884
pFile->hMap = NULL;
3496334885
pFile->pMapRegion = 0;
3496434886
pFile->mmapSize = 0;
3496534887
pFile->mmapSizeActual = 0;
34966
- pFile->mmapSizeMax = sqlite3GlobalConfig.mxMmap;
34888
+ pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
3496734889
#endif
3496834890
3496934891
OpenCounter(+1);
3497034892
return rc;
3497134893
}
@@ -37220,11 +37142,11 @@
3722037142
PCache1 *pCache; /* The newly created page cache */
3722137143
PGroup *pGroup; /* The group the new page cache will belong to */
3722237144
int sz; /* Bytes of memory required to allocate the new cache */
3722337145
3722437146
/*
37225
- ** The seperateCache variable is true if each PCache has its own private
37147
+ ** The separateCache variable is true if each PCache has its own private
3722637148
** PGroup. In other words, separateCache is true for mode (1) where no
3722737149
** mutexing is required.
3722837150
**
3722937151
** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
3723037152
**
@@ -42544,11 +42466,12 @@
4254442466
/* Before the first write, give the VFS a hint of what the final
4254542467
** file size will be.
4254642468
*/
4254742469
assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
4254842470
if( rc==SQLITE_OK
42549
- && (pList->pDirty ? pPager->dbSize : pList->pgno+1)>pPager->dbHintSize
42471
+ && pPager->dbHintSize<pPager->dbSize
42472
+ && (pList->pDirty || pList->pgno>pPager->dbHintSize)
4255042473
){
4255142474
sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
4255242475
sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
4255342476
pPager->dbHintSize = pPager->dbSize;
4255442477
}
@@ -43509,11 +43432,11 @@
4350943432
** requested page is not already stored in the cache, then no
4351043433
** actual disk read occurs. In this case the memory image of the
4351143434
** page is initialized to all zeros.
4351243435
**
4351343436
** If noContent is true, it means that we do not care about the contents
43514
-** of the page. This occurs in two seperate scenarios:
43437
+** of the page. This occurs in two scenarios:
4351543438
**
4351643439
** a) When reading a free-list leaf page from the database, and
4351743440
**
4351843441
** b) When a savepoint is being rolled back and we need to load
4351943442
** a new page into the cache to be filled with the data read
@@ -44919,11 +44842,31 @@
4491944842
pagerReportSize(pPager);
4492044843
}
4492144844
SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
4492244845
return pPager->pCodec;
4492344846
}
44924
-#endif
44847
+
44848
+/*
44849
+** This function is called by the wal module when writing page content
44850
+** into the log file.
44851
+**
44852
+** This function returns a pointer to a buffer containing the encrypted
44853
+** page content. If a malloc fails, this function may return NULL.
44854
+*/
44855
+SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
44856
+ void *aData = 0;
44857
+ CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
44858
+ return aData;
44859
+}
44860
+
44861
+/*
44862
+** Return the current pager state
44863
+*/
44864
+SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
44865
+ return pPager->eState;
44866
+}
44867
+#endif /* SQLITE_HAS_CODEC */
4492544868
4492644869
#ifndef SQLITE_OMIT_AUTOVACUUM
4492744870
/*
4492844871
** Move the page pPg to location pgno in the file.
4492944872
**
@@ -45474,25 +45417,10 @@
4547445417
assert( pPager->eState==PAGER_READER );
4547545418
return sqlite3WalFramesize(pPager->pWal);
4547645419
}
4547745420
#endif
4547845421
45479
-#ifdef SQLITE_HAS_CODEC
45480
-/*
45481
-** This function is called by the wal module when writing page content
45482
-** into the log file.
45483
-**
45484
-** This function returns a pointer to a buffer containing the encrypted
45485
-** page content. If a malloc fails, this function may return NULL.
45486
-*/
45487
-SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
45488
- void *aData = 0;
45489
- CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
45490
- return aData;
45491
-}
45492
-#endif /* SQLITE_HAS_CODEC */
45493
-
4549445422
#endif /* SQLITE_OMIT_DISKIO */
4549545423
4549645424
/************** End of pager.c ***********************************************/
4549745425
/************** Begin file wal.c *********************************************/
4549845426
/*
@@ -50759,11 +50687,11 @@
5075950687
if( rc ) return rc;
5076050688
top = get2byteNotZero(&data[hdr+5]);
5076150689
}else if( gap+2<=top ){
5076250690
/* Search the freelist looking for a free slot big enough to satisfy
5076350691
** the request. The allocation is made from the first free slot in
50764
- ** the list that is large enough to accomadate it.
50692
+ ** the list that is large enough to accommodate it.
5076550693
*/
5076650694
int pc, addr;
5076750695
for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
5076850696
int size; /* Size of the free slot */
5076950697
if( pc>usableSize-4 || pc<addr+4 ){
@@ -52702,11 +52630,11 @@
5270252630
return rc;
5270352631
}
5270452632
5270552633
/*
5270652634
** This routine is called prior to sqlite3PagerCommit when a transaction
52707
-** is commited for an auto-vacuum database.
52635
+** is committed for an auto-vacuum database.
5270852636
**
5270952637
** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
5271052638
** the database file should be truncated to during the commit process.
5271152639
** i.e. the database has been reorganized so that only the first *pnTrunc
5271252640
** pages are in use.
@@ -58045,16 +57973,10 @@
5804557973
*************************************************************************
5804657974
** This file contains the implementation of the sqlite3_backup_XXX()
5804757975
** API functions and the related features.
5804857976
*/
5804957977
58050
-/* Macro to find the minimum of two numeric values.
58051
-*/
58052
-#ifndef MIN
58053
-# define MIN(x,y) ((x)<(y)?(x):(y))
58054
-#endif
58055
-
5805657978
/*
5805757979
** Structure allocated for each backup operation.
5805857980
*/
5805957981
struct sqlite3_backup {
5806057982
sqlite3* pDestDb; /* Destination database handle */
@@ -61942,11 +61864,11 @@
6194261864
/*
6194361865
** If the Vdbe passed as the first argument opened a statement-transaction,
6194461866
** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
6194561867
** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
6194661868
** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
61947
-** statement transaction is commtted.
61869
+** statement transaction is committed.
6194861870
**
6194961871
** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
6195061872
** Otherwise SQLITE_OK.
6195161873
*/
6195261874
SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
@@ -64011,17 +63933,10 @@
6401163933
int iType = sqlite3_value_type( columnMem(pStmt,i) );
6401263934
columnMallocFailure(pStmt);
6401363935
return iType;
6401463936
}
6401563937
64016
-/* The following function is experimental and subject to change or
64017
-** removal */
64018
-/*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
64019
-** return sqlite3_value_numeric_type( columnMem(pStmt,i) );
64020
-**}
64021
-*/
64022
-
6402363938
/*
6402463939
** Convert the N-th element of pStmt->pColName[] into a string using
6402563940
** xFunc() then return that string. If N is out of range, return 0.
6402663941
**
6402763942
** There are up to 5 names for each column. useType determines which
@@ -64643,18 +64558,18 @@
6464364558
pVar = &utf8;
6464464559
}
6464564560
#endif
6464664561
nOut = pVar->n;
6464764562
#ifdef SQLITE_TRACE_SIZE_LIMIT
64648
- if( n>SQLITE_TRACE_SIZE_LIMIT ){
64563
+ if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
6464964564
nOut = SQLITE_TRACE_SIZE_LIMIT;
64650
- while( nOut<pVar->n && (pVar->z[n]&0xc0)==0x80 ){ n++; }
64565
+ while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
6465164566
}
6465264567
#endif
6465364568
sqlite3XPrintf(&out, "'%.*q'", nOut, pVar->z);
6465464569
#ifdef SQLITE_TRACE_SIZE_LIMIT
64655
- if( nOut<pVar->n ) sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-n);
64570
+ if( nOut<pVar->n ) sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
6465664571
#endif
6465764572
#ifndef SQLITE_OMIT_UTF16
6465864573
if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
6465964574
#endif
6466064575
}else if( pVar->flags & MEM_Zero ){
@@ -64670,11 +64585,11 @@
6467064585
for(i=0; i<nOut; i++){
6467164586
sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
6467264587
}
6467364588
sqlite3StrAccumAppend(&out, "'", 1);
6467464589
#ifdef SQLITE_TRACE_SIZE_LIMIT
64675
- if( nOut<pVar->n ) sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-n);
64590
+ if( nOut<pVar->n ) sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
6467664591
#endif
6467764592
}
6467864593
}
6467964594
}
6468064595
return sqlite3StrAccumFinish(&out);
@@ -68269,12 +68184,12 @@
6826968184
** If P2 is non-zero, then a write-transaction is started. A RESERVED lock is
6827068185
** obtained on the database file when a write-transaction is started. No
6827168186
** other process can start another write transaction while this transaction is
6827268187
** underway. Starting a write transaction also creates a rollback journal. A
6827368188
** write transaction must be started before any changes can be made to the
68274
-** database. If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
68275
-** on the file.
68189
+** database. If P2 is greater than or equal to 2 then an EXCLUSIVE lock is
68190
+** also obtained on the file.
6827668191
**
6827768192
** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
6827868193
** true (this flag is set if the Vdbe may modify more than one row and may
6827968194
** throw an ABORT exception), a statement transaction may also be opened.
6828068195
** More specifically, a statement transaction is opened iff the database
@@ -72224,11 +72139,11 @@
7222472139
**
7222572140
** For the purposes of this comparison, EOF is considered greater than any
7222672141
** other key value. If the keys are equal (only possible with two EOF
7222772142
** values), it doesn't matter which index is stored.
7222872143
**
72229
-** The (N/4) elements of aTree[] that preceed the final (N/2) described
72144
+** The (N/4) elements of aTree[] that precede the final (N/2) described
7223072145
** above contains the index of the smallest of each block of 4 iterators.
7223172146
** And so on. So that aTree[1] contains the index of the iterator that
7223272147
** currently points to the smallest key value. aTree[0] is unused.
7223372148
**
7223472149
** Example:
@@ -73499,16 +73414,10 @@
7349973414
** a power-of-two allocation. This mimimizes wasted space in power-of-two
7350073415
** memory allocators.
7350173416
*/
7350273417
#define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
7350373418
73504
-/* Macro to find the minimum of two numeric values.
73505
-*/
73506
-#ifndef MIN
73507
-# define MIN(x,y) ((x)<(y)?(x):(y))
73508
-#endif
73509
-
7351073419
/*
7351173420
** The rollback journal is composed of a linked list of these structures.
7351273421
*/
7351373422
struct FileChunk {
7351473423
FileChunk *pNext; /* Next chunk in the journal */
@@ -75045,12 +74954,12 @@
7504574954
**
7504674955
** Minor point: If this is the case, then the expression will be
7504774956
** re-evaluated for each reference to it.
7504874957
*/
7504974958
sNC.pEList = p->pEList;
75050
- if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
7505174959
sNC.ncFlags |= NC_AsMaybe;
74960
+ if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
7505274961
if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
7505374962
sNC.ncFlags &= ~NC_AsMaybe;
7505474963
7505574964
/* The ORDER BY and GROUP BY clauses may not refer to terms in
7505674965
** outer queries
@@ -76817,19 +76726,19 @@
7681776726
7681876727
if( eType==0 ){
7681976728
/* Could not found an existing table or index to use as the RHS b-tree.
7682076729
** We will have to generate an ephemeral table to do the job.
7682176730
*/
76822
- double savedNQueryLoop = pParse->nQueryLoop;
76731
+ u32 savedNQueryLoop = pParse->nQueryLoop;
7682376732
int rMayHaveNull = 0;
7682476733
eType = IN_INDEX_EPH;
7682576734
if( prNotFound ){
7682676735
*prNotFound = rMayHaveNull = ++pParse->nMem;
7682776736
sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
7682876737
}else{
76829
- testcase( pParse->nQueryLoop>(double)1 );
76830
- pParse->nQueryLoop = (double)1;
76738
+ testcase( pParse->nQueryLoop>0 );
76739
+ pParse->nQueryLoop = 0;
7683176740
if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
7683276741
eType = IN_INDEX_ROWID;
7683376742
}
7683476743
}
7683576744
sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
@@ -76867,11 +76776,11 @@
7686776776
** the register given by rMayHaveNull to NULL. Calling routines will take
7686876777
** care of changing this register value to non-NULL if the RHS is NULL-free.
7686976778
**
7687076779
** If rMayHaveNull is zero, that means that the subquery is being used
7687176780
** for membership testing only. There is no need to initialize any
76872
-** registers to indicate the presense or absence of NULLs on the RHS.
76781
+** registers to indicate the presence or absence of NULLs on the RHS.
7687376782
**
7687476783
** For a SELECT or EXISTS operator, return the register that holds the
7687576784
** result. For IN operators or if an error occurs, the return value is 0.
7687676785
*/
7687776786
#ifndef SQLITE_OMIT_SUBQUERY
@@ -80267,11 +80176,11 @@
8026780176
**
8026880177
** Additional tables might be added in future releases of SQLite.
8026980178
** The sqlite_stat2 table is not created or used unless the SQLite version
8027080179
** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
8027180180
** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated.
80272
-** The sqlite_stat2 table is superceded by sqlite_stat3, which is only
80181
+** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
8027380182
** created and used by SQLite versions 3.7.9 and later and with
8027480183
** SQLITE_ENABLE_STAT3 defined. The fucntionality of sqlite_stat3
8027580184
** is a superset of sqlite_stat2.
8027680185
**
8027780186
** Format of sqlite_stat1:
@@ -83455,10 +83364,11 @@
8345583364
zColl = sqlite3NameFromToken(db, pToken);
8345683365
if( !zColl ) return;
8345783366
8345883367
if( sqlite3LocateCollSeq(pParse, zColl) ){
8345983368
Index *pIdx;
83369
+ sqlite3DbFree(db, p->aCol[i].zColl);
8346083370
p->aCol[i].zColl = zColl;
8346183371
8346283372
/* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
8346383373
** then an index may have been created on this column before the
8346483374
** collation type was added. Correct this if it is the case.
@@ -84874,10 +84784,11 @@
8487484784
zExtra = (char *)(&pIndex->zName[nName+1]);
8487584785
memcpy(pIndex->zName, zName, nName+1);
8487684786
pIndex->pTable = pTab;
8487784787
pIndex->nColumn = pList->nExpr;
8487884788
pIndex->onError = (u8)onError;
84789
+ pIndex->uniqNotNull = onError==OE_Abort;
8487984790
pIndex->autoIndex = (u8)(pName==0);
8488084791
pIndex->pSchema = db->aDb[iDb].pSchema;
8488184792
assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
8488284793
8488384794
/* Check to see if we should honor DESC requests on index columns
@@ -84932,10 +84843,11 @@
8493284843
goto exit_create_index;
8493384844
}
8493484845
pIndex->azColl[i] = zColl;
8493584846
requestedSortOrder = pListItem->sortOrder & sortOrderMask;
8493684847
pIndex->aSortOrder[i] = (u8)requestedSortOrder;
84848
+ if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0;
8493784849
}
8493884850
sqlite3DefaultRowEst(pIndex);
8493984851
8494084852
if( pTab==pParse->pNewTable ){
8494184853
/* This routine has been called to create an automatic index as a
@@ -85363,19 +85275,19 @@
8536385275
assert( db->mallocFailed );
8536485276
return pSrc;
8536585277
}
8536685278
pSrc = pNew;
8536785279
nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
85368
- pSrc->nAlloc = (u16)nGot;
85280
+ pSrc->nAlloc = (u8)nGot;
8536985281
}
8537085282
8537185283
/* Move existing slots that come after the newly inserted slots
8537285284
** out of the way */
8537385285
for(i=pSrc->nSrc-1; i>=iStart; i--){
8537485286
pSrc->a[i+nExtra] = pSrc->a[i];
8537585287
}
85376
- pSrc->nSrc += (i16)nExtra;
85288
+ pSrc->nSrc += (i8)nExtra;
8537785289
8537885290
/* Zero the newly allocated slots */
8537985291
memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
8538085292
for(i=iStart; i<iStart+nExtra; i++){
8538185293
pSrc->a[i].iCursor = -1;
@@ -87378,11 +87290,11 @@
8737887290
** of x. If x is text, then we actually count UTF-8 characters.
8737987291
** If x is a blob, then we count bytes.
8738087292
**
8738187293
** If p1 is negative, then we begin abs(p1) from the end of x[].
8738287294
**
87383
-** If p2 is negative, return the p2 characters preceeding p1.
87295
+** If p2 is negative, return the p2 characters preceding p1.
8738487296
*/
8738587297
static void substrFunc(
8738687298
sqlite3_context *context,
8738787299
int argc,
8738887300
sqlite3_value **argv
@@ -88037,14 +87949,10 @@
8803787949
'0', '1', '2', '3', '4', '5', '6', '7',
8803887950
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
8803987951
};
8804087952
8804187953
/*
88042
-** EXPERIMENTAL - This is not an official function. The interface may
88043
-** change. This function may disappear. Do not write code that depends
88044
-** on this function.
88045
-**
8804687954
** Implementation of the QUOTE() function. This function takes a single
8804787955
** argument. If the argument is numeric, the return value is the same as
8804887956
** the argument. If the argument is NULL, the return value is the string
8804987957
** "NULL". Otherwise, the argument is enclosed in single quotes with
8805087958
** single-quote escapes.
@@ -88229,11 +88137,11 @@
8822988137
}
8823088138
8823188139
/*
8823288140
** The replace() function. Three arguments are all strings: call
8823388141
** them A, B, and C. The result is also a string which is derived
88234
-** from A by replacing every occurance of B with C. The match
88142
+** from A by replacing every occurrence of B with C. The match
8823588143
** must be exact. Collating sequences are not used.
8823688144
*/
8823788145
static void replaceFunc(
8823888146
sqlite3_context *context,
8823988147
int argc,
@@ -94147,15 +94055,19 @@
9414794055
sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
9414894056
}
9414994057
}
9415094058
}
9415194059
sz = -1;
94152
- if( sqlite3_file_control(db,zDb,SQLITE_FCNTL_MMAP_SIZE,&sz)==SQLITE_OK ){
94060
+ rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
9415394061
#if SQLITE_MAX_MMAP_SIZE==0
94154
- sz = 0;
94062
+ sz = 0;
9415594063
#endif
94064
+ if( rc==SQLITE_OK ){
9415694065
returnSingleInt(pParse, "mmap_size", sz);
94066
+ }else if( rc!=SQLITE_NOTFOUND ){
94067
+ pParse->nErr++;
94068
+ pParse->rc = rc;
9415794069
}
9415894070
}else
9415994071
9416094072
/*
9416194073
** PRAGMA temp_store
@@ -94682,11 +94594,11 @@
9468294594
#ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
9468394595
# define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
9468494596
#endif
9468594597
9468694598
#ifndef SQLITE_OMIT_INTEGRITY_CHECK
94687
- /* Pragma "quick_check" is an experimental reduced version of
94599
+ /* Pragma "quick_check" is reduced version of
9468894600
** integrity_check designed to detect most database corruption
9468994601
** without most of the overhead of a full integrity-check.
9469094602
*/
9469194603
if( sqlite3StrICmp(zLeft, "integrity_check")==0
9469294604
|| sqlite3StrICmp(zLeft, "quick_check")==0
@@ -95140,14 +95052,14 @@
9514095052
}else
9514195053
#endif
9514295054
9514395055
#ifdef SQLITE_HAS_CODEC
9514495056
if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
95145
- sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
95057
+ sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
9514695058
}else
9514795059
if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
95148
- sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
95060
+ sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
9514995061
}else
9515095062
if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
9515195063
sqlite3StrICmp(zLeft, "hexrekey")==0) ){
9515295064
int i, h1, h2;
9515395065
char zKey[40];
@@ -95155,13 +95067,13 @@
9515595067
h1 += 9*(1&(h1>>6));
9515695068
h2 += 9*(1&(h2>>6));
9515795069
zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
9515895070
}
9515995071
if( (zLeft[3] & 0xf)==0xb ){
95160
- sqlite3_key(db, zKey, i/2);
95072
+ sqlite3_key_v2(db, zDb, zKey, i/2);
9516195073
}else{
95162
- sqlite3_rekey(db, zKey, i/2);
95074
+ sqlite3_rekey_v2(db, zDb, zKey, i/2);
9516395075
}
9516495076
}else
9516595077
#endif
9516695078
#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
9516795079
if( sqlite3StrICmp(zLeft, "activate_extensions")==0 && zRight ){
@@ -95792,11 +95704,11 @@
9579295704
}
9579395705
9579495706
sqlite3VtabUnlockList(db);
9579595707
9579695708
pParse->db = db;
95797
- pParse->nQueryLoop = (double)1;
95709
+ pParse->nQueryLoop = 0; /* Logarithmic, so 0 really means 1 */
9579895710
if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
9579995711
char *zSqlCopy;
9580095712
int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
9580195713
testcase( nBytes==mxLen );
9580295714
testcase( nBytes==mxLen+1 );
@@ -95814,11 +95726,11 @@
9581495726
pParse->zTail = &zSql[nBytes];
9581595727
}
9581695728
}else{
9581795729
sqlite3RunParser(pParse, zSql, &zErrMsg);
9581895730
}
95819
- assert( 1==(int)pParse->nQueryLoop );
95731
+ assert( 0==pParse->nQueryLoop );
9582095732
9582195733
if( db->mallocFailed ){
9582295734
pParse->rc = SQLITE_NOMEM;
9582395735
}
9582495736
if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
@@ -96178,11 +96090,11 @@
9617896090
sqlite3DbFree(db, p);
9617996091
}
9618096092
}
9618196093
9618296094
/*
96183
-** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
96095
+** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
9618496096
** type of join. Return an integer constant that expresses that type
9618596097
** in terms of the following bit values:
9618696098
**
9618796099
** JT_INNER
9618896100
** JT_CROSS
@@ -97592,11 +97504,11 @@
9759297504
int addr1, n;
9759397505
if( p->iLimit ) return;
9759497506
9759597507
/*
9759697508
** "LIMIT -1" always shows all rows. There is some
97597
- ** contraversy about what the correct behavior should be.
97509
+ ** controversy about what the correct behavior should be.
9759897510
** The current implementation interprets "LIMIT 0" to mean
9759997511
** no rows.
9760097512
*/
9760197513
sqlite3ExprCacheClear(pParse);
9760297514
assert( p->pOffset==0 || p->pLimit!=0 );
@@ -97607,12 +97519,12 @@
9760797519
if( sqlite3ExprIsInteger(p->pLimit, &n) ){
9760897520
sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
9760997521
VdbeComment((v, "LIMIT counter"));
9761097522
if( n==0 ){
9761197523
sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
97612
- }else{
97613
- if( p->nSelectRow > (double)n ) p->nSelectRow = (double)n;
97524
+ }else if( n>=0 && p->nSelectRow>(u64)n ){
97525
+ p->nSelectRow = n;
9761497526
}
9761597527
}else{
9761697528
sqlite3ExprCode(pParse, p->pLimit, iLimit);
9761797529
sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
9761897530
VdbeComment((v, "LIMIT counter"));
@@ -97802,13 +97714,13 @@
9780297714
pDelete = p->pPrior;
9780397715
p->pPrior = pPrior;
9780497716
p->nSelectRow += pPrior->nSelectRow;
9780597717
if( pPrior->pLimit
9780697718
&& sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
97807
- && p->nSelectRow > (double)nLimit
97719
+ && nLimit>0 && p->nSelectRow > (u64)nLimit
9780897720
){
97809
- p->nSelectRow = (double)nLimit;
97721
+ p->nSelectRow = nLimit;
9781097722
}
9781197723
if( addr ){
9781297724
sqlite3VdbeJumpHere(v, addr);
9781397725
}
9781497726
break;
@@ -99953,15 +99865,14 @@
9995399865
Parse *pParse, /* Parse context */
9995499866
Table *pTab, /* Table being queried */
9995599867
Index *pIdx /* Index used to optimize scan, or NULL */
9995699868
){
9995799869
if( pParse->explain==2 ){
99958
- char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s %s%s(~%d rows)",
99870
+ char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
9995999871
pTab->zName,
99960
- pIdx ? "USING COVERING INDEX " : "",
99961
- pIdx ? pIdx->zName : "",
99962
- pTab->nRowEst
99872
+ pIdx ? " USING COVERING INDEX " : "",
99873
+ pIdx ? pIdx->zName : ""
9996399874
);
9996499875
sqlite3VdbeAddOp4(
9996599876
pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
9996699877
);
9996799878
}
@@ -100115,11 +100026,11 @@
100115100026
}
100116100027
continue;
100117100028
}
100118100029
100119100030
/* Increment Parse.nHeight by the height of the largest expression
100120
- ** tree refered to by this, the parent select. The child select
100031
+ ** tree referred to by this, the parent select. The child select
100121100032
** may contain expression trees of at most
100122100033
** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
100123100034
** more conservative than necessary, but much easier than enforcing
100124100035
** an exact limit.
100125100036
*/
@@ -100308,11 +100219,11 @@
100308100219
}
100309100220
100310100221
/* Set the limiter.
100311100222
*/
100312100223
iEnd = sqlite3VdbeMakeLabel(v);
100313
- p->nSelectRow = (double)LARGEST_INT64;
100224
+ p->nSelectRow = LARGEST_INT64;
100314100225
computeLimitRegisters(pParse, p, iEnd);
100315100226
if( p->iLimit==0 && addrSortIndex>=0 ){
100316100227
sqlite3VdbeGetOp(v, addrSortIndex)->opcode = OP_SorterOpen;
100317100228
p->selFlags |= SF_UseSorter;
100318100229
}
@@ -100336,13 +100247,17 @@
100336100247
ExprList *pDist = (sDistinct.isTnct ? p->pEList : 0);
100337100248
100338100249
/* Begin the database scan. */
100339100250
pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pOrderBy, pDist, 0,0);
100340100251
if( pWInfo==0 ) goto select_end;
100341
- if( pWInfo->nRowOut < p->nSelectRow ) p->nSelectRow = pWInfo->nRowOut;
100342
- if( pWInfo->eDistinct ) sDistinct.eTnctType = pWInfo->eDistinct;
100343
- if( pOrderBy && pWInfo->nOBSat==pOrderBy->nExpr ) pOrderBy = 0;
100252
+ if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
100253
+ p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
100254
+ }
100255
+ if( sqlite3WhereIsDistinct(pWInfo) ){
100256
+ sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
100257
+ }
100258
+ if( pOrderBy && sqlite3WhereIsOrdered(pWInfo) ) pOrderBy = 0;
100344100259
100345100260
/* If sorting index that was created by a prior OP_OpenEphemeral
100346100261
** instruction ended up not being needed, then change the OP_OpenEphemeral
100347100262
** into an OP_Noop.
100348100263
*/
@@ -100351,11 +100266,12 @@
100351100266
p->addrOpenEphm[2] = -1;
100352100267
}
100353100268
100354100269
/* Use the standard inner loop. */
100355100270
selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, &sDistinct, pDest,
100356
- pWInfo->iContinue, pWInfo->iBreak);
100271
+ sqlite3WhereContinueLabel(pWInfo),
100272
+ sqlite3WhereBreakLabel(pWInfo));
100357100273
100358100274
/* End the database scan loop.
100359100275
*/
100360100276
sqlite3WhereEnd(pWInfo);
100361100277
}else{
@@ -100384,13 +100300,13 @@
100384100300
pItem->iAlias = 0;
100385100301
}
100386100302
for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
100387100303
pItem->iAlias = 0;
100388100304
}
100389
- if( p->nSelectRow>(double)100 ) p->nSelectRow = (double)100;
100305
+ if( p->nSelectRow>100 ) p->nSelectRow = 100;
100390100306
}else{
100391
- p->nSelectRow = (double)1;
100307
+ p->nSelectRow = 1;
100392100308
}
100393100309
100394100310
100395100311
/* Create a label to jump to when we want to abort the query */
100396100312
addrEnd = sqlite3VdbeMakeLabel(v);
@@ -100466,13 +100382,14 @@
100466100382
** This might involve two separate loops with an OP_Sort in between, or
100467100383
** it might be a single loop that uses an index to extract information
100468100384
** in the right order to begin with.
100469100385
*/
100470100386
sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
100471
- pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0, 0, 0);
100387
+ pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
100388
+ WHERE_GROUPBY, 0);
100472100389
if( pWInfo==0 ) goto select_end;
100473
- if( pWInfo->nOBSat==pGroupBy->nExpr ){
100390
+ if( sqlite3WhereIsOrdered(pWInfo) ){
100474100391
/* The optimizer is able to deliver rows in group by order so
100475100392
** we do not have to sort. The OP_OpenEphemeral table will be
100476100393
** cancelled later because we still need to use the pKeyInfo
100477100394
*/
100478100395
groupBySort = 0;
@@ -100749,12 +100666,12 @@
100749100666
sqlite3ExprListDelete(db, pDel);
100750100667
goto select_end;
100751100668
}
100752100669
updateAccumulator(pParse, &sAggInfo);
100753100670
assert( pMinMax==0 || pMinMax->nExpr==1 );
100754
- if( pWInfo->nOBSat>0 ){
100755
- sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
100671
+ if( sqlite3WhereIsOrdered(pWInfo) ){
100672
+ sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3WhereBreakLabel(pWInfo));
100756100673
VdbeComment((v, "%s() by index",
100757100674
(flag==WHERE_ORDERBY_MIN?"min":"max")));
100758100675
}
100759100676
sqlite3WhereEnd(pWInfo);
100760100677
finalizeAggFunctions(pParse, &sAggInfo);
@@ -102109,11 +102026,11 @@
102109102026
}
102110102027
102111102028
/*
102112102029
** This is called to code the required FOR EACH ROW triggers for an operation
102113102030
** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
102114
-** is given by the op paramater. The tr_tm parameter determines whether the
102031
+** is given by the op parameter. The tr_tm parameter determines whether the
102115102032
** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
102116102033
** parameter pChanges is passed the list of columns being modified.
102117102034
**
102118102035
** If there are no triggers that fire at the specified time for the specified
102119102036
** operation on pTab, this function is a no-op.
@@ -102560,11 +102477,11 @@
102560102477
sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
102561102478
pWInfo = sqlite3WhereBegin(
102562102479
pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, 0
102563102480
);
102564102481
if( pWInfo==0 ) goto update_cleanup;
102565
- okOnePass = pWInfo->okOnePass;
102482
+ okOnePass = sqlite3WhereOkOnePass(pWInfo);
102566102483
102567102484
/* Remember the rowid of every item to be updated.
102568102485
*/
102569102486
sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
102570102487
if( !okOnePass ){
@@ -104397,22 +104314,165 @@
104397104314
#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
104398104315
/***/ int sqlite3WhereTrace = 0;
104399104316
#endif
104400104317
#if defined(SQLITE_DEBUG) \
104401104318
&& (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
104402
-# define WHERETRACE(X) if(sqlite3WhereTrace) sqlite3DebugPrintf X
104319
+# define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
104320
+# define WHERETRACE_ENABLED 1
104403104321
#else
104404
-# define WHERETRACE(X)
104322
+# define WHERETRACE(K,X)
104405104323
#endif
104406104324
104407104325
/* Forward reference
104408104326
*/
104409104327
typedef struct WhereClause WhereClause;
104410104328
typedef struct WhereMaskSet WhereMaskSet;
104411104329
typedef struct WhereOrInfo WhereOrInfo;
104412104330
typedef struct WhereAndInfo WhereAndInfo;
104413
-typedef struct WhereCost WhereCost;
104331
+typedef struct WhereLevel WhereLevel;
104332
+typedef struct WhereLoop WhereLoop;
104333
+typedef struct WherePath WherePath;
104334
+typedef struct WhereTerm WhereTerm;
104335
+typedef struct WhereLoopBuilder WhereLoopBuilder;
104336
+typedef struct WhereScan WhereScan;
104337
+
104338
+/*
104339
+** Cost X is tracked as 10*log2(X) stored in a 16-bit integer. The
104340
+** maximum cost for ordinary tables is 64*(2**63) which becomes 6900.
104341
+** (Virtual tables can return a larger cost, but let's assume they do not.)
104342
+** So all costs can be stored in a 16-bit unsigned integer without risk
104343
+** of overflow.
104344
+**
104345
+** Costs are estimates, so don't go to the computational trouble to compute
104346
+** 10*log2(X) exactly. Instead, a close estimate is used. Any value of
104347
+** X<=1 is stored as 0. X=2 is 10. X=3 is 16. X=1000 is 99. etc.
104348
+**
104349
+** The tool/wherecosttest.c source file implements a command-line program
104350
+** that will convert between WhereCost to integers and do addition and
104351
+** multiplication on WhereCost values. That command-line program is a
104352
+** useful utility to have around when working with this module.
104353
+*/
104354
+typedef unsigned short int WhereCost;
104355
+
104356
+/*
104357
+** This object contains information needed to implement a single nested
104358
+** loop in WHERE clause.
104359
+**
104360
+** Contrast this object with WhereLoop. This object describes the
104361
+** implementation of the loop. WhereLoop describes the algorithm.
104362
+** This object contains a pointer to the WhereLoop algorithm as one of
104363
+** its elements.
104364
+**
104365
+** The WhereInfo object contains a single instance of this object for
104366
+** each term in the FROM clause (which is to say, for each of the
104367
+** nested loops as implemented). The order of WhereLevel objects determines
104368
+** the loop nested order, with WhereInfo.a[0] being the outer loop and
104369
+** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
104370
+*/
104371
+struct WhereLevel {
104372
+ int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
104373
+ int iTabCur; /* The VDBE cursor used to access the table */
104374
+ int iIdxCur; /* The VDBE cursor used to access pIdx */
104375
+ int addrBrk; /* Jump here to break out of the loop */
104376
+ int addrNxt; /* Jump here to start the next IN combination */
104377
+ int addrCont; /* Jump here to continue with the next loop cycle */
104378
+ int addrFirst; /* First instruction of interior of the loop */
104379
+ u8 iFrom; /* Which entry in the FROM clause */
104380
+ u8 op, p5; /* Opcode and P5 of the opcode that ends the loop */
104381
+ int p1, p2; /* Operands of the opcode used to ends the loop */
104382
+ union { /* Information that depends on pWLoop->wsFlags */
104383
+ struct {
104384
+ int nIn; /* Number of entries in aInLoop[] */
104385
+ struct InLoop {
104386
+ int iCur; /* The VDBE cursor used by this IN operator */
104387
+ int addrInTop; /* Top of the IN loop */
104388
+ u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
104389
+ } *aInLoop; /* Information about each nested IN operator */
104390
+ } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
104391
+ Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
104392
+ } u;
104393
+ struct WhereLoop *pWLoop; /* The selected WhereLoop object */
104394
+};
104395
+
104396
+/*
104397
+** Each instance of this object represents an algorithm for evaluating one
104398
+** term of a join. Every term of the FROM clause will have at least
104399
+** one corresponding WhereLoop object (unless INDEXED BY constraints
104400
+** prevent a query solution - which is an error) and many terms of the
104401
+** FROM clause will have multiple WhereLoop objects, each describing a
104402
+** potential way of implementing that FROM-clause term, together with
104403
+** dependencies and cost estimates for using the chosen algorithm.
104404
+**
104405
+** Query planning consists of building up a collection of these WhereLoop
104406
+** objects, then computing a particular sequence of WhereLoop objects, with
104407
+** one WhereLoop object per FROM clause term, that satisfy all dependencies
104408
+** and that minimize the overall cost.
104409
+*/
104410
+struct WhereLoop {
104411
+ Bitmask prereq; /* Bitmask of other loops that must run first */
104412
+ Bitmask maskSelf; /* Bitmask identifying table iTab */
104413
+#ifdef SQLITE_DEBUG
104414
+ char cId; /* Symbolic ID of this loop for debugging use */
104415
+#endif
104416
+ u8 iTab; /* Position in FROM clause of table for this loop */
104417
+ u8 iSortIdx; /* Sorting index number. 0==None */
104418
+ WhereCost rSetup; /* One-time setup cost (ex: create transient index) */
104419
+ WhereCost rRun; /* Cost of running each loop */
104420
+ WhereCost nOut; /* Estimated number of output rows */
104421
+ union {
104422
+ struct { /* Information for internal btree tables */
104423
+ int nEq; /* Number of equality constraints */
104424
+ Index *pIndex; /* Index used, or NULL */
104425
+ } btree;
104426
+ struct { /* Information for virtual tables */
104427
+ int idxNum; /* Index number */
104428
+ u8 needFree; /* True if sqlite3_free(idxStr) is needed */
104429
+ u8 isOrdered; /* True if satisfies ORDER BY */
104430
+ u16 omitMask; /* Terms that may be omitted */
104431
+ char *idxStr; /* Index identifier string */
104432
+ } vtab;
104433
+ } u;
104434
+ u32 wsFlags; /* WHERE_* flags describing the plan */
104435
+ u16 nLTerm; /* Number of entries in aLTerm[] */
104436
+ /**** whereLoopXfer() copies fields above ***********************/
104437
+# define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
104438
+ u16 nLSlot; /* Number of slots allocated for aLTerm[] */
104439
+ WhereTerm **aLTerm; /* WhereTerms used */
104440
+ WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
104441
+ WhereTerm *aLTermSpace[4]; /* Initial aLTerm[] space */
104442
+};
104443
+
104444
+/* Forward declaration of methods */
104445
+static int whereLoopResize(sqlite3*, WhereLoop*, int);
104446
+
104447
+/*
104448
+** Each instance of this object holds a sequence of WhereLoop objects
104449
+** that implement some or all of a query plan.
104450
+**
104451
+** Think of each WhereLoop objects as a node in a graph, which arcs
104452
+** showing dependences and costs for travelling between nodes. (That is
104453
+** not a completely accurate description because WhereLoop costs are a
104454
+** vector, not a scalar, and because dependences are many-to-one, not
104455
+** one-to-one as are graph nodes. But it is a useful visualization aid.)
104456
+** Then a WherePath object is a path through the graph that visits some
104457
+** or all of the WhereLoop objects once.
104458
+**
104459
+** The "solver" works by creating the N best WherePath objects of length
104460
+** 1. Then using those as a basis to compute the N best WherePath objects
104461
+** of length 2. And so forth until the length of WherePaths equals the
104462
+** number of nodes in the FROM clause. The best (lowest cost) WherePath
104463
+** at the end is the choosen query plan.
104464
+*/
104465
+struct WherePath {
104466
+ Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */
104467
+ Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */
104468
+ WhereCost nRow; /* Estimated number of rows generated by this path */
104469
+ WhereCost rCost; /* Total cost of this path */
104470
+ u8 isOrdered; /* True if this path satisfies ORDER BY */
104471
+ u8 isOrderedValid; /* True if the isOrdered field is valid */
104472
+ WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */
104473
+};
104414104474
104415104475
/*
104416104476
** The query generator uses an array of instances of this structure to
104417104477
** help it analyze the subexpressions of the WHERE clause. Each WHERE
104418104478
** clause subexpression is separated from the others by AND operators,
@@ -104461,11 +104521,10 @@
104461104521
**
104462104522
** The number of terms in a join is limited by the number of bits
104463104523
** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
104464104524
** is only able to process joins with 64 or fewer tables.
104465104525
*/
104466
-typedef struct WhereTerm WhereTerm;
104467104526
struct WhereTerm {
104468104527
Expr *pExpr; /* Pointer to the subexpression that is this term */
104469104528
int iParent; /* Disable pWC->a[iParent] when this term disabled */
104470104529
int leftCursor; /* Cursor number of X in "X <op> <expr>" */
104471104530
union {
@@ -104495,10 +104554,26 @@
104495104554
# define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
104496104555
#else
104497104556
# define TERM_VNULL 0x00 /* Disabled if not using stat3 */
104498104557
#endif
104499104558
104559
+/*
104560
+** An instance of the WhereScan object is used as an iterator for locating
104561
+** terms in the WHERE clause that are useful to the query planner.
104562
+*/
104563
+struct WhereScan {
104564
+ WhereClause *pOrigWC; /* Original, innermost WhereClause */
104565
+ WhereClause *pWC; /* WhereClause currently being scanned */
104566
+ char *zCollName; /* Required collating sequence, if not NULL */
104567
+ char idxaff; /* Must match this affinity, if zCollName!=NULL */
104568
+ unsigned char nEquiv; /* Number of entries in aEquiv[] */
104569
+ unsigned char iEquiv; /* Next unused slot in aEquiv[] */
104570
+ u32 opMask; /* Acceptable operators */
104571
+ int k; /* Resume scanning at this->pWC->a[this->k] */
104572
+ int aEquiv[22]; /* Cursor,Column pairs for equivalence classes */
104573
+};
104574
+
104500104575
/*
104501104576
** An instance of the following structure holds all information about a
104502104577
** WHERE clause. Mostly this is a container for one or more WhereTerms.
104503104578
**
104504104579
** Explanation of pOuter: For a WHERE clause of the form
@@ -104508,15 +104583,13 @@
104508104583
** There are separate WhereClause objects for the whole clause and for
104509104584
** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
104510104585
** subclauses points to the WhereClause object for the whole clause.
104511104586
*/
104512104587
struct WhereClause {
104513
- Parse *pParse; /* The parser context */
104514
- WhereMaskSet *pMaskSet; /* Mapping of table cursor numbers to bitmasks */
104588
+ WhereInfo *pWInfo; /* WHERE clause processing context */
104515104589
WhereClause *pOuter; /* Outer conjunction */
104516104590
u8 op; /* Split operator. TK_AND or TK_OR */
104517
- u16 wctrlFlags; /* Might include WHERE_AND_ONLY */
104518104591
int nTerm; /* Number of terms */
104519104592
int nSlot; /* Number of entries in a[] */
104520104593
WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
104521104594
#if defined(SQLITE_SMALL_STACK)
104522104595
WhereTerm aStatic[1]; /* Initial static space for a[] */
@@ -104572,23 +104645,59 @@
104572104645
int n; /* Number of assigned cursor values */
104573104646
int ix[BMS]; /* Cursor assigned to each bit */
104574104647
};
104575104648
104576104649
/*
104577
-** A WhereCost object records a lookup strategy and the estimated
104578
-** cost of pursuing that strategy.
104650
+** This object is a convenience wrapper holding all information needed
104651
+** to construct WhereLoop objects for a particular query.
104579104652
*/
104580
-struct WhereCost {
104581
- WherePlan plan; /* The lookup strategy */
104582
- double rCost; /* Overall cost of pursuing this search strategy */
104583
- Bitmask used; /* Bitmask of cursors used by this plan */
104653
+struct WhereLoopBuilder {
104654
+ WhereInfo *pWInfo; /* Information about this WHERE */
104655
+ WhereClause *pWC; /* WHERE clause terms */
104656
+ ExprList *pOrderBy; /* ORDER BY clause */
104657
+ WhereLoop *pNew; /* Template WhereLoop */
104658
+ WhereLoop *pBest; /* If non-NULL, store single best loop here */
104584104659
};
104585104660
104586104661
/*
104587
-** Bitmasks for the operators that indices are able to exploit. An
104662
+** The WHERE clause processing routine has two halves. The
104663
+** first part does the start of the WHERE loop and the second
104664
+** half does the tail of the WHERE loop. An instance of
104665
+** this structure is returned by the first half and passed
104666
+** into the second half to give some continuity.
104667
+**
104668
+** An instance of this object holds the complete state of the query
104669
+** planner.
104670
+*/
104671
+struct WhereInfo {
104672
+ Parse *pParse; /* Parsing and code generating context */
104673
+ SrcList *pTabList; /* List of tables in the join */
104674
+ ExprList *pOrderBy; /* The ORDER BY clause or NULL */
104675
+ ExprList *pDistinct; /* DISTINCT ON values, or NULL */
104676
+ WhereLoop *pLoops; /* List of all WhereLoop objects */
104677
+ Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
104678
+ WhereCost nRowOut; /* Estimated number of output rows */
104679
+ u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
104680
+ u8 bOBSat; /* ORDER BY satisfied by indices */
104681
+ u8 okOnePass; /* Ok to use one-pass algorithm for UPDATE/DELETE */
104682
+ u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
104683
+ u8 eDistinct; /* One of the WHERE_DISTINCT_* values below */
104684
+ int iTop; /* The very beginning of the WHERE loop */
104685
+ int iContinue; /* Jump here to continue with next record */
104686
+ int iBreak; /* Jump here to break out of the loop */
104687
+ int nLevel; /* Number of nested loop */
104688
+ int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
104689
+ WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */
104690
+ WhereClause sWC; /* Decomposition of the WHERE clause */
104691
+ WhereLevel a[1]; /* Information about each nest loop in WHERE */
104692
+};
104693
+
104694
+/*
104695
+** Bitmasks for the operators on WhereTerm objects. These are all
104696
+** operators that are of interest to the query planner. An
104588104697
** OR-ed combination of these values can be used when searching for
104589
-** terms in the where clause.
104698
+** particular WhereTerms within a WhereClause.
104590104699
*/
104591104700
#define WO_IN 0x001
104592104701
#define WO_EQ 0x002
104593104702
#define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
104594104703
#define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
@@ -104603,96 +104712,106 @@
104603104712
104604104713
#define WO_ALL 0xfff /* Mask of all possible WO_* values */
104605104714
#define WO_SINGLE 0x0ff /* Mask of all non-compound WO_* values */
104606104715
104607104716
/*
104608
-** Value for wsFlags returned by bestIndex() and stored in
104609
-** WhereLevel.wsFlags. These flags determine which search
104610
-** strategies are appropriate.
104611
-**
104612
-** The least significant 12 bits is reserved as a mask for WO_ values above.
104613
-** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
104614
-** But if the table is the right table of a left join, WhereLevel.wsFlags
104615
-** is set to WO_IN|WO_EQ. The WhereLevel.wsFlags field can then be used as
104616
-** the "op" parameter to findTerm when we are resolving equality constraints.
104617
-** ISNULL constraints will then not be used on the right table of a left
104618
-** join. Tickets #2177 and #2189.
104619
-*/
104620
-#define WHERE_ROWID_EQ 0x00001000 /* rowid=EXPR or rowid IN (...) */
104621
-#define WHERE_ROWID_RANGE 0x00002000 /* rowid<EXPR and/or rowid>EXPR */
104622
-#define WHERE_COLUMN_EQ 0x00010000 /* x=EXPR or x IN (...) or x IS NULL */
104623
-#define WHERE_COLUMN_RANGE 0x00020000 /* x<EXPR and/or x>EXPR */
104624
-#define WHERE_COLUMN_IN 0x00040000 /* x IN (...) */
104625
-#define WHERE_COLUMN_NULL 0x00080000 /* x IS NULL */
104626
-#define WHERE_INDEXED 0x000f0000 /* Anything that uses an index */
104627
-#define WHERE_NOT_FULLSCAN 0x100f3000 /* Does not do a full table scan */
104628
-#define WHERE_IN_ABLE 0x080f1000 /* Able to support an IN operator */
104629
-#define WHERE_TOP_LIMIT 0x00100000 /* x<EXPR or x<=EXPR constraint */
104630
-#define WHERE_BTM_LIMIT 0x00200000 /* x>EXPR or x>=EXPR constraint */
104631
-#define WHERE_BOTH_LIMIT 0x00300000 /* Both x>EXPR and x<EXPR */
104632
-#define WHERE_IDX_ONLY 0x00400000 /* Use index only - omit table */
104633
-#define WHERE_ORDERED 0x00800000 /* Output will appear in correct order */
104634
-#define WHERE_REVERSE 0x01000000 /* Scan in reverse order */
104635
-#define WHERE_UNIQUE 0x02000000 /* Selects no more than one row */
104636
-#define WHERE_ALL_UNIQUE 0x04000000 /* This and all prior have one row */
104637
-#define WHERE_OB_UNIQUE 0x00004000 /* Values in ORDER BY columns are
104638
- ** different for every output row */
104639
-#define WHERE_VIRTUALTABLE 0x08000000 /* Use virtual-table processing */
104640
-#define WHERE_MULTI_OR 0x10000000 /* OR using multiple indices */
104641
-#define WHERE_TEMP_INDEX 0x20000000 /* Uses an ephemeral index */
104642
-#define WHERE_DISTINCT 0x40000000 /* Correct order for DISTINCT */
104643
-#define WHERE_COVER_SCAN 0x80000000 /* Full scan of a covering index */
104644
-
104645
-/*
104646
-** This module contains many separate subroutines that work together to
104647
-** find the best indices to use for accessing a particular table in a query.
104648
-** An instance of the following structure holds context information about the
104649
-** index search so that it can be more easily passed between the various
104650
-** routines.
104651
-*/
104652
-typedef struct WhereBestIdx WhereBestIdx;
104653
-struct WhereBestIdx {
104654
- Parse *pParse; /* Parser context */
104655
- WhereClause *pWC; /* The WHERE clause */
104656
- struct SrcList_item *pSrc; /* The FROM clause term to search */
104657
- Bitmask notReady; /* Mask of cursors not available */
104658
- Bitmask notValid; /* Cursors not available for any purpose */
104659
- ExprList *pOrderBy; /* The ORDER BY clause */
104660
- ExprList *pDistinct; /* The select-list if query is DISTINCT */
104661
- sqlite3_index_info **ppIdxInfo; /* Index information passed to xBestIndex */
104662
- int i, n; /* Which loop is being coded; # of loops */
104663
- WhereLevel *aLevel; /* Info about outer loops */
104664
- WhereCost cost; /* Lowest cost query plan */
104665
-};
104666
-
104667
-/*
104668
-** Return TRUE if the probe cost is less than the baseline cost
104669
-*/
104670
-static int compareCost(const WhereCost *pProbe, const WhereCost *pBaseline){
104671
- if( pProbe->rCost<pBaseline->rCost ) return 1;
104672
- if( pProbe->rCost>pBaseline->rCost ) return 0;
104673
- if( pProbe->plan.nOBSat>pBaseline->plan.nOBSat ) return 1;
104674
- if( pProbe->plan.nRow<pBaseline->plan.nRow ) return 1;
104675
- return 0;
104717
+** These are definitions of bits in the WhereLoop.wsFlags field.
104718
+** The particular combination of bits in each WhereLoop help to
104719
+** determine the algorithm that WhereLoop represents.
104720
+*/
104721
+#define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR or x IN (...) or x IS NULL */
104722
+#define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */
104723
+#define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */
104724
+#define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */
104725
+#define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */
104726
+#define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */
104727
+#define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */
104728
+#define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */
104729
+#define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
104730
+#define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */
104731
+#define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */
104732
+#define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */
104733
+#define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
104734
+#define WHERE_ONEROW 0x00001000 /* Selects no more than one row */
104735
+#define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */
104736
+#define WHERE_TEMP_INDEX 0x00004000 /* Uses an ephemeral index */
104737
+
104738
+
104739
+/* Convert a WhereCost value (10 times log2(X)) into its integer value X.
104740
+** A rough approximation is used. The value returned is not exact.
104741
+*/
104742
+static u64 whereCostToInt(WhereCost x){
104743
+ u64 n;
104744
+ if( x<10 ) return 1;
104745
+ n = x%10;
104746
+ x /= 10;
104747
+ if( n>=5 ) n -= 2;
104748
+ else if( n>=1 ) n -= 1;
104749
+ if( x>=3 ) return (n+8)<<(x-3);
104750
+ return (n+8)>>(3-x);
104751
+}
104752
+
104753
+/*
104754
+** Return the estimated number of output rows from a WHERE clause
104755
+*/
104756
+SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
104757
+ return whereCostToInt(pWInfo->nRowOut);
104758
+}
104759
+
104760
+/*
104761
+** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
104762
+** WHERE clause returns outputs for DISTINCT processing.
104763
+*/
104764
+SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
104765
+ return pWInfo->eDistinct;
104766
+}
104767
+
104768
+/*
104769
+** Return TRUE if the WHERE clause returns rows in ORDER BY order.
104770
+** Return FALSE if the output needs to be sorted.
104771
+*/
104772
+SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
104773
+ return pWInfo->bOBSat!=0;
104774
+}
104775
+
104776
+/*
104777
+** Return the VDBE address or label to jump to in order to continue
104778
+** immediately with the next row of a WHERE clause.
104779
+*/
104780
+SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
104781
+ return pWInfo->iContinue;
104782
+}
104783
+
104784
+/*
104785
+** Return the VDBE address or label to jump to in order to break
104786
+** out of a WHERE loop.
104787
+*/
104788
+SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
104789
+ return pWInfo->iBreak;
104790
+}
104791
+
104792
+/*
104793
+** Return TRUE if an UPDATE or DELETE statement can operate directly on
104794
+** the rowids returned by a WHERE clause. Return FALSE if doing an
104795
+** UPDATE or DELETE might change subsequent WHERE clause results.
104796
+*/
104797
+SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo){
104798
+ return pWInfo->okOnePass;
104676104799
}
104677104800
104678104801
/*
104679104802
** Initialize a preallocated WhereClause structure.
104680104803
*/
104681104804
static void whereClauseInit(
104682104805
WhereClause *pWC, /* The WhereClause to be initialized */
104683
- Parse *pParse, /* The parsing context */
104684
- WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmasks */
104685
- u16 wctrlFlags /* Might include WHERE_AND_ONLY */
104806
+ WhereInfo *pWInfo /* The WHERE processing context */
104686104807
){
104687
- pWC->pParse = pParse;
104688
- pWC->pMaskSet = pMaskSet;
104808
+ pWC->pWInfo = pWInfo;
104689104809
pWC->pOuter = 0;
104690104810
pWC->nTerm = 0;
104691104811
pWC->nSlot = ArraySize(pWC->aStatic);
104692104812
pWC->a = pWC->aStatic;
104693
- pWC->wctrlFlags = wctrlFlags;
104694104813
}
104695104814
104696104815
/* Forward reference */
104697104816
static void whereClauseClear(WhereClause*);
104698104817
@@ -104717,11 +104836,11 @@
104717104836
** itself is not freed. This routine is the inverse of whereClauseInit().
104718104837
*/
104719104838
static void whereClauseClear(WhereClause *pWC){
104720104839
int i;
104721104840
WhereTerm *a;
104722
- sqlite3 *db = pWC->pParse->db;
104841
+ sqlite3 *db = pWC->pWInfo->pParse->db;
104723104842
for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
104724104843
if( a->wtFlags & TERM_DYNAMIC ){
104725104844
sqlite3ExprDelete(db, a->pExpr);
104726104845
}
104727104846
if( a->wtFlags & TERM_ORINFO ){
@@ -104758,11 +104877,11 @@
104758104877
WhereTerm *pTerm;
104759104878
int idx;
104760104879
testcase( wtFlags & TERM_VIRTUAL ); /* EV: R-00211-15100 */
104761104880
if( pWC->nTerm>=pWC->nSlot ){
104762104881
WhereTerm *pOld = pWC->a;
104763
- sqlite3 *db = pWC->pParse->db;
104882
+ sqlite3 *db = pWC->pWInfo->pParse->db;
104764104883
pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
104765104884
if( pWC->a==0 ){
104766104885
if( wtFlags & TERM_DYNAMIC ){
104767104886
sqlite3ExprDelete(db, p);
104768104887
}
@@ -104798,12 +104917,12 @@
104798104917
**
104799104918
** In the previous sentence and in the diagram, "slot[]" refers to
104800104919
** the WhereClause.a[] array. The slot[] array grows as needed to contain
104801104920
** all terms of the WHERE clause.
104802104921
*/
104803
-static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
104804
- pWC->op = (u8)op;
104922
+static void whereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
104923
+ pWC->op = op;
104805104924
if( pExpr==0 ) return;
104806104925
if( pExpr->op!=op ){
104807104926
whereClauseInsert(pWC, pExpr, 0);
104808104927
}else{
104809104928
whereSplit(pWC, pExpr->pLeft, op);
@@ -104810,13 +104929,13 @@
104810104929
whereSplit(pWC, pExpr->pRight, op);
104811104930
}
104812104931
}
104813104932
104814104933
/*
104815
-** Initialize an expression mask set (a WhereMaskSet object)
104934
+** Initialize a WhereMaskSet object
104816104935
*/
104817
-#define initMaskSet(P) memset(P, 0, sizeof(*P))
104936
+#define initMaskSet(P) (P)->n=0
104818104937
104819104938
/*
104820104939
** Return the bitmask for the given cursor number. Return 0 if
104821104940
** iCursor is not in the set.
104822104941
*/
@@ -104823,11 +104942,11 @@
104823104942
static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
104824104943
int i;
104825104944
assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
104826104945
for(i=0; i<pMaskSet->n; i++){
104827104946
if( pMaskSet->ix[i]==iCursor ){
104828
- return ((Bitmask)1)<<i;
104947
+ return MASKBIT(i);
104829104948
}
104830104949
}
104831104950
return 0;
104832104951
}
104833104952
@@ -104843,22 +104962,13 @@
104843104962
assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
104844104963
pMaskSet->ix[pMaskSet->n++] = iCursor;
104845104964
}
104846104965
104847104966
/*
104848
-** This routine walks (recursively) an expression tree and generates
104967
+** These routine walk (recursively) an expression tree and generates
104849104968
** a bitmask indicating which tables are used in that expression
104850104969
** tree.
104851
-**
104852
-** In order for this routine to work, the calling function must have
104853
-** previously invoked sqlite3ResolveExprNames() on the expression. See
104854
-** the header comment on that routine for additional information.
104855
-** The sqlite3ResolveExprNames() routines looks for column names and
104856
-** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
104857
-** the VDBE cursor number of the table. This routine just has to
104858
-** translate the cursor numbers into bitmask values and OR all
104859
-** the bitmasks together.
104860104970
*/
104861104971
static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
104862104972
static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
104863104973
static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
104864104974
Bitmask mask = 0;
@@ -104908,11 +105018,11 @@
104908105018
}
104909105019
104910105020
/*
104911105021
** Return TRUE if the given operator is one of the operators that is
104912105022
** allowed for an indexable WHERE clause term. The allowed operators are
104913
-** "=", "<", ">", "<=", ">=", and "IN".
105023
+** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
104914105024
**
104915105025
** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
104916105026
** of one of the following forms: column = expression column > expression
104917105027
** column >= expression column < expression column <= expression
104918105028
** expression = column expression > column expression >= column
@@ -104935,14 +105045,13 @@
104935105045
/*
104936105046
** Commute a comparison operator. Expressions of the form "X op Y"
104937105047
** are converted into "Y op X".
104938105048
**
104939105049
** If left/right precedence rules come into play when determining the
104940
-** collating
104941
-** side of the comparison, it remains associated with the same side after
104942
-** the commutation. So "Y collate NOCASE op X" becomes
104943
-** "X op Y". This is because any collation sequence on
105050
+** collating sequence, then COLLATE operators are adjusted to ensure
105051
+** that the collating sequence does not change. For example:
105052
+** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
104944105053
** the left hand side of a comparison overrides any collation sequence
104945105054
** attached to the right. For the same reason the EP_Collate flag
104946105055
** is not commuted.
104947105056
*/
104948105057
static void exprCommute(Parse *pParse, Expr *pExpr){
@@ -104994,10 +105103,134 @@
104994105103
assert( op!=TK_LE || c==WO_LE );
104995105104
assert( op!=TK_GT || c==WO_GT );
104996105105
assert( op!=TK_GE || c==WO_GE );
104997105106
return c;
104998105107
}
105108
+
105109
+/*
105110
+** Advance to the next WhereTerm that matches according to the criteria
105111
+** established when the pScan object was initialized by whereScanInit().
105112
+** Return NULL if there are no more matching WhereTerms.
105113
+*/
105114
+WhereTerm *whereScanNext(WhereScan *pScan){
105115
+ int iCur; /* The cursor on the LHS of the term */
105116
+ int iColumn; /* The column on the LHS of the term. -1 for IPK */
105117
+ Expr *pX; /* An expression being tested */
105118
+ WhereClause *pWC; /* Shorthand for pScan->pWC */
105119
+ WhereTerm *pTerm; /* The term being tested */
105120
+ int k = pScan->k; /* Where to start scanning */
105121
+
105122
+ while( pScan->iEquiv<=pScan->nEquiv ){
105123
+ iCur = pScan->aEquiv[pScan->iEquiv-2];
105124
+ iColumn = pScan->aEquiv[pScan->iEquiv-1];
105125
+ while( (pWC = pScan->pWC)!=0 ){
105126
+ for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
105127
+ if( pTerm->leftCursor==iCur && pTerm->u.leftColumn==iColumn ){
105128
+ if( (pTerm->eOperator & WO_EQUIV)!=0
105129
+ && pScan->nEquiv<ArraySize(pScan->aEquiv)
105130
+ ){
105131
+ int j;
105132
+ pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
105133
+ assert( pX->op==TK_COLUMN );
105134
+ for(j=0; j<pScan->nEquiv; j+=2){
105135
+ if( pScan->aEquiv[j]==pX->iTable
105136
+ && pScan->aEquiv[j+1]==pX->iColumn ){
105137
+ break;
105138
+ }
105139
+ }
105140
+ if( j==pScan->nEquiv ){
105141
+ pScan->aEquiv[j] = pX->iTable;
105142
+ pScan->aEquiv[j+1] = pX->iColumn;
105143
+ pScan->nEquiv += 2;
105144
+ }
105145
+ }
105146
+ if( (pTerm->eOperator & pScan->opMask)!=0 ){
105147
+ /* Verify the affinity and collating sequence match */
105148
+ if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
105149
+ CollSeq *pColl;
105150
+ Parse *pParse = pWC->pWInfo->pParse;
105151
+ pX = pTerm->pExpr;
105152
+ if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
105153
+ continue;
105154
+ }
105155
+ assert(pX->pLeft);
105156
+ pColl = sqlite3BinaryCompareCollSeq(pParse,
105157
+ pX->pLeft, pX->pRight);
105158
+ if( pColl==0 ) pColl = pParse->db->pDfltColl;
105159
+ if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
105160
+ continue;
105161
+ }
105162
+ }
105163
+ if( (pTerm->eOperator & WO_EQ)!=0
105164
+ && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
105165
+ && pX->iTable==pScan->aEquiv[0]
105166
+ && pX->iColumn==pScan->aEquiv[1]
105167
+ ){
105168
+ continue;
105169
+ }
105170
+ pScan->k = k+1;
105171
+ return pTerm;
105172
+ }
105173
+ }
105174
+ }
105175
+ pScan->pWC = pScan->pWC->pOuter;
105176
+ k = 0;
105177
+ }
105178
+ pScan->pWC = pScan->pOrigWC;
105179
+ k = 0;
105180
+ pScan->iEquiv += 2;
105181
+ }
105182
+ return 0;
105183
+}
105184
+
105185
+/*
105186
+** Initialize a WHERE clause scanner object. Return a pointer to the
105187
+** first match. Return NULL if there are no matches.
105188
+**
105189
+** The scanner will be searching the WHERE clause pWC. It will look
105190
+** for terms of the form "X <op> <expr>" where X is column iColumn of table
105191
+** iCur. The <op> must be one of the operators described by opMask.
105192
+**
105193
+** If the search is for X and the WHERE clause contains terms of the
105194
+** form X=Y then this routine might also return terms of the form
105195
+** "Y <op> <expr>". The number of levels of transitivity is limited,
105196
+** but is enough to handle most commonly occurring SQL statements.
105197
+**
105198
+** If X is not the INTEGER PRIMARY KEY then X must be compatible with
105199
+** index pIdx.
105200
+*/
105201
+WhereTerm *whereScanInit(
105202
+ WhereScan *pScan, /* The WhereScan object being initialized */
105203
+ WhereClause *pWC, /* The WHERE clause to be scanned */
105204
+ int iCur, /* Cursor to scan for */
105205
+ int iColumn, /* Column to scan for */
105206
+ u32 opMask, /* Operator(s) to scan for */
105207
+ Index *pIdx /* Must be compatible with this index */
105208
+){
105209
+ int j;
105210
+
105211
+ /* memset(pScan, 0, sizeof(*pScan)); */
105212
+ pScan->pOrigWC = pWC;
105213
+ pScan->pWC = pWC;
105214
+ if( pIdx && iColumn>=0 ){
105215
+ pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
105216
+ for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
105217
+ if( NEVER(j>=pIdx->nColumn) ) return 0;
105218
+ }
105219
+ pScan->zCollName = pIdx->azColl[j];
105220
+ }else{
105221
+ pScan->idxaff = 0;
105222
+ pScan->zCollName = 0;
105223
+ }
105224
+ pScan->opMask = opMask;
105225
+ pScan->k = 0;
105226
+ pScan->aEquiv[0] = iCur;
105227
+ pScan->aEquiv[1] = iColumn;
105228
+ pScan->nEquiv = 2;
105229
+ pScan->iEquiv = 2;
105230
+ return whereScanNext(pScan);
105231
+}
104999105232
105000105233
/*
105001105234
** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
105002105235
** where X is a reference to the iColumn of table iCur and <op> is one of
105003105236
** the WO_xx operator codes specified by the op parameter.
@@ -105026,98 +105259,32 @@
105026105259
int iColumn, /* Column number of LHS */
105027105260
Bitmask notReady, /* RHS must not overlap with this mask */
105028105261
u32 op, /* Mask of WO_xx values describing operator */
105029105262
Index *pIdx /* Must be compatible with this index, if not NULL */
105030105263
){
105031
- WhereTerm *pTerm; /* Term being examined as possible result */
105032
- WhereTerm *pResult = 0; /* The answer to return */
105033
- WhereClause *pWCOrig = pWC; /* Original pWC value */
105034
- int j, k; /* Loop counters */
105035
- Expr *pX; /* Pointer to an expression */
105036
- Parse *pParse; /* Parsing context */
105037
- int iOrigCol = iColumn; /* Original value of iColumn */
105038
- int nEquiv = 2; /* Number of entires in aEquiv[] */
105039
- int iEquiv = 2; /* Number of entries of aEquiv[] processed so far */
105040
- int aEquiv[22]; /* iCur,iColumn and up to 10 other equivalents */
105041
-
105042
- assert( iCur>=0 );
105043
- aEquiv[0] = iCur;
105044
- aEquiv[1] = iColumn;
105045
- for(;;){
105046
- for(pWC=pWCOrig; pWC; pWC=pWC->pOuter){
105047
- for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
105048
- if( pTerm->leftCursor==iCur
105049
- && pTerm->u.leftColumn==iColumn
105050
- ){
105051
- if( (pTerm->prereqRight & notReady)==0
105052
- && (pTerm->eOperator & op & WO_ALL)!=0
105053
- ){
105054
- if( iOrigCol>=0 && pIdx && (pTerm->eOperator & WO_ISNULL)==0 ){
105055
- CollSeq *pColl;
105056
- char idxaff;
105057
-
105058
- pX = pTerm->pExpr;
105059
- pParse = pWC->pParse;
105060
- idxaff = pIdx->pTable->aCol[iOrigCol].affinity;
105061
- if( !sqlite3IndexAffinityOk(pX, idxaff) ){
105062
- continue;
105063
- }
105064
-
105065
- /* Figure out the collation sequence required from an index for
105066
- ** it to be useful for optimising expression pX. Store this
105067
- ** value in variable pColl.
105068
- */
105069
- assert(pX->pLeft);
105070
- pColl = sqlite3BinaryCompareCollSeq(pParse,pX->pLeft,pX->pRight);
105071
- if( pColl==0 ) pColl = pParse->db->pDfltColl;
105072
-
105073
- for(j=0; pIdx->aiColumn[j]!=iOrigCol; j++){
105074
- if( NEVER(j>=pIdx->nColumn) ) return 0;
105075
- }
105076
- if( sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ){
105077
- continue;
105078
- }
105079
- }
105080
- if( pTerm->prereqRight==0 && (pTerm->eOperator&WO_EQ)!=0 ){
105081
- pResult = pTerm;
105082
- goto findTerm_success;
105083
- }else if( pResult==0 ){
105084
- pResult = pTerm;
105085
- }
105086
- }
105087
- if( (pTerm->eOperator & WO_EQUIV)!=0
105088
- && nEquiv<ArraySize(aEquiv)
105089
- ){
105090
- pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
105091
- assert( pX->op==TK_COLUMN );
105092
- for(j=0; j<nEquiv; j+=2){
105093
- if( aEquiv[j]==pX->iTable && aEquiv[j+1]==pX->iColumn ) break;
105094
- }
105095
- if( j==nEquiv ){
105096
- aEquiv[j] = pX->iTable;
105097
- aEquiv[j+1] = pX->iColumn;
105098
- nEquiv += 2;
105099
- }
105100
- }
105101
- }
105102
- }
105103
- }
105104
- if( iEquiv>=nEquiv ) break;
105105
- iCur = aEquiv[iEquiv++];
105106
- iColumn = aEquiv[iEquiv++];
105107
- }
105108
-findTerm_success:
105264
+ WhereTerm *pResult = 0;
105265
+ WhereTerm *p;
105266
+ WhereScan scan;
105267
+
105268
+ p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
105269
+ while( p ){
105270
+ if( (p->prereqRight & notReady)==0 ){
105271
+ if( p->prereqRight==0 && (p->eOperator&WO_EQ)!=0 ){
105272
+ return p;
105273
+ }
105274
+ if( pResult==0 ) pResult = p;
105275
+ }
105276
+ p = whereScanNext(&scan);
105277
+ }
105109105278
return pResult;
105110105279
}
105111105280
105112105281
/* Forward reference */
105113105282
static void exprAnalyze(SrcList*, WhereClause*, int);
105114105283
105115105284
/*
105116105285
** Call exprAnalyze on all terms in a WHERE clause.
105117
-**
105118
-**
105119105286
*/
105120105287
static void exprAnalyzeAll(
105121105288
SrcList *pTabList, /* the FROM clause */
105122105289
WhereClause *pWC /* the WHERE clause to be analyzed */
105123105290
){
@@ -105345,15 +105512,15 @@
105345105512
static void exprAnalyzeOrTerm(
105346105513
SrcList *pSrc, /* the FROM clause */
105347105514
WhereClause *pWC, /* the complete WHERE clause */
105348105515
int idxTerm /* Index of the OR-term to be analyzed */
105349105516
){
105350
- Parse *pParse = pWC->pParse; /* Parser context */
105517
+ WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
105518
+ Parse *pParse = pWInfo->pParse; /* Parser context */
105351105519
sqlite3 *db = pParse->db; /* Database connection */
105352105520
WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
105353105521
Expr *pExpr = pTerm->pExpr; /* The expression of the term */
105354
- WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
105355105522
int i; /* Loop counters */
105356105523
WhereClause *pOrWc; /* Breakup of pTerm into subterms */
105357105524
WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
105358105525
WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
105359105526
Bitmask chngToIN; /* Tables that might satisfy case 1 */
@@ -105368,11 +105535,11 @@
105368105535
assert( pExpr->op==TK_OR );
105369105536
pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
105370105537
if( pOrInfo==0 ) return;
105371105538
pTerm->wtFlags |= TERM_ORINFO;
105372105539
pOrWc = &pOrInfo->wc;
105373
- whereClauseInit(pOrWc, pWC->pParse, pMaskSet, pWC->wctrlFlags);
105540
+ whereClauseInit(pOrWc, pWInfo);
105374105541
whereSplit(pOrWc, pExpr, TK_OR);
105375105542
exprAnalyzeAll(pSrc, pOrWc);
105376105543
if( db->mallocFailed ) return;
105377105544
assert( pOrWc->nTerm>=2 );
105378105545
@@ -105394,20 +105561,20 @@
105394105561
Bitmask b = 0;
105395105562
pOrTerm->u.pAndInfo = pAndInfo;
105396105563
pOrTerm->wtFlags |= TERM_ANDINFO;
105397105564
pOrTerm->eOperator = WO_AND;
105398105565
pAndWC = &pAndInfo->wc;
105399
- whereClauseInit(pAndWC, pWC->pParse, pMaskSet, pWC->wctrlFlags);
105566
+ whereClauseInit(pAndWC, pWC->pWInfo);
105400105567
whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
105401105568
exprAnalyzeAll(pSrc, pAndWC);
105402105569
pAndWC->pOuter = pWC;
105403105570
testcase( db->mallocFailed );
105404105571
if( !db->mallocFailed ){
105405105572
for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
105406105573
assert( pAndTerm->pExpr );
105407105574
if( allowedOp(pAndTerm->pExpr->op) ){
105408
- b |= getMask(pMaskSet, pAndTerm->leftCursor);
105575
+ b |= getMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
105409105576
}
105410105577
}
105411105578
}
105412105579
indexable &= b;
105413105580
}
@@ -105414,14 +105581,14 @@
105414105581
}else if( pOrTerm->wtFlags & TERM_COPIED ){
105415105582
/* Skip this term for now. We revisit it when we process the
105416105583
** corresponding TERM_VIRTUAL term */
105417105584
}else{
105418105585
Bitmask b;
105419
- b = getMask(pMaskSet, pOrTerm->leftCursor);
105586
+ b = getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
105420105587
if( pOrTerm->wtFlags & TERM_VIRTUAL ){
105421105588
WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
105422
- b |= getMask(pMaskSet, pOther->leftCursor);
105589
+ b |= getMask(&pWInfo->sMaskSet, pOther->leftCursor);
105423105590
}
105424105591
indexable &= b;
105425105592
if( (pOrTerm->eOperator & WO_EQ)==0 ){
105426105593
chngToIN = 0;
105427105594
}else{
@@ -105479,11 +105646,11 @@
105479105646
/* This is the 2-bit case and we are on the second iteration and
105480105647
** current term is from the first iteration. So skip this term. */
105481105648
assert( j==1 );
105482105649
continue;
105483105650
}
105484
- if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
105651
+ if( (chngToIN & getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){
105485105652
/* This term must be of the form t1.a==t2.b where t2 is in the
105486105653
** chngToIN set but t1 is not. This term will be either preceeded
105487105654
** or follwed by an inverted copy (t2.b==t1.a). Skip this term
105488105655
** and use its inversion. */
105489105656
testcase( pOrTerm->wtFlags & TERM_COPIED );
@@ -105498,11 +105665,11 @@
105498105665
if( i<0 ){
105499105666
/* No candidate table+column was found. This can only occur
105500105667
** on the second iteration */
105501105668
assert( j==1 );
105502105669
assert( IsPowerOfTwo(chngToIN) );
105503
- assert( chngToIN==getMask(pMaskSet, iCursor) );
105670
+ assert( chngToIN==getMask(&pWInfo->sMaskSet, iCursor) );
105504105671
break;
105505105672
}
105506105673
testcase( j==1 );
105507105674
105508105675
/* We have found a candidate table and column. Check to see if that
@@ -105547,11 +105714,11 @@
105547105714
if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
105548105715
assert( pOrTerm->eOperator & WO_EQ );
105549105716
assert( pOrTerm->leftCursor==iCursor );
105550105717
assert( pOrTerm->u.leftColumn==iColumn );
105551105718
pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
105552
- pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
105719
+ pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
105553105720
pLeft = pOrTerm->pExpr->pLeft;
105554105721
}
105555105722
assert( pLeft!=0 );
105556105723
pDup = sqlite3ExprDup(db, pLeft, 0);
105557105724
pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
@@ -105596,10 +105763,11 @@
105596105763
static void exprAnalyze(
105597105764
SrcList *pSrc, /* the FROM clause */
105598105765
WhereClause *pWC, /* the WHERE clause */
105599105766
int idxTerm /* Index of the term to be analyzed */
105600105767
){
105768
+ WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
105601105769
WhereTerm *pTerm; /* The term to be analyzed */
105602105770
WhereMaskSet *pMaskSet; /* Set of table index masks */
105603105771
Expr *pExpr; /* The expression to be analyzed */
105604105772
Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
105605105773
Bitmask prereqAll; /* Prerequesites of pExpr */
@@ -105606,18 +105774,18 @@
105606105774
Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
105607105775
Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
105608105776
int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
105609105777
int noCase = 0; /* LIKE/GLOB distinguishes case */
105610105778
int op; /* Top-level operator. pExpr->op */
105611
- Parse *pParse = pWC->pParse; /* Parsing context */
105779
+ Parse *pParse = pWInfo->pParse; /* Parsing context */
105612105780
sqlite3 *db = pParse->db; /* Database connection */
105613105781
105614105782
if( db->mallocFailed ){
105615105783
return;
105616105784
}
105617105785
pTerm = &pWC->a[idxTerm];
105618
- pMaskSet = pWC->pMaskSet;
105786
+ pMaskSet = &pWInfo->sMaskSet;
105619105787
pExpr = pTerm->pExpr;
105620105788
assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
105621105789
prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
105622105790
op = pExpr->op;
105623105791
if( op==TK_IN ){
@@ -105891,15 +106059,12 @@
105891106059
*/
105892106060
pTerm->prereqRight |= extraRight;
105893106061
}
105894106062
105895106063
/*
105896
-** This function searches the expression list passed as the second argument
105897
-** for an expression of type TK_COLUMN that refers to the same column and
105898
-** uses the same collation sequence as the iCol'th column of index pIdx.
105899
-** Argument iBase is the cursor number used for the table that pIdx refers
105900
-** to.
106064
+** This function searches pList for a entry that matches the iCol-th column
106065
+** of index pIdx.
105901106066
**
105902106067
** If such an expression is found, its index in pList->a[] is returned. If
105903106068
** no expression is found, -1 is returned.
105904106069
*/
105905106070
static int findIndexCol(
@@ -105925,82 +106090,23 @@
105925106090
}
105926106091
}
105927106092
105928106093
return -1;
105929106094
}
105930
-
105931
-/*
105932
-** This routine determines if pIdx can be used to assist in processing a
105933
-** DISTINCT qualifier. In other words, it tests whether or not using this
105934
-** index for the outer loop guarantees that rows with equal values for
105935
-** all expressions in the pDistinct list are delivered grouped together.
105936
-**
105937
-** For example, the query
105938
-**
105939
-** SELECT DISTINCT a, b, c FROM tbl WHERE a = ?
105940
-**
105941
-** can benefit from any index on columns "b" and "c".
105942
-*/
105943
-static int isDistinctIndex(
105944
- Parse *pParse, /* Parsing context */
105945
- WhereClause *pWC, /* The WHERE clause */
105946
- Index *pIdx, /* The index being considered */
105947
- int base, /* Cursor number for the table pIdx is on */
105948
- ExprList *pDistinct, /* The DISTINCT expressions */
105949
- int nEqCol /* Number of index columns with == */
105950
-){
105951
- Bitmask mask = 0; /* Mask of unaccounted for pDistinct exprs */
105952
- int i; /* Iterator variable */
105953
-
105954
- assert( pDistinct!=0 );
105955
- if( pIdx->zName==0 || pDistinct->nExpr>=BMS ) return 0;
105956
- testcase( pDistinct->nExpr==BMS-1 );
105957
-
105958
- /* Loop through all the expressions in the distinct list. If any of them
105959
- ** are not simple column references, return early. Otherwise, test if the
105960
- ** WHERE clause contains a "col=X" clause. If it does, the expression
105961
- ** can be ignored. If it does not, and the column does not belong to the
105962
- ** same table as index pIdx, return early. Finally, if there is no
105963
- ** matching "col=X" expression and the column is on the same table as pIdx,
105964
- ** set the corresponding bit in variable mask.
105965
- */
105966
- for(i=0; i<pDistinct->nExpr; i++){
105967
- WhereTerm *pTerm;
105968
- Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
105969
- if( p->op!=TK_COLUMN ) return 0;
105970
- pTerm = findTerm(pWC, p->iTable, p->iColumn, ~(Bitmask)0, WO_EQ, 0);
105971
- if( pTerm ){
105972
- Expr *pX = pTerm->pExpr;
105973
- CollSeq *p1 = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
105974
- CollSeq *p2 = sqlite3ExprCollSeq(pParse, p);
105975
- if( p1==p2 ) continue;
105976
- }
105977
- if( p->iTable!=base ) return 0;
105978
- mask |= (((Bitmask)1) << i);
105979
- }
105980
-
105981
- for(i=nEqCol; mask && i<pIdx->nColumn; i++){
105982
- int iExpr = findIndexCol(pParse, pDistinct, base, pIdx, i);
105983
- if( iExpr<0 ) break;
105984
- mask &= ~(((Bitmask)1) << iExpr);
105985
- }
105986
-
105987
- return (mask==0);
105988
-}
105989
-
105990106095
105991106096
/*
105992106097
** Return true if the DISTINCT expression-list passed as the third argument
105993
-** is redundant. A DISTINCT list is redundant if the database contains a
105994
-** UNIQUE index that guarantees that the result of the query will be distinct
105995
-** anyway.
106098
+** is redundant.
106099
+**
106100
+** A DISTINCT list is redundant if the database contains some subset of
106101
+** columns that are unique and non-null.
105996106102
*/
105997106103
static int isDistinctRedundant(
105998
- Parse *pParse,
105999
- SrcList *pTabList,
106000
- WhereClause *pWC,
106001
- ExprList *pDistinct
106104
+ Parse *pParse, /* Parsing context */
106105
+ SrcList *pTabList, /* The FROM clause */
106106
+ WhereClause *pWC, /* The WHERE clause */
106107
+ ExprList *pDistinct /* The result set that needs to be DISTINCT */
106002106108
){
106003106109
Table *pTab;
106004106110
Index *pIdx;
106005106111
int i;
106006106112
int iBase;
@@ -106051,35 +106157,90 @@
106051106157
}
106052106158
}
106053106159
106054106160
return 0;
106055106161
}
106162
+
106163
+/*
106164
+** The (an approximate) sum of two WhereCosts. This computation is
106165
+** not a simple "+" operator because WhereCost is stored as a logarithmic
106166
+** value.
106167
+**
106168
+*/
106169
+static WhereCost whereCostAdd(WhereCost a, WhereCost b){
106170
+ static const unsigned char x[] = {
106171
+ 10, 10, /* 0,1 */
106172
+ 9, 9, /* 2,3 */
106173
+ 8, 8, /* 4,5 */
106174
+ 7, 7, 7, /* 6,7,8 */
106175
+ 6, 6, 6, /* 9,10,11 */
106176
+ 5, 5, 5, /* 12-14 */
106177
+ 4, 4, 4, 4, /* 15-18 */
106178
+ 3, 3, 3, 3, 3, 3, /* 19-24 */
106179
+ 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
106180
+ };
106181
+ if( a>=b ){
106182
+ if( a>b+49 ) return a;
106183
+ if( a>b+31 ) return a+1;
106184
+ return a+x[a-b];
106185
+ }else{
106186
+ if( b>a+49 ) return b;
106187
+ if( b>a+31 ) return b+1;
106188
+ return b+x[b-a];
106189
+ }
106190
+}
106056106191
106057106192
/*
106058
-** Prepare a crude estimate of the logarithm of the input value.
106059
-** The results need not be exact. This is only used for estimating
106060
-** the total cost of performing operations with O(logN) or O(NlogN)
106061
-** complexity. Because N is just a guess, it is no great tragedy if
106062
-** logN is a little off.
106193
+** Convert an integer into a WhereCost. In other words, compute a
106194
+** good approximatation for 10*log2(x).
106063106195
*/
106064
-static double estLog(double N){
106065
- double logN = 1;
106066
- double x = 10;
106067
- while( N>x ){
106068
- logN += 1;
106069
- x *= 10;
106070
- }
106071
- return logN;
106196
+static WhereCost whereCost(tRowcnt x){
106197
+ static WhereCost a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
106198
+ WhereCost y = 40;
106199
+ if( x<8 ){
106200
+ if( x<2 ) return 0;
106201
+ while( x<8 ){ y -= 10; x <<= 1; }
106202
+ }else{
106203
+ while( x>255 ){ y += 40; x >>= 4; }
106204
+ while( x>15 ){ y += 10; x >>= 1; }
106205
+ }
106206
+ return a[x&7] + y - 10;
106207
+}
106208
+
106209
+#ifndef SQLITE_OMIT_VIRTUALTABLE
106210
+/*
106211
+** Convert a double (as received from xBestIndex of a virtual table)
106212
+** into a WhereCost. In other words, compute an approximation for
106213
+** 10*log2(x).
106214
+*/
106215
+static WhereCost whereCostFromDouble(double x){
106216
+ u64 a;
106217
+ WhereCost e;
106218
+ assert( sizeof(x)==8 && sizeof(a)==8 );
106219
+ if( x<=1 ) return 0;
106220
+ if( x<=2000000000 ) return whereCost((tRowcnt)x);
106221
+ memcpy(&a, &x, 8);
106222
+ e = (a>>52) - 1022;
106223
+ return e*10;
106224
+}
106225
+#endif /* SQLITE_OMIT_VIRTUALTABLE */
106226
+
106227
+/*
106228
+** Estimate the logarithm of the input value to base 2.
106229
+*/
106230
+static WhereCost estLog(WhereCost N){
106231
+ WhereCost x = whereCost(N);
106232
+ return x>33 ? x - 33 : 0;
106072106233
}
106073106234
106074106235
/*
106075106236
** Two routines for printing the content of an sqlite3_index_info
106076106237
** structure. Used for testing and debugging only. If neither
106077106238
** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
106078106239
** are no-ops.
106079106240
*/
106080
-#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
106241
+#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
106081106242
static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
106082106243
int i;
106083106244
if( !sqlite3WhereTrace ) return;
106084106245
for(i=0; i<p->nConstraint; i++){
106085106246
sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
@@ -106113,111 +106274,10 @@
106113106274
#else
106114106275
#define TRACE_IDX_INPUTS(A)
106115106276
#define TRACE_IDX_OUTPUTS(A)
106116106277
#endif
106117106278
106118
-/*
106119
-** Required because bestIndex() is called by bestOrClauseIndex()
106120
-*/
106121
-static void bestIndex(WhereBestIdx*);
106122
-
106123
-/*
106124
-** This routine attempts to find an scanning strategy that can be used
106125
-** to optimize an 'OR' expression that is part of a WHERE clause.
106126
-**
106127
-** The table associated with FROM clause term pSrc may be either a
106128
-** regular B-Tree table or a virtual table.
106129
-*/
106130
-static void bestOrClauseIndex(WhereBestIdx *p){
106131
-#ifndef SQLITE_OMIT_OR_OPTIMIZATION
106132
- WhereClause *pWC = p->pWC; /* The WHERE clause */
106133
- struct SrcList_item *pSrc = p->pSrc; /* The FROM clause term to search */
106134
- const int iCur = pSrc->iCursor; /* The cursor of the table */
106135
- const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur); /* Bitmask for pSrc */
106136
- WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm]; /* End of pWC->a[] */
106137
- WhereTerm *pTerm; /* A single term of the WHERE clause */
106138
-
106139
- /* The OR-clause optimization is disallowed if the INDEXED BY or
106140
- ** NOT INDEXED clauses are used or if the WHERE_AND_ONLY bit is set. */
106141
- if( pSrc->notIndexed || pSrc->pIndex!=0 ){
106142
- return;
106143
- }
106144
- if( pWC->wctrlFlags & WHERE_AND_ONLY ){
106145
- return;
106146
- }
106147
-
106148
- /* Search the WHERE clause terms for a usable WO_OR term. */
106149
- for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
106150
- if( (pTerm->eOperator & WO_OR)!=0
106151
- && ((pTerm->prereqAll & ~maskSrc) & p->notReady)==0
106152
- && (pTerm->u.pOrInfo->indexable & maskSrc)!=0
106153
- ){
106154
- WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
106155
- WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
106156
- WhereTerm *pOrTerm;
106157
- int flags = WHERE_MULTI_OR;
106158
- double rTotal = 0;
106159
- double nRow = 0;
106160
- Bitmask used = 0;
106161
- WhereBestIdx sBOI;
106162
-
106163
- sBOI = *p;
106164
- sBOI.pOrderBy = 0;
106165
- sBOI.pDistinct = 0;
106166
- sBOI.ppIdxInfo = 0;
106167
- for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
106168
- WHERETRACE(("... Multi-index OR testing for term %d of %d....\n",
106169
- (pOrTerm - pOrWC->a), (pTerm - pWC->a)
106170
- ));
106171
- if( (pOrTerm->eOperator& WO_AND)!=0 ){
106172
- sBOI.pWC = &pOrTerm->u.pAndInfo->wc;
106173
- bestIndex(&sBOI);
106174
- }else if( pOrTerm->leftCursor==iCur ){
106175
- WhereClause tempWC;
106176
- tempWC.pParse = pWC->pParse;
106177
- tempWC.pMaskSet = pWC->pMaskSet;
106178
- tempWC.pOuter = pWC;
106179
- tempWC.op = TK_AND;
106180
- tempWC.a = pOrTerm;
106181
- tempWC.wctrlFlags = 0;
106182
- tempWC.nTerm = 1;
106183
- sBOI.pWC = &tempWC;
106184
- bestIndex(&sBOI);
106185
- }else{
106186
- continue;
106187
- }
106188
- rTotal += sBOI.cost.rCost;
106189
- nRow += sBOI.cost.plan.nRow;
106190
- used |= sBOI.cost.used;
106191
- if( rTotal>=p->cost.rCost ) break;
106192
- }
106193
-
106194
- /* If there is an ORDER BY clause, increase the scan cost to account
106195
- ** for the cost of the sort. */
106196
- if( p->pOrderBy!=0 ){
106197
- WHERETRACE(("... sorting increases OR cost %.9g to %.9g\n",
106198
- rTotal, rTotal+nRow*estLog(nRow)));
106199
- rTotal += nRow*estLog(nRow);
106200
- }
106201
-
106202
- /* If the cost of scanning using this OR term for optimization is
106203
- ** less than the current cost stored in pCost, replace the contents
106204
- ** of pCost. */
106205
- WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
106206
- if( rTotal<p->cost.rCost ){
106207
- p->cost.rCost = rTotal;
106208
- p->cost.used = used;
106209
- p->cost.plan.nRow = nRow;
106210
- p->cost.plan.nOBSat = p->i ? p->aLevel[p->i-1].plan.nOBSat : 0;
106211
- p->cost.plan.wsFlags = flags;
106212
- p->cost.plan.u.pTerm = pTerm;
106213
- }
106214
- }
106215
- }
106216
-#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
106217
-}
106218
-
106219106279
#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
106220106280
/*
106221106281
** Return TRUE if the WHERE clause term pTerm is of a form where it
106222106282
** could be used with an index to access pSrc, assuming an appropriate
106223106283
** index existed.
@@ -106229,92 +106289,17 @@
106229106289
){
106230106290
char aff;
106231106291
if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
106232106292
if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
106233106293
if( (pTerm->prereqRight & notReady)!=0 ) return 0;
106294
+ if( pTerm->u.leftColumn<0 ) return 0;
106234106295
aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
106235106296
if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
106236106297
return 1;
106237106298
}
106238106299
#endif
106239106300
106240
-#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
106241
-/*
106242
-** If the query plan for pSrc specified in pCost is a full table scan
106243
-** and indexing is allows (if there is no NOT INDEXED clause) and it
106244
-** possible to construct a transient index that would perform better
106245
-** than a full table scan even when the cost of constructing the index
106246
-** is taken into account, then alter the query plan to use the
106247
-** transient index.
106248
-*/
106249
-static void bestAutomaticIndex(WhereBestIdx *p){
106250
- Parse *pParse = p->pParse; /* The parsing context */
106251
- WhereClause *pWC = p->pWC; /* The WHERE clause */
106252
- struct SrcList_item *pSrc = p->pSrc; /* The FROM clause term to search */
106253
- double nTableRow; /* Rows in the input table */
106254
- double logN; /* log(nTableRow) */
106255
- double costTempIdx; /* per-query cost of the transient index */
106256
- WhereTerm *pTerm; /* A single term of the WHERE clause */
106257
- WhereTerm *pWCEnd; /* End of pWC->a[] */
106258
- Table *pTable; /* Table tht might be indexed */
106259
-
106260
- if( pParse->nQueryLoop<=(double)1 ){
106261
- /* There is no point in building an automatic index for a single scan */
106262
- return;
106263
- }
106264
- if( (pParse->db->flags & SQLITE_AutoIndex)==0 ){
106265
- /* Automatic indices are disabled at run-time */
106266
- return;
106267
- }
106268
- if( (p->cost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0
106269
- && (p->cost.plan.wsFlags & WHERE_COVER_SCAN)==0
106270
- ){
106271
- /* We already have some kind of index in use for this query. */
106272
- return;
106273
- }
106274
- if( pSrc->viaCoroutine ){
106275
- /* Cannot index a co-routine */
106276
- return;
106277
- }
106278
- if( pSrc->notIndexed ){
106279
- /* The NOT INDEXED clause appears in the SQL. */
106280
- return;
106281
- }
106282
- if( pSrc->isCorrelated ){
106283
- /* The source is a correlated sub-query. No point in indexing it. */
106284
- return;
106285
- }
106286
-
106287
- assert( pParse->nQueryLoop >= (double)1 );
106288
- pTable = pSrc->pTab;
106289
- nTableRow = pTable->nRowEst;
106290
- logN = estLog(nTableRow);
106291
- costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
106292
- if( costTempIdx>=p->cost.rCost ){
106293
- /* The cost of creating the transient table would be greater than
106294
- ** doing the full table scan */
106295
- return;
106296
- }
106297
-
106298
- /* Search for any equality comparison term */
106299
- pWCEnd = &pWC->a[pWC->nTerm];
106300
- for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
106301
- if( termCanDriveIndex(pTerm, pSrc, p->notReady) ){
106302
- WHERETRACE(("auto-index reduces cost from %.1f to %.1f\n",
106303
- p->cost.rCost, costTempIdx));
106304
- p->cost.rCost = costTempIdx;
106305
- p->cost.plan.nRow = logN + 1;
106306
- p->cost.plan.wsFlags = WHERE_TEMP_INDEX;
106307
- p->cost.used = pTerm->prereqRight;
106308
- break;
106309
- }
106310
- }
106311
-}
106312
-#else
106313
-# define bestAutomaticIndex(A) /* no-op */
106314
-#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
106315
-
106316106301
106317106302
#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
106318106303
/*
106319106304
** Generate code to construct the Index object for an automatic index
106320106305
** and to set up the WhereLevel object pLevel so that the code generator
@@ -106340,10 +106325,11 @@
106340106325
int regRecord; /* Register holding an index record */
106341106326
int n; /* Column counter */
106342106327
int i; /* Loop counter */
106343106328
int mxBitCol; /* Maximum column in pSrc->colUsed */
106344106329
CollSeq *pColl; /* Collating sequence to on a column */
106330
+ WhereLoop *pLoop; /* The Loop object */
106345106331
Bitmask idxCols; /* Bitmap of columns used for indexing */
106346106332
Bitmask extraCols; /* Bitmap of additional columns */
106347106333
106348106334
/* Generate code to skip over the creation and initialization of the
106349106335
** transient index on 2nd and subsequent iterations of the loop. */
@@ -106354,54 +106340,58 @@
106354106340
/* Count the number of columns that will be added to the index
106355106341
** and used to match WHERE clause constraints */
106356106342
nColumn = 0;
106357106343
pTable = pSrc->pTab;
106358106344
pWCEnd = &pWC->a[pWC->nTerm];
106345
+ pLoop = pLevel->pWLoop;
106359106346
idxCols = 0;
106360106347
for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
106361106348
if( termCanDriveIndex(pTerm, pSrc, notReady) ){
106362106349
int iCol = pTerm->u.leftColumn;
106363
- Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
106350
+ Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
106364106351
testcase( iCol==BMS );
106365106352
testcase( iCol==BMS-1 );
106366106353
if( (idxCols & cMask)==0 ){
106367
- nColumn++;
106354
+ if( whereLoopResize(pParse->db, pLoop, nColumn+1) ) return;
106355
+ pLoop->aLTerm[nColumn++] = pTerm;
106368106356
idxCols |= cMask;
106369106357
}
106370106358
}
106371106359
}
106372106360
assert( nColumn>0 );
106373
- pLevel->plan.nEq = nColumn;
106361
+ pLoop->u.btree.nEq = pLoop->nLTerm = nColumn;
106362
+ pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
106363
+ | WHERE_TEMP_INDEX;
106374106364
106375106365
/* Count the number of additional columns needed to create a
106376106366
** covering index. A "covering index" is an index that contains all
106377106367
** columns that are needed by the query. With a covering index, the
106378106368
** original table never needs to be accessed. Automatic indices must
106379106369
** be a covering index because the index will not be updated if the
106380106370
** original table changes and the index and table cannot both be used
106381106371
** if they go out of sync.
106382106372
*/
106383
- extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1)));
106373
+ extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
106384106374
mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
106385106375
testcase( pTable->nCol==BMS-1 );
106386106376
testcase( pTable->nCol==BMS-2 );
106387106377
for(i=0; i<mxBitCol; i++){
106388
- if( extraCols & (((Bitmask)1)<<i) ) nColumn++;
106378
+ if( extraCols & MASKBIT(i) ) nColumn++;
106389106379
}
106390
- if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
106380
+ if( pSrc->colUsed & MASKBIT(BMS-1) ){
106391106381
nColumn += pTable->nCol - BMS + 1;
106392106382
}
106393
- pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;
106383
+ pLoop->wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY;
106394106384
106395106385
/* Construct the Index object to describe this index */
106396106386
nByte = sizeof(Index);
106397106387
nByte += nColumn*sizeof(int); /* Index.aiColumn */
106398106388
nByte += nColumn*sizeof(char*); /* Index.azColl */
106399106389
nByte += nColumn; /* Index.aSortOrder */
106400106390
pIdx = sqlite3DbMallocZero(pParse->db, nByte);
106401106391
if( pIdx==0 ) return;
106402
- pLevel->plan.u.pIdx = pIdx;
106392
+ pLoop->u.btree.pIndex = pIdx;
106403106393
pIdx->azColl = (char**)&pIdx[1];
106404106394
pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
106405106395
pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
106406106396
pIdx->zName = "auto-index";
106407106397
pIdx->nColumn = nColumn;
@@ -106409,11 +106399,13 @@
106409106399
n = 0;
106410106400
idxCols = 0;
106411106401
for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
106412106402
if( termCanDriveIndex(pTerm, pSrc, notReady) ){
106413106403
int iCol = pTerm->u.leftColumn;
106414
- Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
106404
+ Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
106405
+ testcase( iCol==BMS-1 );
106406
+ testcase( iCol==BMS );
106415106407
if( (idxCols & cMask)==0 ){
106416106408
Expr *pX = pTerm->pExpr;
106417106409
idxCols |= cMask;
106418106410
pIdx->aiColumn[n] = pTerm->u.leftColumn;
106419106411
pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
@@ -106420,22 +106412,22 @@
106420106412
pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
106421106413
n++;
106422106414
}
106423106415
}
106424106416
}
106425
- assert( (u32)n==pLevel->plan.nEq );
106417
+ assert( (u32)n==pLoop->u.btree.nEq );
106426106418
106427106419
/* Add additional columns needed to make the automatic index into
106428106420
** a covering index */
106429106421
for(i=0; i<mxBitCol; i++){
106430
- if( extraCols & (((Bitmask)1)<<i) ){
106422
+ if( extraCols & MASKBIT(i) ){
106431106423
pIdx->aiColumn[n] = i;
106432106424
pIdx->azColl[n] = "BINARY";
106433106425
n++;
106434106426
}
106435106427
}
106436
- if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
106428
+ if( pSrc->colUsed & MASKBIT(BMS-1) ){
106437106429
for(i=BMS-1; i<pTable->nCol; i++){
106438106430
pIdx->aiColumn[n] = i;
106439106431
pIdx->azColl[n] = "BINARY";
106440106432
n++;
106441106433
}
@@ -106443,10 +106435,11 @@
106443106435
assert( n==nColumn );
106444106436
106445106437
/* Create the automatic index */
106446106438
pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
106447106439
assert( pLevel->iIdxCur>=0 );
106440
+ pLevel->iIdxCur = pParse->nTab++;
106448106441
sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
106449106442
(char*)pKeyinfo, P4_KEYINFO_HANDOFF);
106450106443
VdbeComment((v, "for %s", pTable->zName));
106451106444
106452106445
/* Fill the automatic index with content */
@@ -106469,26 +106462,25 @@
106469106462
/*
106470106463
** Allocate and populate an sqlite3_index_info structure. It is the
106471106464
** responsibility of the caller to eventually release the structure
106472106465
** by passing the pointer returned by this function to sqlite3_free().
106473106466
*/
106474
-static sqlite3_index_info *allocateIndexInfo(WhereBestIdx *p){
106475
- Parse *pParse = p->pParse;
106476
- WhereClause *pWC = p->pWC;
106477
- struct SrcList_item *pSrc = p->pSrc;
106478
- ExprList *pOrderBy = p->pOrderBy;
106467
+static sqlite3_index_info *allocateIndexInfo(
106468
+ Parse *pParse,
106469
+ WhereClause *pWC,
106470
+ struct SrcList_item *pSrc,
106471
+ ExprList *pOrderBy
106472
+){
106479106473
int i, j;
106480106474
int nTerm;
106481106475
struct sqlite3_index_constraint *pIdxCons;
106482106476
struct sqlite3_index_orderby *pIdxOrderBy;
106483106477
struct sqlite3_index_constraint_usage *pUsage;
106484106478
WhereTerm *pTerm;
106485106479
int nOrderBy;
106486106480
sqlite3_index_info *pIdxInfo;
106487106481
106488
- WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
106489
-
106490106482
/* Count the number of possible WHERE clause constraints referring
106491106483
** to this virtual table */
106492106484
for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
106493106485
if( pTerm->leftCursor != pSrc->iCursor ) continue;
106494106486
assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
@@ -106520,11 +106512,10 @@
106520106512
pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
106521106513
+ (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
106522106514
+ sizeof(*pIdxOrderBy)*nOrderBy );
106523106515
if( pIdxInfo==0 ){
106524106516
sqlite3ErrorMsg(pParse, "out of memory");
106525
- /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
106526106517
return 0;
106527106518
}
106528106519
106529106520
/* Initialize the structure. The sqlite3_index_info structure contains
106530106521
** many fields that are declared "const" to prevent xBestIndex from
@@ -106576,12 +106567,12 @@
106576106567
}
106577106568
106578106569
/*
106579106570
** The table object reference passed as the second argument to this function
106580106571
** must represent a virtual table. This function invokes the xBestIndex()
106581
-** method of the virtual table with the sqlite3_index_info pointer passed
106582
-** as the argument.
106572
+** method of the virtual table with the sqlite3_index_info object that
106573
+** comes in as the 3rd argument to this function.
106583106574
**
106584106575
** If an error occurs, pParse is populated with an error message and a
106585106576
** non-zero value is returned. Otherwise, 0 is returned and the output
106586106577
** part of the sqlite3_index_info structure is left populated.
106587106578
**
@@ -106592,11 +106583,10 @@
106592106583
static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
106593106584
sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
106594106585
int i;
106595106586
int rc;
106596106587
106597
- WHERETRACE(("xBestIndex for %s\n", pTab->zName));
106598106588
TRACE_IDX_INPUTS(p);
106599106589
rc = pVtab->pModule->xBestIndex(pVtab, p);
106600106590
TRACE_IDX_OUTPUTS(p);
106601106591
106602106592
if( rc!=SQLITE_OK ){
@@ -106618,211 +106608,12 @@
106618106608
}
106619106609
}
106620106610
106621106611
return pParse->nErr;
106622106612
}
106623
-
106624
-
106625
-/*
106626
-** Compute the best index for a virtual table.
106627
-**
106628
-** The best index is computed by the xBestIndex method of the virtual
106629
-** table module. This routine is really just a wrapper that sets up
106630
-** the sqlite3_index_info structure that is used to communicate with
106631
-** xBestIndex.
106632
-**
106633
-** In a join, this routine might be called multiple times for the
106634
-** same virtual table. The sqlite3_index_info structure is created
106635
-** and initialized on the first invocation and reused on all subsequent
106636
-** invocations. The sqlite3_index_info structure is also used when
106637
-** code is generated to access the virtual table. The whereInfoDelete()
106638
-** routine takes care of freeing the sqlite3_index_info structure after
106639
-** everybody has finished with it.
106640
-*/
106641
-static void bestVirtualIndex(WhereBestIdx *p){
106642
- Parse *pParse = p->pParse; /* The parsing context */
106643
- WhereClause *pWC = p->pWC; /* The WHERE clause */
106644
- struct SrcList_item *pSrc = p->pSrc; /* The FROM clause term to search */
106645
- Table *pTab = pSrc->pTab;
106646
- sqlite3_index_info *pIdxInfo;
106647
- struct sqlite3_index_constraint *pIdxCons;
106648
- struct sqlite3_index_constraint_usage *pUsage;
106649
- WhereTerm *pTerm;
106650
- int i, j;
106651
- int nOrderBy;
106652
- int bAllowIN; /* Allow IN optimizations */
106653
- double rCost;
106654
-
106655
- /* Make sure wsFlags is initialized to some sane value. Otherwise, if the
106656
- ** malloc in allocateIndexInfo() fails and this function returns leaving
106657
- ** wsFlags in an uninitialized state, the caller may behave unpredictably.
106658
- */
106659
- memset(&p->cost, 0, sizeof(p->cost));
106660
- p->cost.plan.wsFlags = WHERE_VIRTUALTABLE;
106661
-
106662
- /* If the sqlite3_index_info structure has not been previously
106663
- ** allocated and initialized, then allocate and initialize it now.
106664
- */
106665
- pIdxInfo = *p->ppIdxInfo;
106666
- if( pIdxInfo==0 ){
106667
- *p->ppIdxInfo = pIdxInfo = allocateIndexInfo(p);
106668
- }
106669
- if( pIdxInfo==0 ){
106670
- return;
106671
- }
106672
-
106673
- /* At this point, the sqlite3_index_info structure that pIdxInfo points
106674
- ** to will have been initialized, either during the current invocation or
106675
- ** during some prior invocation. Now we just have to customize the
106676
- ** details of pIdxInfo for the current invocation and pass it to
106677
- ** xBestIndex.
106678
- */
106679
-
106680
- /* The module name must be defined. Also, by this point there must
106681
- ** be a pointer to an sqlite3_vtab structure. Otherwise
106682
- ** sqlite3ViewGetColumnNames() would have picked up the error.
106683
- */
106684
- assert( pTab->azModuleArg && pTab->azModuleArg[0] );
106685
- assert( sqlite3GetVTable(pParse->db, pTab) );
106686
-
106687
- /* Try once or twice. On the first attempt, allow IN optimizations.
106688
- ** If an IN optimization is accepted by the virtual table xBestIndex
106689
- ** method, but the pInfo->aConstrainUsage.omit flag is not set, then
106690
- ** the query will not work because it might allow duplicate rows in
106691
- ** output. In that case, run the xBestIndex method a second time
106692
- ** without the IN constraints. Usually this loop only runs once.
106693
- ** The loop will exit using a "break" statement.
106694
- */
106695
- for(bAllowIN=1; 1; bAllowIN--){
106696
- assert( bAllowIN==0 || bAllowIN==1 );
106697
-
106698
- /* Set the aConstraint[].usable fields and initialize all
106699
- ** output variables to zero.
106700
- **
106701
- ** aConstraint[].usable is true for constraints where the right-hand
106702
- ** side contains only references to tables to the left of the current
106703
- ** table. In other words, if the constraint is of the form:
106704
- **
106705
- ** column = expr
106706
- **
106707
- ** and we are evaluating a join, then the constraint on column is
106708
- ** only valid if all tables referenced in expr occur to the left
106709
- ** of the table containing column.
106710
- **
106711
- ** The aConstraints[] array contains entries for all constraints
106712
- ** on the current table. That way we only have to compute it once
106713
- ** even though we might try to pick the best index multiple times.
106714
- ** For each attempt at picking an index, the order of tables in the
106715
- ** join might be different so we have to recompute the usable flag
106716
- ** each time.
106717
- */
106718
- pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
106719
- pUsage = pIdxInfo->aConstraintUsage;
106720
- for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
106721
- j = pIdxCons->iTermOffset;
106722
- pTerm = &pWC->a[j];
106723
- if( (pTerm->prereqRight&p->notReady)==0
106724
- && (bAllowIN || (pTerm->eOperator & WO_IN)==0)
106725
- ){
106726
- pIdxCons->usable = 1;
106727
- }else{
106728
- pIdxCons->usable = 0;
106729
- }
106730
- }
106731
- memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
106732
- if( pIdxInfo->needToFreeIdxStr ){
106733
- sqlite3_free(pIdxInfo->idxStr);
106734
- }
106735
- pIdxInfo->idxStr = 0;
106736
- pIdxInfo->idxNum = 0;
106737
- pIdxInfo->needToFreeIdxStr = 0;
106738
- pIdxInfo->orderByConsumed = 0;
106739
- /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
106740
- pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
106741
- nOrderBy = pIdxInfo->nOrderBy;
106742
- if( !p->pOrderBy ){
106743
- pIdxInfo->nOrderBy = 0;
106744
- }
106745
-
106746
- if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
106747
- return;
106748
- }
106749
-
106750
- pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
106751
- for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
106752
- if( pUsage[i].argvIndex>0 ){
106753
- j = pIdxCons->iTermOffset;
106754
- pTerm = &pWC->a[j];
106755
- p->cost.used |= pTerm->prereqRight;
106756
- if( (pTerm->eOperator & WO_IN)!=0 ){
106757
- if( pUsage[i].omit==0 ){
106758
- /* Do not attempt to use an IN constraint if the virtual table
106759
- ** says that the equivalent EQ constraint cannot be safely omitted.
106760
- ** If we do attempt to use such a constraint, some rows might be
106761
- ** repeated in the output. */
106762
- break;
106763
- }
106764
- /* A virtual table that is constrained by an IN clause may not
106765
- ** consume the ORDER BY clause because (1) the order of IN terms
106766
- ** is not necessarily related to the order of output terms and
106767
- ** (2) Multiple outputs from a single IN value will not merge
106768
- ** together. */
106769
- pIdxInfo->orderByConsumed = 0;
106770
- }
106771
- }
106772
- }
106773
- if( i>=pIdxInfo->nConstraint ) break;
106774
- }
106775
-
106776
- /* The orderByConsumed signal is only valid if all outer loops collectively
106777
- ** generate just a single row of output.
106778
- */
106779
- if( pIdxInfo->orderByConsumed ){
106780
- for(i=0; i<p->i; i++){
106781
- if( (p->aLevel[i].plan.wsFlags & WHERE_UNIQUE)==0 ){
106782
- pIdxInfo->orderByConsumed = 0;
106783
- }
106784
- }
106785
- }
106786
-
106787
- /* If there is an ORDER BY clause, and the selected virtual table index
106788
- ** does not satisfy it, increase the cost of the scan accordingly. This
106789
- ** matches the processing for non-virtual tables in bestBtreeIndex().
106790
- */
106791
- rCost = pIdxInfo->estimatedCost;
106792
- if( p->pOrderBy && pIdxInfo->orderByConsumed==0 ){
106793
- rCost += estLog(rCost)*rCost;
106794
- }
106795
-
106796
- /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
106797
- ** inital value of lowestCost in this loop. If it is, then the
106798
- ** (cost<lowestCost) test below will never be true.
106799
- **
106800
- ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT
106801
- ** is defined.
106802
- */
106803
- if( (SQLITE_BIG_DBL/((double)2))<rCost ){
106804
- p->cost.rCost = (SQLITE_BIG_DBL/((double)2));
106805
- }else{
106806
- p->cost.rCost = rCost;
106807
- }
106808
- p->cost.plan.u.pVtabIdx = pIdxInfo;
106809
- if( pIdxInfo->orderByConsumed ){
106810
- p->cost.plan.wsFlags |= WHERE_ORDERED;
106811
- p->cost.plan.nOBSat = nOrderBy;
106812
- }else{
106813
- p->cost.plan.nOBSat = p->i ? p->aLevel[p->i-1].plan.nOBSat : 0;
106814
- }
106815
- p->cost.plan.nEq = 0;
106816
- pIdxInfo->nOrderBy = nOrderBy;
106817
-
106818
- /* Try to find a more efficient access pattern by using multiple indexes
106819
- ** to optimize an OR expression within the WHERE clause.
106820
- */
106821
- bestOrClauseIndex(p);
106822
-}
106823
-#endif /* SQLITE_OMIT_VIRTUALTABLE */
106613
+#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
106614
+
106824106615
106825106616
#ifdef SQLITE_ENABLE_STAT3
106826106617
/*
106827106618
** Estimate the location of a particular key among all keys in an
106828106619
** index. Store the results in aStat as follows:
@@ -107060,11 +106851,11 @@
107060106851
Parse *pParse, /* Parsing & code generating context */
107061106852
Index *p, /* The index containing the range-compared column; "x" */
107062106853
int nEq, /* index into p->aCol[] of the range-compared column */
107063106854
WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
107064106855
WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
107065
- double *pRangeDiv /* OUT: Reduce search space by this divisor */
106856
+ WhereCost *pRangeDiv /* OUT: Reduce search space by this divisor */
107066106857
){
107067106858
int rc = SQLITE_OK;
107068106859
107069106860
#ifdef SQLITE_ENABLE_STAT3
107070106861
@@ -107098,29 +106889,35 @@
107098106889
if( (pUpper->eOperator & WO_LE)!=0 ) iUpper += a[1];
107099106890
}
107100106891
sqlite3ValueFree(pRangeVal);
107101106892
}
107102106893
if( rc==SQLITE_OK ){
107103
- if( iUpper<=iLower ){
107104
- *pRangeDiv = (double)p->aiRowEst[0];
107105
- }else{
107106
- *pRangeDiv = (double)p->aiRowEst[0]/(double)(iUpper - iLower);
106894
+ WhereCost iBase = whereCost(p->aiRowEst[0]);
106895
+ if( iUpper>iLower ){
106896
+ iBase -= whereCost(iUpper - iLower);
107107106897
}
107108
- WHERETRACE(("range scan regions: %u..%u div=%g\n",
107109
- (u32)iLower, (u32)iUpper, *pRangeDiv));
106898
+ *pRangeDiv = iBase;
106899
+ WHERETRACE(0x100, ("range scan regions: %u..%u div=%d\n",
106900
+ (u32)iLower, (u32)iUpper, *pRangeDiv));
107110106901
return SQLITE_OK;
107111106902
}
107112106903
}
107113106904
#else
107114106905
UNUSED_PARAMETER(pParse);
107115106906
UNUSED_PARAMETER(p);
107116106907
UNUSED_PARAMETER(nEq);
107117106908
#endif
107118106909
assert( pLower || pUpper );
107119
- *pRangeDiv = (double)1;
107120
- if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ) *pRangeDiv *= (double)4;
107121
- if( pUpper ) *pRangeDiv *= (double)4;
106910
+ *pRangeDiv = 0;
106911
+ /* TUNING: Each inequality constraint reduces the search space 4-fold.
106912
+ ** A BETWEEN operator, therefore, reduces the search space 16-fold */
106913
+ if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ){
106914
+ *pRangeDiv += 20; assert( 20==whereCost(4) );
106915
+ }
106916
+ if( pUpper ){
106917
+ *pRangeDiv += 20; assert( 20==whereCost(4) );
106918
+ }
107122106919
return rc;
107123106920
}
107124106921
107125106922
#ifdef SQLITE_ENABLE_STAT3
107126106923
/*
@@ -107142,11 +106939,11 @@
107142106939
*/
107143106940
static int whereEqualScanEst(
107144106941
Parse *pParse, /* Parsing & code generating context */
107145106942
Index *p, /* The index whose left-most column is pTerm */
107146106943
Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
107147
- double *pnRow /* Write the revised row estimate here */
106944
+ tRowcnt *pnRow /* Write the revised row estimate here */
107148106945
){
107149106946
sqlite3_value *pRhs = 0; /* VALUE on right-hand side of pTerm */
107150106947
u8 aff; /* Column affinity */
107151106948
int rc; /* Subfunction return code */
107152106949
tRowcnt a[2]; /* Statistics */
@@ -107161,11 +106958,11 @@
107161106958
pRhs = sqlite3ValueNew(pParse->db);
107162106959
}
107163106960
if( pRhs==0 ) return SQLITE_NOTFOUND;
107164106961
rc = whereKeyStats(pParse, p, pRhs, 0, a);
107165106962
if( rc==SQLITE_OK ){
107166
- WHERETRACE(("equality scan regions: %d\n", (int)a[1]));
106963
+ WHERETRACE(0x100,("equality scan regions: %d\n", (int)a[1]));
107167106964
*pnRow = a[1];
107168106965
}
107169106966
whereEqualScanEst_cancel:
107170106967
sqlite3ValueFree(pRhs);
107171106968
return rc;
@@ -107191,16 +106988,16 @@
107191106988
*/
107192106989
static int whereInScanEst(
107193106990
Parse *pParse, /* Parsing & code generating context */
107194106991
Index *p, /* The index whose left-most column is pTerm */
107195106992
ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
107196
- double *pnRow /* Write the revised row estimate here */
106993
+ tRowcnt *pnRow /* Write the revised row estimate here */
107197106994
){
107198
- int rc = SQLITE_OK; /* Subfunction return code */
107199
- double nEst; /* Number of rows for a single term */
107200
- double nRowEst = (double)0; /* New estimate of the number of rows */
107201
- int i; /* Loop counter */
106995
+ int rc = SQLITE_OK; /* Subfunction return code */
106996
+ tRowcnt nEst; /* Number of rows for a single term */
106997
+ tRowcnt nRowEst = 0; /* New estimate of the number of rows */
106998
+ int i; /* Loop counter */
107202106999
107203107000
assert( p->aSample!=0 );
107204107001
for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
107205107002
nEst = p->aiRowEst[0];
107206107003
rc = whereEqualScanEst(pParse, p, pList->a[i].pExpr, &nEst);
@@ -107207,888 +107004,15 @@
107207107004
nRowEst += nEst;
107208107005
}
107209107006
if( rc==SQLITE_OK ){
107210107007
if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
107211107008
*pnRow = nRowEst;
107212
- WHERETRACE(("IN row estimate: est=%g\n", nRowEst));
107213
- }
107214
- return rc;
107215
-}
107216
-#endif /* defined(SQLITE_ENABLE_STAT3) */
107217
-
107218
-/*
107219
-** Check to see if column iCol of the table with cursor iTab will appear
107220
-** in sorted order according to the current query plan.
107221
-**
107222
-** Return values:
107223
-**
107224
-** 0 iCol is not ordered
107225
-** 1 iCol has only a single value
107226
-** 2 iCol is in ASC order
107227
-** 3 iCol is in DESC order
107228
-*/
107229
-static int isOrderedColumn(
107230
- WhereBestIdx *p,
107231
- int iTab,
107232
- int iCol
107233
-){
107234
- int i, j;
107235
- WhereLevel *pLevel = &p->aLevel[p->i-1];
107236
- Index *pIdx;
107237
- u8 sortOrder;
107238
- for(i=p->i-1; i>=0; i--, pLevel--){
107239
- if( pLevel->iTabCur!=iTab ) continue;
107240
- if( (pLevel->plan.wsFlags & WHERE_ALL_UNIQUE)!=0 ){
107241
- return 1;
107242
- }
107243
- assert( (pLevel->plan.wsFlags & WHERE_ORDERED)!=0 );
107244
- if( (pIdx = pLevel->plan.u.pIdx)!=0 ){
107245
- if( iCol<0 ){
107246
- sortOrder = 0;
107247
- testcase( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 );
107248
- }else{
107249
- int n = pIdx->nColumn;
107250
- for(j=0; j<n; j++){
107251
- if( iCol==pIdx->aiColumn[j] ) break;
107252
- }
107253
- if( j>=n ) return 0;
107254
- sortOrder = pIdx->aSortOrder[j];
107255
- testcase( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 );
107256
- }
107257
- }else{
107258
- if( iCol!=(-1) ) return 0;
107259
- sortOrder = 0;
107260
- testcase( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 );
107261
- }
107262
- if( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 ){
107263
- assert( sortOrder==0 || sortOrder==1 );
107264
- testcase( sortOrder==1 );
107265
- sortOrder = 1 - sortOrder;
107266
- }
107267
- return sortOrder+2;
107268
- }
107269
- return 0;
107270
-}
107271
-
107272
-/*
107273
-** This routine decides if pIdx can be used to satisfy the ORDER BY
107274
-** clause, either in whole or in part. The return value is the
107275
-** cumulative number of terms in the ORDER BY clause that are satisfied
107276
-** by the index pIdx and other indices in outer loops.
107277
-**
107278
-** The table being queried has a cursor number of "base". pIdx is the
107279
-** index that is postulated for use to access the table.
107280
-**
107281
-** The *pbRev value is set to 0 order 1 depending on whether or not
107282
-** pIdx should be run in the forward order or in reverse order.
107283
-*/
107284
-static int isSortingIndex(
107285
- WhereBestIdx *p, /* Best index search context */
107286
- Index *pIdx, /* The index we are testing */
107287
- int base, /* Cursor number for the table to be sorted */
107288
- int *pbRev, /* Set to 1 for reverse-order scan of pIdx */
107289
- int *pbObUnique /* ORDER BY column values will different in every row */
107290
-){
107291
- int i; /* Number of pIdx terms used */
107292
- int j; /* Number of ORDER BY terms satisfied */
107293
- int sortOrder = 2; /* 0: forward. 1: backward. 2: unknown */
107294
- int nTerm; /* Number of ORDER BY terms */
107295
- struct ExprList_item *pOBItem;/* A term of the ORDER BY clause */
107296
- Table *pTab = pIdx->pTable; /* Table that owns index pIdx */
107297
- ExprList *pOrderBy; /* The ORDER BY clause */
107298
- Parse *pParse = p->pParse; /* Parser context */
107299
- sqlite3 *db = pParse->db; /* Database connection */
107300
- int nPriorSat; /* ORDER BY terms satisfied by outer loops */
107301
- int seenRowid = 0; /* True if an ORDER BY rowid term is seen */
107302
- int uniqueNotNull; /* pIdx is UNIQUE with all terms are NOT NULL */
107303
- int outerObUnique; /* Outer loops generate different values in
107304
- ** every row for the ORDER BY columns */
107305
-
107306
- if( p->i==0 ){
107307
- nPriorSat = 0;
107308
- outerObUnique = 1;
107309
- }else{
107310
- u32 wsFlags = p->aLevel[p->i-1].plan.wsFlags;
107311
- nPriorSat = p->aLevel[p->i-1].plan.nOBSat;
107312
- if( (wsFlags & WHERE_ORDERED)==0 ){
107313
- /* This loop cannot be ordered unless the next outer loop is
107314
- ** also ordered */
107315
- return nPriorSat;
107316
- }
107317
- if( OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ){
107318
- /* Only look at the outer-most loop if the OrderByIdxJoin
107319
- ** optimization is disabled */
107320
- return nPriorSat;
107321
- }
107322
- testcase( wsFlags & WHERE_OB_UNIQUE );
107323
- testcase( wsFlags & WHERE_ALL_UNIQUE );
107324
- outerObUnique = (wsFlags & (WHERE_OB_UNIQUE|WHERE_ALL_UNIQUE))!=0;
107325
- }
107326
- pOrderBy = p->pOrderBy;
107327
- assert( pOrderBy!=0 );
107328
- if( pIdx->bUnordered ){
107329
- /* Hash indices (indicated by the "unordered" tag on sqlite_stat1) cannot
107330
- ** be used for sorting */
107331
- return nPriorSat;
107332
- }
107333
- nTerm = pOrderBy->nExpr;
107334
- uniqueNotNull = pIdx->onError!=OE_None;
107335
- assert( nTerm>0 );
107336
-
107337
- /* Argument pIdx must either point to a 'real' named index structure,
107338
- ** or an index structure allocated on the stack by bestBtreeIndex() to
107339
- ** represent the rowid index that is part of every table. */
107340
- assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
107341
-
107342
- /* Match terms of the ORDER BY clause against columns of
107343
- ** the index.
107344
- **
107345
- ** Note that indices have pIdx->nColumn regular columns plus
107346
- ** one additional column containing the rowid. The rowid column
107347
- ** of the index is also allowed to match against the ORDER BY
107348
- ** clause.
107349
- */
107350
- j = nPriorSat;
107351
- for(i=0,pOBItem=&pOrderBy->a[j]; j<nTerm && i<=pIdx->nColumn; i++){
107352
- Expr *pOBExpr; /* The expression of the ORDER BY pOBItem */
107353
- CollSeq *pColl; /* The collating sequence of pOBExpr */
107354
- int termSortOrder; /* Sort order for this term */
107355
- int iColumn; /* The i-th column of the index. -1 for rowid */
107356
- int iSortOrder; /* 1 for DESC, 0 for ASC on the i-th index term */
107357
- int isEq; /* Subject to an == or IS NULL constraint */
107358
- int isMatch; /* ORDER BY term matches the index term */
107359
- const char *zColl; /* Name of collating sequence for i-th index term */
107360
- WhereTerm *pConstraint; /* A constraint in the WHERE clause */
107361
-
107362
- /* If the next term of the ORDER BY clause refers to anything other than
107363
- ** a column in the "base" table, then this index will not be of any
107364
- ** further use in handling the ORDER BY. */
107365
- pOBExpr = sqlite3ExprSkipCollate(pOBItem->pExpr);
107366
- if( pOBExpr->op!=TK_COLUMN || pOBExpr->iTable!=base ){
107367
- break;
107368
- }
107369
-
107370
- /* Find column number and collating sequence for the next entry
107371
- ** in the index */
107372
- if( pIdx->zName && i<pIdx->nColumn ){
107373
- iColumn = pIdx->aiColumn[i];
107374
- if( iColumn==pIdx->pTable->iPKey ){
107375
- iColumn = -1;
107376
- }
107377
- iSortOrder = pIdx->aSortOrder[i];
107378
- zColl = pIdx->azColl[i];
107379
- assert( zColl!=0 );
107380
- }else{
107381
- iColumn = -1;
107382
- iSortOrder = 0;
107383
- zColl = 0;
107384
- }
107385
-
107386
- /* Check to see if the column number and collating sequence of the
107387
- ** index match the column number and collating sequence of the ORDER BY
107388
- ** clause entry. Set isMatch to 1 if they both match. */
107389
- if( pOBExpr->iColumn==iColumn ){
107390
- if( zColl ){
107391
- pColl = sqlite3ExprCollSeq(pParse, pOBItem->pExpr);
107392
- if( !pColl ) pColl = db->pDfltColl;
107393
- isMatch = sqlite3StrICmp(pColl->zName, zColl)==0;
107394
- }else{
107395
- isMatch = 1;
107396
- }
107397
- }else{
107398
- isMatch = 0;
107399
- }
107400
-
107401
- /* termSortOrder is 0 or 1 for whether or not the access loop should
107402
- ** run forward or backwards (respectively) in order to satisfy this
107403
- ** term of the ORDER BY clause. */
107404
- assert( pOBItem->sortOrder==0 || pOBItem->sortOrder==1 );
107405
- assert( iSortOrder==0 || iSortOrder==1 );
107406
- termSortOrder = iSortOrder ^ pOBItem->sortOrder;
107407
-
107408
- /* If X is the column in the index and ORDER BY clause, check to see
107409
- ** if there are any X= or X IS NULL constraints in the WHERE clause. */
107410
- pConstraint = findTerm(p->pWC, base, iColumn, p->notReady,
107411
- WO_EQ|WO_ISNULL|WO_IN, pIdx);
107412
- if( pConstraint==0 ){
107413
- isEq = 0;
107414
- }else if( (pConstraint->eOperator & WO_IN)!=0 ){
107415
- isEq = 0;
107416
- }else if( (pConstraint->eOperator & WO_ISNULL)!=0 ){
107417
- uniqueNotNull = 0;
107418
- isEq = 1; /* "X IS NULL" means X has only a single value */
107419
- }else if( pConstraint->prereqRight==0 ){
107420
- isEq = 1; /* Constraint "X=constant" means X has only a single value */
107421
- }else{
107422
- Expr *pRight = pConstraint->pExpr->pRight;
107423
- if( pRight->op==TK_COLUMN ){
107424
- WHERETRACE((" .. isOrderedColumn(tab=%d,col=%d)",
107425
- pRight->iTable, pRight->iColumn));
107426
- isEq = isOrderedColumn(p, pRight->iTable, pRight->iColumn);
107427
- WHERETRACE((" -> isEq=%d\n", isEq));
107428
-
107429
- /* If the constraint is of the form X=Y where Y is an ordered value
107430
- ** in an outer loop, then make sure the sort order of Y matches the
107431
- ** sort order required for X. */
107432
- if( isMatch && isEq>=2 && isEq!=pOBItem->sortOrder+2 ){
107433
- testcase( isEq==2 );
107434
- testcase( isEq==3 );
107435
- break;
107436
- }
107437
- }else{
107438
- isEq = 0; /* "X=expr" places no ordering constraints on X */
107439
- }
107440
- }
107441
- if( !isMatch ){
107442
- if( isEq==0 ){
107443
- break;
107444
- }else{
107445
- continue;
107446
- }
107447
- }else if( isEq!=1 ){
107448
- if( sortOrder==2 ){
107449
- sortOrder = termSortOrder;
107450
- }else if( termSortOrder!=sortOrder ){
107451
- break;
107452
- }
107453
- }
107454
- j++;
107455
- pOBItem++;
107456
- if( iColumn<0 ){
107457
- seenRowid = 1;
107458
- break;
107459
- }else if( pTab->aCol[iColumn].notNull==0 && isEq!=1 ){
107460
- testcase( isEq==0 );
107461
- testcase( isEq==2 );
107462
- testcase( isEq==3 );
107463
- uniqueNotNull = 0;
107464
- }
107465
- }
107466
- if( seenRowid ){
107467
- uniqueNotNull = 1;
107468
- }else if( uniqueNotNull==0 || i<pIdx->nColumn ){
107469
- uniqueNotNull = 0;
107470
- }
107471
-
107472
- /* If we have not found at least one ORDER BY term that matches the
107473
- ** index, then show no progress. */
107474
- if( pOBItem==&pOrderBy->a[nPriorSat] ) return nPriorSat;
107475
-
107476
- /* Either the outer queries must generate rows where there are no two
107477
- ** rows with the same values in all ORDER BY columns, or else this
107478
- ** loop must generate just a single row of output. Example: Suppose
107479
- ** the outer loops generate A=1 and A=1, and this loop generates B=3
107480
- ** and B=4. Then without the following test, ORDER BY A,B would
107481
- ** generate the wrong order output: 1,3 1,4 1,3 1,4
107482
- */
107483
- if( outerObUnique==0 && uniqueNotNull==0 ) return nPriorSat;
107484
- *pbObUnique = uniqueNotNull;
107485
-
107486
- /* Return the necessary scan order back to the caller */
107487
- *pbRev = sortOrder & 1;
107488
-
107489
- /* If there was an "ORDER BY rowid" term that matched, or it is only
107490
- ** possible for a single row from this table to match, then skip over
107491
- ** any additional ORDER BY terms dealing with this table.
107492
- */
107493
- if( uniqueNotNull ){
107494
- /* Advance j over additional ORDER BY terms associated with base */
107495
- WhereMaskSet *pMS = p->pWC->pMaskSet;
107496
- Bitmask m = ~getMask(pMS, base);
107497
- while( j<nTerm && (exprTableUsage(pMS, pOrderBy->a[j].pExpr)&m)==0 ){
107498
- j++;
107499
- }
107500
- }
107501
- return j;
107502
-}
107503
-
107504
-/*
107505
-** Find the best query plan for accessing a particular table. Write the
107506
-** best query plan and its cost into the p->cost.
107507
-**
107508
-** The lowest cost plan wins. The cost is an estimate of the amount of
107509
-** CPU and disk I/O needed to process the requested result.
107510
-** Factors that influence cost include:
107511
-**
107512
-** * The estimated number of rows that will be retrieved. (The
107513
-** fewer the better.)
107514
-**
107515
-** * Whether or not sorting must occur.
107516
-**
107517
-** * Whether or not there must be separate lookups in the
107518
-** index and in the main table.
107519
-**
107520
-** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
107521
-** the SQL statement, then this function only considers plans using the
107522
-** named index. If no such plan is found, then the returned cost is
107523
-** SQLITE_BIG_DBL. If a plan is found that uses the named index,
107524
-** then the cost is calculated in the usual way.
107525
-**
107526
-** If a NOT INDEXED clause was attached to the table
107527
-** in the SELECT statement, then no indexes are considered. However, the
107528
-** selected plan may still take advantage of the built-in rowid primary key
107529
-** index.
107530
-*/
107531
-static void bestBtreeIndex(WhereBestIdx *p){
107532
- Parse *pParse = p->pParse; /* The parsing context */
107533
- WhereClause *pWC = p->pWC; /* The WHERE clause */
107534
- struct SrcList_item *pSrc = p->pSrc; /* The FROM clause term to search */
107535
- int iCur = pSrc->iCursor; /* The cursor of the table to be accessed */
107536
- Index *pProbe; /* An index we are evaluating */
107537
- Index *pIdx; /* Copy of pProbe, or zero for IPK index */
107538
- int eqTermMask; /* Current mask of valid equality operators */
107539
- int idxEqTermMask; /* Index mask of valid equality operators */
107540
- Index sPk; /* A fake index object for the primary key */
107541
- tRowcnt aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
107542
- int aiColumnPk = -1; /* The aColumn[] value for the sPk index */
107543
- int wsFlagMask; /* Allowed flags in p->cost.plan.wsFlag */
107544
- int nPriorSat; /* ORDER BY terms satisfied by outer loops */
107545
- int nOrderBy; /* Number of ORDER BY terms */
107546
- char bSortInit; /* Initializer for bSort in inner loop */
107547
- char bDistInit; /* Initializer for bDist in inner loop */
107548
-
107549
-
107550
- /* Initialize the cost to a worst-case value */
107551
- memset(&p->cost, 0, sizeof(p->cost));
107552
- p->cost.rCost = SQLITE_BIG_DBL;
107553
-
107554
- /* If the pSrc table is the right table of a LEFT JOIN then we may not
107555
- ** use an index to satisfy IS NULL constraints on that table. This is
107556
- ** because columns might end up being NULL if the table does not match -
107557
- ** a circumstance which the index cannot help us discover. Ticket #2177.
107558
- */
107559
- if( pSrc->jointype & JT_LEFT ){
107560
- idxEqTermMask = WO_EQ|WO_IN;
107561
- }else{
107562
- idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
107563
- }
107564
-
107565
- if( pSrc->pIndex ){
107566
- /* An INDEXED BY clause specifies a particular index to use */
107567
- pIdx = pProbe = pSrc->pIndex;
107568
- wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
107569
- eqTermMask = idxEqTermMask;
107570
- }else{
107571
- /* There is no INDEXED BY clause. Create a fake Index object in local
107572
- ** variable sPk to represent the rowid primary key index. Make this
107573
- ** fake index the first in a chain of Index objects with all of the real
107574
- ** indices to follow */
107575
- Index *pFirst; /* First of real indices on the table */
107576
- memset(&sPk, 0, sizeof(Index));
107577
- sPk.nColumn = 1;
107578
- sPk.aiColumn = &aiColumnPk;
107579
- sPk.aiRowEst = aiRowEstPk;
107580
- sPk.onError = OE_Replace;
107581
- sPk.pTable = pSrc->pTab;
107582
- aiRowEstPk[0] = pSrc->pTab->nRowEst;
107583
- aiRowEstPk[1] = 1;
107584
- pFirst = pSrc->pTab->pIndex;
107585
- if( pSrc->notIndexed==0 ){
107586
- /* The real indices of the table are only considered if the
107587
- ** NOT INDEXED qualifier is omitted from the FROM clause */
107588
- sPk.pNext = pFirst;
107589
- }
107590
- pProbe = &sPk;
107591
- wsFlagMask = ~(
107592
- WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
107593
- );
107594
- eqTermMask = WO_EQ|WO_IN;
107595
- pIdx = 0;
107596
- }
107597
-
107598
- nOrderBy = p->pOrderBy ? p->pOrderBy->nExpr : 0;
107599
- if( p->i ){
107600
- nPriorSat = p->aLevel[p->i-1].plan.nOBSat;
107601
- bSortInit = nPriorSat<nOrderBy;
107602
- bDistInit = 0;
107603
- }else{
107604
- nPriorSat = 0;
107605
- bSortInit = nOrderBy>0;
107606
- bDistInit = p->pDistinct!=0;
107607
- }
107608
-
107609
- /* Loop over all indices looking for the best one to use
107610
- */
107611
- for(; pProbe; pIdx=pProbe=pProbe->pNext){
107612
- const tRowcnt * const aiRowEst = pProbe->aiRowEst;
107613
- WhereCost pc; /* Cost of using pProbe */
107614
- double log10N = (double)1; /* base-10 logarithm of nRow (inexact) */
107615
-
107616
- /* The following variables are populated based on the properties of
107617
- ** index being evaluated. They are then used to determine the expected
107618
- ** cost and number of rows returned.
107619
- **
107620
- ** pc.plan.nEq:
107621
- ** Number of equality terms that can be implemented using the index.
107622
- ** In other words, the number of initial fields in the index that
107623
- ** are used in == or IN or NOT NULL constraints of the WHERE clause.
107624
- **
107625
- ** nInMul:
107626
- ** The "in-multiplier". This is an estimate of how many seek operations
107627
- ** SQLite must perform on the index in question. For example, if the
107628
- ** WHERE clause is:
107629
- **
107630
- ** WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
107631
- **
107632
- ** SQLite must perform 9 lookups on an index on (a, b), so nInMul is
107633
- ** set to 9. Given the same schema and either of the following WHERE
107634
- ** clauses:
107635
- **
107636
- ** WHERE a = 1
107637
- ** WHERE a >= 2
107638
- **
107639
- ** nInMul is set to 1.
107640
- **
107641
- ** If there exists a WHERE term of the form "x IN (SELECT ...)", then
107642
- ** the sub-select is assumed to return 25 rows for the purposes of
107643
- ** determining nInMul.
107644
- **
107645
- ** bInEst:
107646
- ** Set to true if there was at least one "x IN (SELECT ...)" term used
107647
- ** in determining the value of nInMul. Note that the RHS of the
107648
- ** IN operator must be a SELECT, not a value list, for this variable
107649
- ** to be true.
107650
- **
107651
- ** rangeDiv:
107652
- ** An estimate of a divisor by which to reduce the search space due
107653
- ** to inequality constraints. In the absence of sqlite_stat3 ANALYZE
107654
- ** data, a single inequality reduces the search space to 1/4rd its
107655
- ** original size (rangeDiv==4). Two inequalities reduce the search
107656
- ** space to 1/16th of its original size (rangeDiv==16).
107657
- **
107658
- ** bSort:
107659
- ** Boolean. True if there is an ORDER BY clause that will require an
107660
- ** external sort (i.e. scanning the index being evaluated will not
107661
- ** correctly order records).
107662
- **
107663
- ** bDist:
107664
- ** Boolean. True if there is a DISTINCT clause that will require an
107665
- ** external btree.
107666
- **
107667
- ** bLookup:
107668
- ** Boolean. True if a table lookup is required for each index entry
107669
- ** visited. In other words, true if this is not a covering index.
107670
- ** This is always false for the rowid primary key index of a table.
107671
- ** For other indexes, it is true unless all the columns of the table
107672
- ** used by the SELECT statement are present in the index (such an
107673
- ** index is sometimes described as a covering index).
107674
- ** For example, given the index on (a, b), the second of the following
107675
- ** two queries requires table b-tree lookups in order to find the value
107676
- ** of column c, but the first does not because columns a and b are
107677
- ** both available in the index.
107678
- **
107679
- ** SELECT a, b FROM tbl WHERE a = 1;
107680
- ** SELECT a, b, c FROM tbl WHERE a = 1;
107681
- */
107682
- int bInEst = 0; /* True if "x IN (SELECT...)" seen */
107683
- int nInMul = 1; /* Number of distinct equalities to lookup */
107684
- double rangeDiv = (double)1; /* Estimated reduction in search space */
107685
- int nBound = 0; /* Number of range constraints seen */
107686
- char bSort = bSortInit; /* True if external sort required */
107687
- char bDist = bDistInit; /* True if index cannot help with DISTINCT */
107688
- char bLookup = 0; /* True if not a covering index */
107689
- WhereTerm *pTerm; /* A single term of the WHERE clause */
107690
-#ifdef SQLITE_ENABLE_STAT3
107691
- WhereTerm *pFirstTerm = 0; /* First term matching the index */
107692
-#endif
107693
-
107694
- WHERETRACE((
107695
- " %s(%s):\n",
107696
- pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk")
107697
- ));
107698
- memset(&pc, 0, sizeof(pc));
107699
- pc.plan.nOBSat = nPriorSat;
107700
-
107701
- /* Determine the values of pc.plan.nEq and nInMul */
107702
- for(pc.plan.nEq=0; pc.plan.nEq<pProbe->nColumn; pc.plan.nEq++){
107703
- int j = pProbe->aiColumn[pc.plan.nEq];
107704
- pTerm = findTerm(pWC, iCur, j, p->notReady, eqTermMask, pIdx);
107705
- if( pTerm==0 ) break;
107706
- pc.plan.wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
107707
- testcase( pTerm->pWC!=pWC );
107708
- if( pTerm->eOperator & WO_IN ){
107709
- Expr *pExpr = pTerm->pExpr;
107710
- pc.plan.wsFlags |= WHERE_COLUMN_IN;
107711
- if( ExprHasProperty(pExpr, EP_xIsSelect) ){
107712
- /* "x IN (SELECT ...)": Assume the SELECT returns 25 rows */
107713
- nInMul *= 25;
107714
- bInEst = 1;
107715
- }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
107716
- /* "x IN (value, value, ...)" */
107717
- nInMul *= pExpr->x.pList->nExpr;
107718
- }
107719
- }else if( pTerm->eOperator & WO_ISNULL ){
107720
- pc.plan.wsFlags |= WHERE_COLUMN_NULL;
107721
- }
107722
-#ifdef SQLITE_ENABLE_STAT3
107723
- if( pc.plan.nEq==0 && pProbe->aSample ) pFirstTerm = pTerm;
107724
-#endif
107725
- pc.used |= pTerm->prereqRight;
107726
- }
107727
-
107728
- /* If the index being considered is UNIQUE, and there is an equality
107729
- ** constraint for all columns in the index, then this search will find
107730
- ** at most a single row. In this case set the WHERE_UNIQUE flag to
107731
- ** indicate this to the caller.
107732
- **
107733
- ** Otherwise, if the search may find more than one row, test to see if
107734
- ** there is a range constraint on indexed column (pc.plan.nEq+1) that
107735
- ** can be optimized using the index.
107736
- */
107737
- if( pc.plan.nEq==pProbe->nColumn && pProbe->onError!=OE_None ){
107738
- testcase( pc.plan.wsFlags & WHERE_COLUMN_IN );
107739
- testcase( pc.plan.wsFlags & WHERE_COLUMN_NULL );
107740
- if( (pc.plan.wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
107741
- pc.plan.wsFlags |= WHERE_UNIQUE;
107742
- if( p->i==0 || (p->aLevel[p->i-1].plan.wsFlags & WHERE_ALL_UNIQUE)!=0 ){
107743
- pc.plan.wsFlags |= WHERE_ALL_UNIQUE;
107744
- }
107745
- }
107746
- }else if( pProbe->bUnordered==0 ){
107747
- int j;
107748
- j = (pc.plan.nEq==pProbe->nColumn ? -1 : pProbe->aiColumn[pc.plan.nEq]);
107749
- if( findTerm(pWC, iCur, j, p->notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
107750
- WhereTerm *pTop, *pBtm;
107751
- pTop = findTerm(pWC, iCur, j, p->notReady, WO_LT|WO_LE, pIdx);
107752
- pBtm = findTerm(pWC, iCur, j, p->notReady, WO_GT|WO_GE, pIdx);
107753
- whereRangeScanEst(pParse, pProbe, pc.plan.nEq, pBtm, pTop, &rangeDiv);
107754
- if( pTop ){
107755
- nBound = 1;
107756
- pc.plan.wsFlags |= WHERE_TOP_LIMIT;
107757
- pc.used |= pTop->prereqRight;
107758
- testcase( pTop->pWC!=pWC );
107759
- }
107760
- if( pBtm ){
107761
- nBound++;
107762
- pc.plan.wsFlags |= WHERE_BTM_LIMIT;
107763
- pc.used |= pBtm->prereqRight;
107764
- testcase( pBtm->pWC!=pWC );
107765
- }
107766
- pc.plan.wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
107767
- }
107768
- }
107769
-
107770
- /* If there is an ORDER BY clause and the index being considered will
107771
- ** naturally scan rows in the required order, set the appropriate flags
107772
- ** in pc.plan.wsFlags. Otherwise, if there is an ORDER BY clause but
107773
- ** the index will scan rows in a different order, set the bSort
107774
- ** variable. */
107775
- if( bSort && (pSrc->jointype & JT_LEFT)==0 ){
107776
- int bRev = 2;
107777
- int bObUnique = 0;
107778
- WHERETRACE((" --> before isSortIndex: nPriorSat=%d\n",nPriorSat));
107779
- pc.plan.nOBSat = isSortingIndex(p, pProbe, iCur, &bRev, &bObUnique);
107780
- WHERETRACE((" --> after isSortIndex: bRev=%d bObU=%d nOBSat=%d\n",
107781
- bRev, bObUnique, pc.plan.nOBSat));
107782
- if( nPriorSat<pc.plan.nOBSat || (pc.plan.wsFlags & WHERE_ALL_UNIQUE)!=0 ){
107783
- pc.plan.wsFlags |= WHERE_ORDERED;
107784
- if( bObUnique ) pc.plan.wsFlags |= WHERE_OB_UNIQUE;
107785
- }
107786
- if( nOrderBy==pc.plan.nOBSat ){
107787
- bSort = 0;
107788
- pc.plan.wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE;
107789
- }
107790
- if( bRev & 1 ) pc.plan.wsFlags |= WHERE_REVERSE;
107791
- }
107792
-
107793
- /* If there is a DISTINCT qualifier and this index will scan rows in
107794
- ** order of the DISTINCT expressions, clear bDist and set the appropriate
107795
- ** flags in pc.plan.wsFlags. */
107796
- if( bDist
107797
- && isDistinctIndex(pParse, pWC, pProbe, iCur, p->pDistinct, pc.plan.nEq)
107798
- && (pc.plan.wsFlags & WHERE_COLUMN_IN)==0
107799
- ){
107800
- bDist = 0;
107801
- pc.plan.wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_DISTINCT;
107802
- }
107803
-
107804
- /* If currently calculating the cost of using an index (not the IPK
107805
- ** index), determine if all required column data may be obtained without
107806
- ** using the main table (i.e. if the index is a covering
107807
- ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
107808
- ** pc.plan.wsFlags. Otherwise, set the bLookup variable to true. */
107809
- if( pIdx ){
107810
- Bitmask m = pSrc->colUsed;
107811
- int j;
107812
- for(j=0; j<pIdx->nColumn; j++){
107813
- int x = pIdx->aiColumn[j];
107814
- if( x<BMS-1 ){
107815
- m &= ~(((Bitmask)1)<<x);
107816
- }
107817
- }
107818
- if( m==0 ){
107819
- pc.plan.wsFlags |= WHERE_IDX_ONLY;
107820
- }else{
107821
- bLookup = 1;
107822
- }
107823
- }
107824
-
107825
- /*
107826
- ** Estimate the number of rows of output. For an "x IN (SELECT...)"
107827
- ** constraint, do not let the estimate exceed half the rows in the table.
107828
- */
107829
- pc.plan.nRow = (double)(aiRowEst[pc.plan.nEq] * nInMul);
107830
- if( bInEst && pc.plan.nRow*2>aiRowEst[0] ){
107831
- pc.plan.nRow = aiRowEst[0]/2;
107832
- nInMul = (int)(pc.plan.nRow / aiRowEst[pc.plan.nEq]);
107833
- }
107834
-
107835
-#ifdef SQLITE_ENABLE_STAT3
107836
- /* If the constraint is of the form x=VALUE or x IN (E1,E2,...)
107837
- ** and we do not think that values of x are unique and if histogram
107838
- ** data is available for column x, then it might be possible
107839
- ** to get a better estimate on the number of rows based on
107840
- ** VALUE and how common that value is according to the histogram.
107841
- */
107842
- if( pc.plan.nRow>(double)1 && pc.plan.nEq==1
107843
- && pFirstTerm!=0 && aiRowEst[1]>1 ){
107844
- assert( (pFirstTerm->eOperator & (WO_EQ|WO_ISNULL|WO_IN))!=0 );
107845
- if( pFirstTerm->eOperator & (WO_EQ|WO_ISNULL) ){
107846
- testcase( pFirstTerm->eOperator & WO_EQ );
107847
- testcase( pFirstTerm->eOperator & WO_EQUIV );
107848
- testcase( pFirstTerm->eOperator & WO_ISNULL );
107849
- whereEqualScanEst(pParse, pProbe, pFirstTerm->pExpr->pRight,
107850
- &pc.plan.nRow);
107851
- }else if( bInEst==0 ){
107852
- assert( pFirstTerm->eOperator & WO_IN );
107853
- whereInScanEst(pParse, pProbe, pFirstTerm->pExpr->x.pList,
107854
- &pc.plan.nRow);
107855
- }
107856
- }
107857
-#endif /* SQLITE_ENABLE_STAT3 */
107858
-
107859
- /* Adjust the number of output rows and downward to reflect rows
107860
- ** that are excluded by range constraints.
107861
- */
107862
- pc.plan.nRow = pc.plan.nRow/rangeDiv;
107863
- if( pc.plan.nRow<1 ) pc.plan.nRow = 1;
107864
-
107865
- /* Experiments run on real SQLite databases show that the time needed
107866
- ** to do a binary search to locate a row in a table or index is roughly
107867
- ** log10(N) times the time to move from one row to the next row within
107868
- ** a table or index. The actual times can vary, with the size of
107869
- ** records being an important factor. Both moves and searches are
107870
- ** slower with larger records, presumably because fewer records fit
107871
- ** on one page and hence more pages have to be fetched.
107872
- **
107873
- ** The ANALYZE command and the sqlite_stat1 and sqlite_stat3 tables do
107874
- ** not give us data on the relative sizes of table and index records.
107875
- ** So this computation assumes table records are about twice as big
107876
- ** as index records
107877
- */
107878
- if( (pc.plan.wsFlags&~(WHERE_REVERSE|WHERE_ORDERED|WHERE_OB_UNIQUE))
107879
- ==WHERE_IDX_ONLY
107880
- && (pWC->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
107881
- && sqlite3GlobalConfig.bUseCis
107882
- && OptimizationEnabled(pParse->db, SQLITE_CoverIdxScan)
107883
- ){
107884
- /* This index is not useful for indexing, but it is a covering index.
107885
- ** A full-scan of the index might be a little faster than a full-scan
107886
- ** of the table, so give this case a cost slightly less than a table
107887
- ** scan. */
107888
- pc.rCost = aiRowEst[0]*3 + pProbe->nColumn;
107889
- pc.plan.wsFlags |= WHERE_COVER_SCAN|WHERE_COLUMN_RANGE;
107890
- }else if( (pc.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
107891
- /* The cost of a full table scan is a number of move operations equal
107892
- ** to the number of rows in the table.
107893
- **
107894
- ** We add an additional 4x penalty to full table scans. This causes
107895
- ** the cost function to err on the side of choosing an index over
107896
- ** choosing a full scan. This 4x full-scan penalty is an arguable
107897
- ** decision and one which we expect to revisit in the future. But
107898
- ** it seems to be working well enough at the moment.
107899
- */
107900
- pc.rCost = aiRowEst[0]*4;
107901
- pc.plan.wsFlags &= ~WHERE_IDX_ONLY;
107902
- if( pIdx ){
107903
- pc.plan.wsFlags &= ~WHERE_ORDERED;
107904
- pc.plan.nOBSat = nPriorSat;
107905
- }
107906
- }else{
107907
- log10N = estLog(aiRowEst[0]);
107908
- pc.rCost = pc.plan.nRow;
107909
- if( pIdx ){
107910
- if( bLookup ){
107911
- /* For an index lookup followed by a table lookup:
107912
- ** nInMul index searches to find the start of each index range
107913
- ** + nRow steps through the index
107914
- ** + nRow table searches to lookup the table entry using the rowid
107915
- */
107916
- pc.rCost += (nInMul + pc.plan.nRow)*log10N;
107917
- }else{
107918
- /* For a covering index:
107919
- ** nInMul index searches to find the initial entry
107920
- ** + nRow steps through the index
107921
- */
107922
- pc.rCost += nInMul*log10N;
107923
- }
107924
- }else{
107925
- /* For a rowid primary key lookup:
107926
- ** nInMult table searches to find the initial entry for each range
107927
- ** + nRow steps through the table
107928
- */
107929
- pc.rCost += nInMul*log10N;
107930
- }
107931
- }
107932
-
107933
- /* Add in the estimated cost of sorting the result. Actual experimental
107934
- ** measurements of sorting performance in SQLite show that sorting time
107935
- ** adds C*N*log10(N) to the cost, where N is the number of rows to be
107936
- ** sorted and C is a factor between 1.95 and 4.3. We will split the
107937
- ** difference and select C of 3.0.
107938
- */
107939
- if( bSort ){
107940
- double m = estLog(pc.plan.nRow*(nOrderBy - pc.plan.nOBSat)/nOrderBy);
107941
- m *= (double)(pc.plan.nOBSat ? 2 : 3);
107942
- pc.rCost += pc.plan.nRow*m;
107943
- }
107944
- if( bDist ){
107945
- pc.rCost += pc.plan.nRow*estLog(pc.plan.nRow)*3;
107946
- }
107947
-
107948
- /**** Cost of using this index has now been computed ****/
107949
-
107950
- /* If there are additional constraints on this table that cannot
107951
- ** be used with the current index, but which might lower the number
107952
- ** of output rows, adjust the nRow value accordingly. This only
107953
- ** matters if the current index is the least costly, so do not bother
107954
- ** with this step if we already know this index will not be chosen.
107955
- ** Also, never reduce the output row count below 2 using this step.
107956
- **
107957
- ** It is critical that the notValid mask be used here instead of
107958
- ** the notReady mask. When computing an "optimal" index, the notReady
107959
- ** mask will only have one bit set - the bit for the current table.
107960
- ** The notValid mask, on the other hand, always has all bits set for
107961
- ** tables that are not in outer loops. If notReady is used here instead
107962
- ** of notValid, then a optimal index that depends on inner joins loops
107963
- ** might be selected even when there exists an optimal index that has
107964
- ** no such dependency.
107965
- */
107966
- if( pc.plan.nRow>2 && pc.rCost<=p->cost.rCost ){
107967
- int k; /* Loop counter */
107968
- int nSkipEq = pc.plan.nEq; /* Number of == constraints to skip */
107969
- int nSkipRange = nBound; /* Number of < constraints to skip */
107970
- Bitmask thisTab; /* Bitmap for pSrc */
107971
-
107972
- thisTab = getMask(pWC->pMaskSet, iCur);
107973
- for(pTerm=pWC->a, k=pWC->nTerm; pc.plan.nRow>2 && k; k--, pTerm++){
107974
- if( pTerm->wtFlags & TERM_VIRTUAL ) continue;
107975
- if( (pTerm->prereqAll & p->notValid)!=thisTab ) continue;
107976
- if( pTerm->eOperator & (WO_EQ|WO_IN|WO_ISNULL) ){
107977
- if( nSkipEq ){
107978
- /* Ignore the first pc.plan.nEq equality matches since the index
107979
- ** has already accounted for these */
107980
- nSkipEq--;
107981
- }else{
107982
- /* Assume each additional equality match reduces the result
107983
- ** set size by a factor of 10 */
107984
- pc.plan.nRow /= 10;
107985
- }
107986
- }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GT|WO_GE) ){
107987
- if( nSkipRange ){
107988
- /* Ignore the first nSkipRange range constraints since the index
107989
- ** has already accounted for these */
107990
- nSkipRange--;
107991
- }else{
107992
- /* Assume each additional range constraint reduces the result
107993
- ** set size by a factor of 3. Indexed range constraints reduce
107994
- ** the search space by a larger factor: 4. We make indexed range
107995
- ** more selective intentionally because of the subjective
107996
- ** observation that indexed range constraints really are more
107997
- ** selective in practice, on average. */
107998
- pc.plan.nRow /= 3;
107999
- }
108000
- }else if( (pTerm->eOperator & WO_NOOP)==0 ){
108001
- /* Any other expression lowers the output row count by half */
108002
- pc.plan.nRow /= 2;
108003
- }
108004
- }
108005
- if( pc.plan.nRow<2 ) pc.plan.nRow = 2;
108006
- }
108007
-
108008
-
108009
- WHERETRACE((
108010
- " nEq=%d nInMul=%d rangeDiv=%d bSort=%d bLookup=%d wsFlags=0x%08x\n"
108011
- " notReady=0x%llx log10N=%.1f nRow=%.1f cost=%.1f\n"
108012
- " used=0x%llx nOBSat=%d\n",
108013
- pc.plan.nEq, nInMul, (int)rangeDiv, bSort, bLookup, pc.plan.wsFlags,
108014
- p->notReady, log10N, pc.plan.nRow, pc.rCost, pc.used,
108015
- pc.plan.nOBSat
108016
- ));
108017
-
108018
- /* If this index is the best we have seen so far, then record this
108019
- ** index and its cost in the p->cost structure.
108020
- */
108021
- if( (!pIdx || pc.plan.wsFlags) && compareCost(&pc, &p->cost) ){
108022
- p->cost = pc;
108023
- p->cost.plan.wsFlags &= wsFlagMask;
108024
- p->cost.plan.u.pIdx = pIdx;
108025
- }
108026
-
108027
- /* If there was an INDEXED BY clause, then only that one index is
108028
- ** considered. */
108029
- if( pSrc->pIndex ) break;
108030
-
108031
- /* Reset masks for the next index in the loop */
108032
- wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
108033
- eqTermMask = idxEqTermMask;
108034
- }
108035
-
108036
- /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
108037
- ** is set, then reverse the order that the index will be scanned
108038
- ** in. This is used for application testing, to help find cases
108039
- ** where application behavior depends on the (undefined) order that
108040
- ** SQLite outputs rows in in the absence of an ORDER BY clause. */
108041
- if( !p->pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
108042
- p->cost.plan.wsFlags |= WHERE_REVERSE;
108043
- }
108044
-
108045
- assert( p->pOrderBy || (p->cost.plan.wsFlags&WHERE_ORDERED)==0 );
108046
- assert( p->cost.plan.u.pIdx==0 || (p->cost.plan.wsFlags&WHERE_ROWID_EQ)==0 );
108047
- assert( pSrc->pIndex==0
108048
- || p->cost.plan.u.pIdx==0
108049
- || p->cost.plan.u.pIdx==pSrc->pIndex
108050
- );
108051
-
108052
- WHERETRACE((" best index is %s cost=%.1f\n",
108053
- p->cost.plan.u.pIdx ? p->cost.plan.u.pIdx->zName : "ipk",
108054
- p->cost.rCost));
108055
-
108056
- bestOrClauseIndex(p);
108057
- bestAutomaticIndex(p);
108058
- p->cost.plan.wsFlags |= eqTermMask;
108059
-}
108060
-
108061
-/*
108062
-** Find the query plan for accessing table pSrc->pTab. Write the
108063
-** best query plan and its cost into the WhereCost object supplied
108064
-** as the last parameter. This function may calculate the cost of
108065
-** both real and virtual table scans.
108066
-**
108067
-** This function does not take ORDER BY or DISTINCT into account. Nor
108068
-** does it remember the virtual table query plan. All it does is compute
108069
-** the cost while determining if an OR optimization is applicable. The
108070
-** details will be reconsidered later if the optimization is found to be
108071
-** applicable.
108072
-*/
108073
-static void bestIndex(WhereBestIdx *p){
108074
-#ifndef SQLITE_OMIT_VIRTUALTABLE
108075
- if( IsVirtual(p->pSrc->pTab) ){
108076
- sqlite3_index_info *pIdxInfo = 0;
108077
- p->ppIdxInfo = &pIdxInfo;
108078
- bestVirtualIndex(p);
108079
- assert( pIdxInfo!=0 || p->pParse->db->mallocFailed );
108080
- if( pIdxInfo && pIdxInfo->needToFreeIdxStr ){
108081
- sqlite3_free(pIdxInfo->idxStr);
108082
- }
108083
- sqlite3DbFree(p->pParse->db, pIdxInfo);
108084
- }else
108085
-#endif
108086
- {
108087
- bestBtreeIndex(p);
108088
- }
108089
-}
107009
+ WHERETRACE(0x100,("IN row estimate: est=%g\n", nRowEst));
107010
+ }
107011
+ return rc;
107012
+}
107013
+#endif /* defined(SQLITE_ENABLE_STAT3) */
108090107014
108091107015
/*
108092107016
** Disable a term in the WHERE clause. Except, do not disable the term
108093107017
** if it controls a LEFT OUTER JOIN and it did not originate in the ON
108094107018
** or USING clause of that join.
@@ -108183,10 +107107,11 @@
108183107107
static int codeEqualityTerm(
108184107108
Parse *pParse, /* The parsing context */
108185107109
WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
108186107110
WhereLevel *pLevel, /* The level of the FROM clause we are working on */
108187107111
int iEq, /* Index of the equality term within this level */
107112
+ int bRev, /* True for reverse-order IN operations */
108188107113
int iTarget /* Attempt to leave results in this register */
108189107114
){
108190107115
Expr *pX = pTerm->pExpr;
108191107116
Vdbe *v = pParse->pVdbe;
108192107117
int iReg; /* Register holding results */
@@ -108200,18 +107125,17 @@
108200107125
#ifndef SQLITE_OMIT_SUBQUERY
108201107126
}else{
108202107127
int eType;
108203107128
int iTab;
108204107129
struct InLoop *pIn;
108205
- u8 bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
107130
+ WhereLoop *pLoop = pLevel->pWLoop;
108206107131
108207
- if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0
108208
- && pLevel->plan.u.pIdx->aSortOrder[iEq]
107132
+ if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
107133
+ && pLoop->u.btree.pIndex!=0
107134
+ && pLoop->u.btree.pIndex->aSortOrder[iEq]
108209107135
){
108210107136
testcase( iEq==0 );
108211
- testcase( iEq==pLevel->plan.u.pIdx->nColumn-1 );
108212
- testcase( iEq>0 && iEq+1<pLevel->plan.u.pIdx->nColumn );
108213107137
testcase( bRev );
108214107138
bRev = !bRev;
108215107139
}
108216107140
assert( pX->op==TK_IN );
108217107141
iReg = iTarget;
@@ -108220,11 +107144,12 @@
108220107144
testcase( bRev );
108221107145
bRev = !bRev;
108222107146
}
108223107147
iTab = pX->iTable;
108224107148
sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
108225
- assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
107149
+ assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
107150
+ pLoop->wsFlags |= WHERE_IN_ABLE;
108226107151
if( pLevel->u.in.nIn==0 ){
108227107152
pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
108228107153
}
108229107154
pLevel->u.in.nIn++;
108230107155
pLevel->u.in.aInLoop =
@@ -108290,33 +107215,35 @@
108290107215
** string in this example would be set to SQLITE_AFF_NONE.
108291107216
*/
108292107217
static int codeAllEqualityTerms(
108293107218
Parse *pParse, /* Parsing context */
108294107219
WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
108295
- WhereClause *pWC, /* The WHERE clause */
108296
- Bitmask notReady, /* Which parts of FROM have not yet been coded */
107220
+ int bRev, /* Reverse the order of IN operators */
108297107221
int nExtraReg, /* Number of extra registers to allocate */
108298107222
char **pzAff /* OUT: Set to point to affinity string */
108299107223
){
108300
- int nEq = pLevel->plan.nEq; /* The number of == or IN constraints to code */
107224
+ int nEq; /* The number of == or IN constraints to code */
108301107225
Vdbe *v = pParse->pVdbe; /* The vm under construction */
108302107226
Index *pIdx; /* The index being used for this loop */
108303
- int iCur = pLevel->iTabCur; /* The cursor of the table */
108304107227
WhereTerm *pTerm; /* A single constraint term */
107228
+ WhereLoop *pLoop; /* The WhereLoop object */
108305107229
int j; /* Loop counter */
108306107230
int regBase; /* Base register */
108307107231
int nReg; /* Number of registers to allocate */
108308107232
char *zAff; /* Affinity string to return */
108309107233
108310107234
/* This module is only called on query plans that use an index. */
108311
- assert( pLevel->plan.wsFlags & WHERE_INDEXED );
108312
- pIdx = pLevel->plan.u.pIdx;
107235
+ pLoop = pLevel->pWLoop;
107236
+ assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
107237
+ nEq = pLoop->u.btree.nEq;
107238
+ pIdx = pLoop->u.btree.pIndex;
107239
+ assert( pIdx!=0 );
108313107240
108314107241
/* Figure out how many memory cells we will need then allocate them.
108315107242
*/
108316107243
regBase = pParse->nMem + 1;
108317
- nReg = pLevel->plan.nEq + nExtraReg;
107244
+ nReg = pLoop->u.btree.nEq + nExtraReg;
108318107245
pParse->nMem += nReg;
108319107246
108320107247
zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
108321107248
if( !zAff ){
108322107249
pParse->db->mallocFailed = 1;
@@ -108325,18 +107252,17 @@
108325107252
/* Evaluate the equality constraints
108326107253
*/
108327107254
assert( pIdx->nColumn>=nEq );
108328107255
for(j=0; j<nEq; j++){
108329107256
int r1;
108330
- int k = pIdx->aiColumn[j];
108331
- pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
108332
- if( pTerm==0 ) break;
107257
+ pTerm = pLoop->aLTerm[j];
107258
+ assert( pTerm!=0 );
108333107259
/* The following true for indices with redundant columns.
108334107260
** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
108335107261
testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
108336107262
testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
108337
- r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, regBase+j);
107263
+ r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
108338107264
if( r1!=regBase+j ){
108339107265
if( nReg==1 ){
108340107266
sqlite3ReleaseTempReg(pParse, regBase);
108341107267
regBase = r1;
108342107268
}else{
@@ -108400,20 +107326,19 @@
108400107326
**
108401107327
** The returned pointer points to memory obtained from sqlite3DbMalloc().
108402107328
** It is the responsibility of the caller to free the buffer when it is
108403107329
** no longer required.
108404107330
*/
108405
-static char *explainIndexRange(sqlite3 *db, WhereLevel *pLevel, Table *pTab){
108406
- WherePlan *pPlan = &pLevel->plan;
108407
- Index *pIndex = pPlan->u.pIdx;
108408
- int nEq = pPlan->nEq;
107331
+static char *explainIndexRange(sqlite3 *db, WhereLoop *pLoop, Table *pTab){
107332
+ Index *pIndex = pLoop->u.btree.pIndex;
107333
+ int nEq = pLoop->u.btree.nEq;
108409107334
int i, j;
108410107335
Column *aCol = pTab->aCol;
108411107336
int *aiColumn = pIndex->aiColumn;
108412107337
StrAccum txt;
108413107338
108414
- if( nEq==0 && (pPlan->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
107339
+ if( nEq==0 && (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
108415107340
return 0;
108416107341
}
108417107342
sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
108418107343
txt.db = db;
108419107344
sqlite3StrAccumAppend(&txt, " (", 2);
@@ -108420,15 +107345,15 @@
108420107345
for(i=0; i<nEq; i++){
108421107346
explainAppendTerm(&txt, i, aCol[aiColumn[i]].zName, "=");
108422107347
}
108423107348
108424107349
j = i;
108425
- if( pPlan->wsFlags&WHERE_BTM_LIMIT ){
107350
+ if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
108426107351
char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
108427107352
explainAppendTerm(&txt, i++, z, ">");
108428107353
}
108429
- if( pPlan->wsFlags&WHERE_TOP_LIMIT ){
107354
+ if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
108430107355
char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
108431107356
explainAppendTerm(&txt, i, z, "<");
108432107357
}
108433107358
sqlite3StrAccumAppend(&txt, ")", 1);
108434107359
return sqlite3StrAccumFinish(&txt);
@@ -108447,24 +107372,26 @@
108447107372
int iLevel, /* Value for "level" column of output */
108448107373
int iFrom, /* Value for "from" column of output */
108449107374
u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
108450107375
){
108451107376
if( pParse->explain==2 ){
108452
- u32 flags = pLevel->plan.wsFlags;
108453107377
struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
108454107378
Vdbe *v = pParse->pVdbe; /* VM being constructed */
108455107379
sqlite3 *db = pParse->db; /* Database handle */
108456107380
char *zMsg; /* Text to add to EQP output */
108457
- sqlite3_int64 nRow; /* Expected number of rows visited by scan */
108458107381
int iId = pParse->iSelectId; /* Select id (left-most output column) */
108459107382
int isSearch; /* True for a SEARCH. False for SCAN. */
107383
+ WhereLoop *pLoop; /* The controlling WhereLoop object */
107384
+ u32 flags; /* Flags that describe this loop */
108460107385
107386
+ pLoop = pLevel->pWLoop;
107387
+ flags = pLoop->wsFlags;
108461107388
if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
108462107389
108463
- isSearch = (pLevel->plan.nEq>0)
108464
- || (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
108465
- || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
107390
+ isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
107391
+ || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
107392
+ || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
108466107393
108467107394
zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
108468107395
if( pItem->pSelect ){
108469107396
zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
108470107397
}else{
@@ -108472,47 +107399,42 @@
108472107399
}
108473107400
108474107401
if( pItem->zAlias ){
108475107402
zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
108476107403
}
108477
- if( (flags & WHERE_INDEXED)!=0 ){
108478
- char *zWhere = explainIndexRange(db, pLevel, pItem->pTab);
107404
+ if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0
107405
+ && ALWAYS(pLoop->u.btree.pIndex!=0)
107406
+ ){
107407
+ char *zWhere = explainIndexRange(db, pLoop, pItem->pTab);
108479107408
zMsg = sqlite3MAppendf(db, zMsg, "%s USING %s%sINDEX%s%s%s", zMsg,
108480107409
((flags & WHERE_TEMP_INDEX)?"AUTOMATIC ":""),
108481107410
((flags & WHERE_IDX_ONLY)?"COVERING ":""),
108482107411
((flags & WHERE_TEMP_INDEX)?"":" "),
108483
- ((flags & WHERE_TEMP_INDEX)?"": pLevel->plan.u.pIdx->zName),
107412
+ ((flags & WHERE_TEMP_INDEX)?"": pLoop->u.btree.pIndex->zName),
108484107413
zWhere
108485107414
);
108486107415
sqlite3DbFree(db, zWhere);
108487
- }else if( flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
107416
+ }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
108488107417
zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
108489107418
108490
- if( flags&WHERE_ROWID_EQ ){
107419
+ if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
108491107420
zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
108492107421
}else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
108493107422
zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
108494107423
}else if( flags&WHERE_BTM_LIMIT ){
108495107424
zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
108496
- }else if( flags&WHERE_TOP_LIMIT ){
107425
+ }else if( ALWAYS(flags&WHERE_TOP_LIMIT) ){
108497107426
zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
108498107427
}
108499107428
}
108500107429
#ifndef SQLITE_OMIT_VIRTUALTABLE
108501107430
else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
108502
- sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
108503107431
zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
108504
- pVtabIdx->idxNum, pVtabIdx->idxStr);
107432
+ pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
108505107433
}
108506107434
#endif
108507
- if( wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) ){
108508
- testcase( wctrlFlags & WHERE_ORDERBY_MIN );
108509
- nRow = 1;
108510
- }else{
108511
- nRow = (sqlite3_int64)pLevel->plan.nRow;
108512
- }
108513
- zMsg = sqlite3MAppendf(db, zMsg, "%s (~%lld rows)", zMsg, nRow);
107435
+ zMsg = sqlite3MAppendf(db, zMsg, "%s", zMsg);
108514107436
sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
108515107437
}
108516107438
}
108517107439
#else
108518107440
# define explainOneScan(u,v,w,x,y,z)
@@ -108524,19 +107446,19 @@
108524107446
** implementation described by pWInfo.
108525107447
*/
108526107448
static Bitmask codeOneLoopStart(
108527107449
WhereInfo *pWInfo, /* Complete information about the WHERE clause */
108528107450
int iLevel, /* Which level of pWInfo->a[] should be coded */
108529
- u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
108530107451
Bitmask notReady /* Which tables are currently available */
108531107452
){
108532107453
int j, k; /* Loop counters */
108533107454
int iCur; /* The VDBE cursor for the table */
108534107455
int addrNxt; /* Where to jump to continue with the next IN case */
108535107456
int omitTable; /* True if we use the index only */
108536107457
int bRev; /* True if we need to scan in reverse order */
108537107458
WhereLevel *pLevel; /* The where level to be coded */
107459
+ WhereLoop *pLoop; /* The WhereLoop object being coded */
108538107460
WhereClause *pWC; /* Decomposition of the entire WHERE clause */
108539107461
WhereTerm *pTerm; /* A WHERE clause term */
108540107462
Parse *pParse; /* Parsing context */
108541107463
Vdbe *v; /* The prepared stmt under constructions */
108542107464
struct SrcList_item *pTabItem; /* FROM clause term being coded */
@@ -108546,17 +107468,18 @@
108546107468
int iReleaseReg = 0; /* Temp register to free before returning */
108547107469
Bitmask newNotReady; /* Return value */
108548107470
108549107471
pParse = pWInfo->pParse;
108550107472
v = pParse->pVdbe;
108551
- pWC = pWInfo->pWC;
107473
+ pWC = &pWInfo->sWC;
108552107474
pLevel = &pWInfo->a[iLevel];
107475
+ pLoop = pLevel->pWLoop;
108553107476
pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
108554107477
iCur = pTabItem->iCursor;
108555
- bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
108556
- omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0
108557
- && (wctrlFlags & WHERE_FORCE_TABLE)==0;
107478
+ bRev = (pWInfo->revMask>>iLevel)&1;
107479
+ omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
107480
+ && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
108558107481
VdbeNoopComment((v, "Begin Join Loop %d", iLevel));
108559107482
108560107483
/* Create labels for the "break" and "continue" instructions
108561107484
** for the current loop. Jump to addrBrk to break out of a loop.
108562107485
** Jump to cont to go immediately to the next iteration of the
@@ -108589,51 +107512,41 @@
108589107512
sqlite3VdbeAddOp2(v, OP_If, regYield+1, addrBrk);
108590107513
pLevel->op = OP_Goto;
108591107514
}else
108592107515
108593107516
#ifndef SQLITE_OMIT_VIRTUALTABLE
108594
- if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
108595
- /* Case 0: The table is a virtual-table. Use the VFilter and VNext
107517
+ if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
107518
+ /* Case 1: The table is a virtual-table. Use the VFilter and VNext
108596107519
** to access the data.
108597107520
*/
108598107521
int iReg; /* P3 Value for OP_VFilter */
108599107522
int addrNotFound;
108600
- sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
108601
- int nConstraint = pVtabIdx->nConstraint;
108602
- struct sqlite3_index_constraint_usage *aUsage =
108603
- pVtabIdx->aConstraintUsage;
108604
- const struct sqlite3_index_constraint *aConstraint =
108605
- pVtabIdx->aConstraint;
107523
+ int nConstraint = pLoop->nLTerm;
108606107524
108607107525
sqlite3ExprCachePush(pParse);
108608107526
iReg = sqlite3GetTempRange(pParse, nConstraint+2);
108609107527
addrNotFound = pLevel->addrBrk;
108610
- for(j=1; j<=nConstraint; j++){
108611
- for(k=0; k<nConstraint; k++){
108612
- if( aUsage[k].argvIndex==j ){
108613
- int iTarget = iReg+j+1;
108614
- pTerm = &pWC->a[aConstraint[k].iTermOffset];
108615
- if( pTerm->eOperator & WO_IN ){
108616
- codeEqualityTerm(pParse, pTerm, pLevel, k, iTarget);
108617
- addrNotFound = pLevel->addrNxt;
108618
- }else{
108619
- sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
108620
- }
108621
- break;
108622
- }
108623
- }
108624
- if( k==nConstraint ) break;
108625
- }
108626
- sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
108627
- sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
108628
- sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg, pVtabIdx->idxStr,
108629
- pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
108630
- pVtabIdx->needToFreeIdxStr = 0;
108631107528
for(j=0; j<nConstraint; j++){
108632
- if( aUsage[j].omit ){
108633
- int iTerm = aConstraint[j].iTermOffset;
108634
- disableTerm(pLevel, &pWC->a[iTerm]);
107529
+ int iTarget = iReg+j+2;
107530
+ pTerm = pLoop->aLTerm[j];
107531
+ if( pTerm==0 ) continue;
107532
+ if( pTerm->eOperator & WO_IN ){
107533
+ codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
107534
+ addrNotFound = pLevel->addrNxt;
107535
+ }else{
107536
+ sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
107537
+ }
107538
+ }
107539
+ sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
107540
+ sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
107541
+ sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
107542
+ pLoop->u.vtab.idxStr,
107543
+ pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
107544
+ pLoop->u.vtab.needFree = 0;
107545
+ for(j=0; j<nConstraint && j<16; j++){
107546
+ if( (pLoop->u.vtab.omitMask>>j)&1 ){
107547
+ disableTerm(pLevel, pLoop->aLTerm[j]);
108635107548
}
108636107549
}
108637107550
pLevel->op = OP_VNext;
108638107551
pLevel->p1 = iCur;
108639107552
pLevel->p2 = sqlite3VdbeCurrentAddr(v);
@@ -108640,41 +107553,49 @@
108640107553
sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
108641107554
sqlite3ExprCachePop(pParse, 1);
108642107555
}else
108643107556
#endif /* SQLITE_OMIT_VIRTUALTABLE */
108644107557
108645
- if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
108646
- /* Case 1: We can directly reference a single row using an
107558
+ if( (pLoop->wsFlags & WHERE_IPK)!=0
107559
+ && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
107560
+ ){
107561
+ /* Case 2: We can directly reference a single row using an
108647107562
** equality comparison against the ROWID field. Or
108648107563
** we reference multiple rows using a "rowid IN (...)"
108649107564
** construct.
108650107565
*/
107566
+ assert( pLoop->u.btree.nEq==1 );
108651107567
iReleaseReg = sqlite3GetTempReg(pParse);
108652
- pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
107568
+ pTerm = pLoop->aLTerm[0];
108653107569
assert( pTerm!=0 );
108654107570
assert( pTerm->pExpr!=0 );
108655107571
assert( omitTable==0 );
108656107572
testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
108657
- iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, iReleaseReg);
107573
+ iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
108658107574
addrNxt = pLevel->addrNxt;
108659107575
sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
108660107576
sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
108661107577
sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
108662107578
sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
108663107579
VdbeComment((v, "pk"));
108664107580
pLevel->op = OP_Noop;
108665
- }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
108666
- /* Case 2: We have an inequality comparison against the ROWID field.
107581
+ }else if( (pLoop->wsFlags & WHERE_IPK)!=0
107582
+ && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
107583
+ ){
107584
+ /* Case 3: We have an inequality comparison against the ROWID field.
108667107585
*/
108668107586
int testOp = OP_Noop;
108669107587
int start;
108670107588
int memEndValue = 0;
108671107589
WhereTerm *pStart, *pEnd;
108672107590
108673107591
assert( omitTable==0 );
108674
- pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
108675
- pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
107592
+ j = 0;
107593
+ pStart = pEnd = 0;
107594
+ if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
107595
+ if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
107596
+ assert( pStart!=0 || pEnd!=0 );
108676107597
if( bRev ){
108677107598
pTerm = pStart;
108678107599
pStart = pEnd;
108679107600
pEnd = pTerm;
108680107601
}
@@ -108725,24 +107646,20 @@
108725107646
}
108726107647
start = sqlite3VdbeCurrentAddr(v);
108727107648
pLevel->op = bRev ? OP_Prev : OP_Next;
108728107649
pLevel->p1 = iCur;
108729107650
pLevel->p2 = start;
108730
- if( pStart==0 && pEnd==0 ){
108731
- pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
108732
- }else{
108733
- assert( pLevel->p5==0 );
108734
- }
107651
+ assert( pLevel->p5==0 );
108735107652
if( testOp!=OP_Noop ){
108736107653
iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
108737107654
sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
108738107655
sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
108739107656
sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
108740107657
sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
108741107658
}
108742
- }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
108743
- /* Case 3: A scan using an index.
107659
+ }else if( pLoop->wsFlags & WHERE_INDEXED ){
107660
+ /* Case 4: A scan using an index.
108744107661
**
108745107662
** The WHERE clause may contain zero or more equality
108746107663
** terms ("==" or "IN" operators) that refer to the N
108747107664
** left-most columns of the index. It may also contain
108748107665
** inequality constraints (>, <, >= or <=) on the indexed
@@ -108784,12 +107701,12 @@
108784107701
static const u8 aEndOp[] = {
108785107702
OP_Noop, /* 0: (!end_constraints) */
108786107703
OP_IdxGE, /* 1: (end_constraints && !bRev) */
108787107704
OP_IdxLT /* 2: (end_constraints && bRev) */
108788107705
};
108789
- int nEq = pLevel->plan.nEq; /* Number of == or IN terms */
108790
- int isMinQuery = 0; /* If this is an optimized SELECT min(x).. */
107706
+ int nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
107707
+ int isMinQuery = 0; /* If this is an optimized SELECT min(x).. */
108791107708
int regBase; /* Base register holding constraint values */
108792107709
int r1; /* Temp register */
108793107710
WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
108794107711
WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
108795107712
int startEq; /* True if range start uses ==, >= or <= */
@@ -108801,24 +107718,23 @@
108801107718
int nExtraReg = 0; /* Number of extra registers needed */
108802107719
int op; /* Instruction opcode */
108803107720
char *zStartAff; /* Affinity for start of range constraint */
108804107721
char *zEndAff; /* Affinity for end of range constraint */
108805107722
108806
- pIdx = pLevel->plan.u.pIdx;
107723
+ pIdx = pLoop->u.btree.pIndex;
108807107724
iIdxCur = pLevel->iIdxCur;
108808
- k = (nEq==pIdx->nColumn ? -1 : pIdx->aiColumn[nEq]);
108809107725
108810107726
/* If this loop satisfies a sort order (pOrderBy) request that
108811107727
** was passed to this function to implement a "SELECT min(x) ..."
108812107728
** query, then the caller will only allow the loop to run for
108813107729
** a single iteration. This means that the first row returned
108814107730
** should not have a NULL value stored in 'x'. If column 'x' is
108815107731
** the first one after the nEq equality constraints in the index,
108816107732
** this requires some special handling.
108817107733
*/
108818
- if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
108819
- && (pLevel->plan.wsFlags&WHERE_ORDERED)
107734
+ if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
107735
+ && (pWInfo->bOBSat!=0)
108820107736
&& (pIdx->nColumn>nEq)
108821107737
){
108822107738
/* assert( pOrderBy->nExpr==1 ); */
108823107739
/* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
108824107740
isMinQuery = 1;
@@ -108826,26 +107742,25 @@
108826107742
}
108827107743
108828107744
/* Find any inequality constraint terms for the start and end
108829107745
** of the range.
108830107746
*/
108831
- if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
108832
- pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
107747
+ j = nEq;
107748
+ if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
107749
+ pRangeStart = pLoop->aLTerm[j++];
108833107750
nExtraReg = 1;
108834107751
}
108835
- if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
108836
- pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
107752
+ if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
107753
+ pRangeEnd = pLoop->aLTerm[j++];
108837107754
nExtraReg = 1;
108838107755
}
108839107756
108840107757
/* Generate code to evaluate all constraint terms using == or IN
108841107758
** and store the values of those terms in an array of registers
108842107759
** starting at regBase.
108843107760
*/
108844
- regBase = codeAllEqualityTerms(
108845
- pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff
108846
- );
107761
+ regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
108847107762
zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
108848107763
addrNxt = pLevel->addrNxt;
108849107764
108850107765
/* If we are doing a reverse order scan on an ascending index, or
108851107766
** a forward order scan on a descending index, interchange the
@@ -108855,14 +107770,14 @@
108855107770
|| (bRev && pIdx->nColumn==nEq)
108856107771
){
108857107772
SWAP(WhereTerm *, pRangeEnd, pRangeStart);
108858107773
}
108859107774
108860
- testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
108861
- testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
108862
- testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
108863
- testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
107775
+ testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
107776
+ testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
107777
+ testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
107778
+ testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
108864107779
startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
108865107780
endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
108866107781
start_constraints = pRangeStart || nEq>0;
108867107782
108868107783
/* Seek the index cursor to the start of the range. */
@@ -108948,13 +107863,13 @@
108948107863
/* If there are inequality constraints, check that the value
108949107864
** of the table column that the inequality contrains is not NULL.
108950107865
** If it is, jump to the next iteration of the loop.
108951107866
*/
108952107867
r1 = sqlite3GetTempReg(pParse);
108953
- testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
108954
- testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
108955
- if( (pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
107868
+ testcase( pLoop->wsFlags & WHERE_BTM_LIMIT );
107869
+ testcase( pLoop->wsFlags & WHERE_TOP_LIMIT );
107870
+ if( (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
108956107871
sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
108957107872
sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
108958107873
}
108959107874
sqlite3ReleaseTempReg(pParse, r1);
108960107875
@@ -108969,28 +107884,28 @@
108969107884
}
108970107885
108971107886
/* Record the instruction used to terminate the loop. Disable
108972107887
** WHERE clause terms made redundant by the index range scan.
108973107888
*/
108974
- if( pLevel->plan.wsFlags & WHERE_UNIQUE ){
107889
+ if( pLoop->wsFlags & WHERE_ONEROW ){
108975107890
pLevel->op = OP_Noop;
108976107891
}else if( bRev ){
108977107892
pLevel->op = OP_Prev;
108978107893
}else{
108979107894
pLevel->op = OP_Next;
108980107895
}
108981107896
pLevel->p1 = iIdxCur;
108982
- if( pLevel->plan.wsFlags & WHERE_COVER_SCAN ){
107897
+ if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
108983107898
pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
108984107899
}else{
108985107900
assert( pLevel->p5==0 );
108986107901
}
108987107902
}else
108988107903
108989107904
#ifndef SQLITE_OMIT_OR_OPTIMIZATION
108990
- if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
108991
- /* Case 4: Two or more separately indexed terms connected by OR
107905
+ if( pLoop->wsFlags & WHERE_MULTI_OR ){
107906
+ /* Case 5: Two or more separately indexed terms connected by OR
108992107907
**
108993107908
** Example:
108994107909
**
108995107910
** CREATE TABLE t1(a,b,c,d);
108996107911
** CREATE INDEX i1 ON t1(a);
@@ -109039,11 +107954,11 @@
109039107954
int iRetInit; /* Address of regReturn init */
109040107955
int untestedTerms = 0; /* Some terms not completely tested */
109041107956
int ii; /* Loop counter */
109042107957
Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
109043107958
109044
- pTerm = pLevel->plan.u.pTerm;
107959
+ pTerm = pLoop->aLTerm[0];
109045107960
assert( pTerm!=0 );
109046107961
assert( pTerm->eOperator & WO_OR );
109047107962
assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
109048107963
pOrWc = &pTerm->u.pOrInfo->wc;
109049107964
pLevel->op = OP_Return;
@@ -109058,11 +107973,11 @@
109058107973
struct SrcList_item *origSrc; /* Original list of tables */
109059107974
nNotReady = pWInfo->nLevel - iLevel - 1;
109060107975
pOrTab = sqlite3StackAllocRaw(pParse->db,
109061107976
sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
109062107977
if( pOrTab==0 ) return notReady;
109063
- pOrTab->nAlloc = (i16)(nNotReady + 1);
107978
+ pOrTab->nAlloc = (u8)(nNotReady + 1);
109064107979
pOrTab->nSrc = pOrTab->nAlloc;
109065107980
memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
109066107981
origSrc = pWInfo->pTabList->a;
109067107982
for(k=1; k<=nNotReady; k++){
109068107983
memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
@@ -109080,11 +107995,11 @@
109080107995
** over the top of the loop into the body of it. In this case the
109081107996
** correct response for the end-of-loop code (the OP_Return) is to
109082107997
** fall through to the next instruction, just as an OP_Next does if
109083107998
** called on an uninitialized cursor.
109084107999
*/
109085
- if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
108000
+ if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
109086108001
regRowset = ++pParse->nMem;
109087108002
regRowid = ++pParse->nMem;
109088108003
sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
109089108004
}
109090108005
iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
@@ -109131,15 +108046,15 @@
109131108046
pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
109132108047
WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
109133108048
WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY, iCovCur);
109134108049
assert( pSubWInfo || pParse->nErr || pParse->db->mallocFailed );
109135108050
if( pSubWInfo ){
109136
- WhereLevel *pLvl;
108051
+ WhereLoop *pSubLoop;
109137108052
explainOneScan(
109138108053
pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
109139108054
);
109140
- if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
108055
+ if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
109141108056
int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
109142108057
int r;
109143108058
r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
109144108059
regRowid, 0);
109145108060
sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
@@ -109164,17 +108079,17 @@
109164108079
** processed or the index is the same as that used by all previous
109165108080
** terms, set pCov to the candidate covering index. Otherwise, set
109166108081
** pCov to NULL to indicate that no candidate covering index will
109167108082
** be available.
109168108083
*/
109169
- pLvl = &pSubWInfo->a[0];
109170
- if( (pLvl->plan.wsFlags & WHERE_INDEXED)!=0
109171
- && (pLvl->plan.wsFlags & WHERE_TEMP_INDEX)==0
109172
- && (ii==0 || pLvl->plan.u.pIdx==pCov)
108084
+ pSubLoop = pSubWInfo->a[0].pWLoop;
108085
+ assert( (pSubLoop->wsFlags & WHERE_TEMP_INDEX)==0 );
108086
+ if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
108087
+ && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
109173108088
){
109174
- assert( pLvl->iIdxCur==iCovCur );
109175
- pCov = pLvl->plan.u.pIdx;
108089
+ assert( pSubWInfo->a[0].iIdxCur==iCovCur );
108090
+ pCov = pSubLoop->u.btree.pIndex;
109176108091
}else{
109177108092
pCov = 0;
109178108093
}
109179108094
109180108095
/* Finish the loop through table entries that match term pOrTerm. */
@@ -109196,23 +108111,22 @@
109196108111
if( !untestedTerms ) disableTerm(pLevel, pTerm);
109197108112
}else
109198108113
#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
109199108114
109200108115
{
109201
- /* Case 5: There is no usable index. We must do a complete
108116
+ /* Case 6: There is no usable index. We must do a complete
109202108117
** scan of the entire table.
109203108118
*/
109204108119
static const u8 aStep[] = { OP_Next, OP_Prev };
109205108120
static const u8 aStart[] = { OP_Rewind, OP_Last };
109206108121
assert( bRev==0 || bRev==1 );
109207
- assert( omitTable==0 );
109208108122
pLevel->op = aStep[bRev];
109209108123
pLevel->p1 = iCur;
109210108124
pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
109211108125
pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
109212108126
}
109213
- newNotReady = notReady & ~getMask(pWC->pMaskSet, iCur);
108127
+ newNotReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur);
109214108128
109215108129
/* Insert code to test every subexpression that can be completely
109216108130
** computed using the current set of tables.
109217108131
**
109218108132
** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
@@ -109258,10 +108172,12 @@
109258108172
assert( !ExprHasProperty(pE, EP_FromJoin) );
109259108173
assert( (pTerm->prereqRight & newNotReady)!=0 );
109260108174
pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
109261108175
if( pAlt==0 ) continue;
109262108176
if( pAlt->wtFlags & (TERM_CODED) ) continue;
108177
+ testcase( pAlt->eOperator & WO_EQ );
108178
+ testcase( pAlt->eOperator & WO_IN );
109263108179
VdbeNoopComment((v, "begin transitive constraint"));
109264108180
sEq = *pAlt->pExpr;
109265108181
sEq.pLeft = pE->pLeft;
109266108182
sqlite3ExprIfFalse(pParse, &sEq, addrCont, SQLITE_JUMPIFNULL);
109267108183
}
@@ -109290,51 +108206,1562 @@
109290108206
sqlite3ReleaseTempReg(pParse, iReleaseReg);
109291108207
109292108208
return newNotReady;
109293108209
}
109294108210
109295
-#if defined(SQLITE_TEST)
108211
+#ifdef WHERETRACE_ENABLED
109296108212
/*
109297
-** The following variable holds a text description of query plan generated
109298
-** by the most recent call to sqlite3WhereBegin(). Each call to WhereBegin
109299
-** overwrites the previous. This information is used for testing and
109300
-** analysis only.
108213
+** Print a WhereLoop object for debugging purposes
109301108214
*/
109302
-SQLITE_API char sqlite3_query_plan[BMS*2*40]; /* Text of the join */
109303
-static int nQPlan = 0; /* Next free slow in _query_plan[] */
108215
+static void whereLoopPrint(WhereLoop *p, SrcList *pTabList){
108216
+ int nb = 1+(pTabList->nSrc+7)/8;
108217
+ struct SrcList_item *pItem = pTabList->a + p->iTab;
108218
+ Table *pTab = pItem->pTab;
108219
+ sqlite3DebugPrintf("%c %2d.%0*llx.%0*llx", p->cId,
108220
+ p->iTab, nb, p->maskSelf, nb, p->prereq);
108221
+ sqlite3DebugPrintf(" %8s",
108222
+ pItem->zAlias ? pItem->zAlias : pTab->zName);
108223
+ if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
108224
+ if( p->u.btree.pIndex ){
108225
+ const char *zName = p->u.btree.pIndex->zName;
108226
+ if( zName==0 ) zName = "ipk";
108227
+ if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
108228
+ int i = sqlite3Strlen30(zName) - 1;
108229
+ while( zName[i]!='_' ) i--;
108230
+ zName += i;
108231
+ }
108232
+ sqlite3DebugPrintf(".%-12s %2d", zName, p->u.btree.nEq);
108233
+ }else{
108234
+ sqlite3DebugPrintf("%16s","");
108235
+ }
108236
+ }else{
108237
+ char *z;
108238
+ if( p->u.vtab.idxStr ){
108239
+ z = sqlite3_mprintf("(%d,\"%s\",%x)",
108240
+ p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
108241
+ }else{
108242
+ z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
108243
+ }
108244
+ sqlite3DebugPrintf(" %-15s", z);
108245
+ sqlite3_free(z);
108246
+ }
108247
+ sqlite3DebugPrintf(" fg %05x N %d", p->wsFlags, p->nLTerm);
108248
+ sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
108249
+}
108250
+#endif
109304108251
109305
-#endif /* SQLITE_TEST */
108252
+/*
108253
+** Convert bulk memory into a valid WhereLoop that can be passed
108254
+** to whereLoopClear harmlessly.
108255
+*/
108256
+static void whereLoopInit(WhereLoop *p){
108257
+ p->aLTerm = p->aLTermSpace;
108258
+ p->nLTerm = 0;
108259
+ p->nLSlot = ArraySize(p->aLTermSpace);
108260
+ p->wsFlags = 0;
108261
+}
109306108262
108263
+/*
108264
+** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
108265
+*/
108266
+static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
108267
+ if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_TEMP_INDEX) ){
108268
+ if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
108269
+ sqlite3_free(p->u.vtab.idxStr);
108270
+ p->u.vtab.needFree = 0;
108271
+ p->u.vtab.idxStr = 0;
108272
+ }else if( (p->wsFlags & WHERE_TEMP_INDEX)!=0 && p->u.btree.pIndex!=0 ){
108273
+ sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
108274
+ sqlite3DbFree(db, p->u.btree.pIndex);
108275
+ p->u.btree.pIndex = 0;
108276
+ }
108277
+ }
108278
+}
108279
+
108280
+/*
108281
+** Deallocate internal memory used by a WhereLoop object
108282
+*/
108283
+static void whereLoopClear(sqlite3 *db, WhereLoop *p){
108284
+ if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
108285
+ whereLoopClearUnion(db, p);
108286
+ whereLoopInit(p);
108287
+}
108288
+
108289
+/*
108290
+** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
108291
+*/
108292
+static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
108293
+ WhereTerm **paNew;
108294
+ if( p->nLSlot>=n ) return SQLITE_OK;
108295
+ n = (n+7)&~7;
108296
+ paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
108297
+ if( paNew==0 ) return SQLITE_NOMEM;
108298
+ memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
108299
+ if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
108300
+ p->aLTerm = paNew;
108301
+ p->nLSlot = n;
108302
+ return SQLITE_OK;
108303
+}
108304
+
108305
+/*
108306
+** Transfer content from the second pLoop into the first.
108307
+*/
108308
+static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
108309
+ if( whereLoopResize(db, pTo, pFrom->nLTerm) ) return SQLITE_NOMEM;
108310
+ whereLoopClearUnion(db, pTo);
108311
+ memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
108312
+ memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
108313
+ if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
108314
+ pFrom->u.vtab.needFree = 0;
108315
+ }else if( (pFrom->wsFlags & WHERE_TEMP_INDEX)!=0 ){
108316
+ pFrom->u.btree.pIndex = 0;
108317
+ }
108318
+ return SQLITE_OK;
108319
+}
108320
+
108321
+/*
108322
+** Delete a WhereLoop object
108323
+*/
108324
+static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
108325
+ whereLoopClear(db, p);
108326
+ sqlite3DbFree(db, p);
108327
+}
109307108328
109308108329
/*
109309108330
** Free a WhereInfo structure
109310108331
*/
109311108332
static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
109312108333
if( ALWAYS(pWInfo) ){
109313
- int i;
109314
- for(i=0; i<pWInfo->nLevel; i++){
109315
- sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
109316
- if( pInfo ){
109317
- /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
109318
- if( pInfo->needToFreeIdxStr ){
109319
- sqlite3_free(pInfo->idxStr);
109320
- }
109321
- sqlite3DbFree(db, pInfo);
109322
- }
109323
- if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){
109324
- Index *pIdx = pWInfo->a[i].plan.u.pIdx;
109325
- if( pIdx ){
109326
- sqlite3DbFree(db, pIdx->zColAff);
109327
- sqlite3DbFree(db, pIdx);
109328
- }
109329
- }
109330
- }
109331
- whereClauseClear(pWInfo->pWC);
108334
+ whereClauseClear(&pWInfo->sWC);
108335
+ while( pWInfo->pLoops ){
108336
+ WhereLoop *p = pWInfo->pLoops;
108337
+ pWInfo->pLoops = p->pNextLoop;
108338
+ whereLoopDelete(db, p);
108339
+ }
109332108340
sqlite3DbFree(db, pWInfo);
109333108341
}
109334108342
}
109335108343
108344
+/*
108345
+** Insert or replace a WhereLoop entry using the template supplied.
108346
+**
108347
+** An existing WhereLoop entry might be overwritten if the new template
108348
+** is better and has fewer dependencies. Or the template will be ignored
108349
+** and no insert will occur if an existing WhereLoop is faster and has
108350
+** fewer dependencies than the template. Otherwise a new WhereLoop is
108351
+** added based on the template.
108352
+**
108353
+** If pBuilder->pBest is not NULL then we only care about the very
108354
+** best template and that template should be stored in pBuilder->pBest.
108355
+** If pBuilder->pBest is NULL then a list of the best templates are stored
108356
+** in pBuilder->pWInfo->pLoops.
108357
+**
108358
+** When accumulating multiple loops (when pBuilder->pBest is NULL) we
108359
+** still might overwrite similar loops with the new template if the
108360
+** template is better. Loops may be overwritten if the following
108361
+** conditions are met:
108362
+**
108363
+** (1) They have the same iTab.
108364
+** (2) They have the same iSortIdx.
108365
+** (3) The template has same or fewer dependencies than the current loop
108366
+** (4) The template has the same or lower cost than the current loop
108367
+** (5) The template uses more terms of the same index but has no additional
108368
+** dependencies
108369
+*/
108370
+static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
108371
+ WhereLoop **ppPrev, *p, *pNext = 0;
108372
+ WhereInfo *pWInfo = pBuilder->pWInfo;
108373
+ sqlite3 *db = pWInfo->pParse->db;
108374
+
108375
+ /* If pBuilder->pBest is defined, then only keep track of the single
108376
+ ** best WhereLoop. pBuilder->pBest->maskSelf==0 indicates that no
108377
+ ** prior WhereLoops have been evaluated and that the current pTemplate
108378
+ ** is therefore the first and hence the best and should be retained.
108379
+ */
108380
+ if( (p = pBuilder->pBest)!=0 ){
108381
+ if( p->maskSelf!=0 ){
108382
+ WhereCost rCost = whereCostAdd(p->rRun,p->rSetup);
108383
+ WhereCost rTemplate = whereCostAdd(pTemplate->rRun,pTemplate->rSetup);
108384
+ if( rCost < rTemplate ){
108385
+ testcase( rCost==rTemplate-1 );
108386
+ goto whereLoopInsert_noop;
108387
+ }
108388
+ if( rCost==rTemplate && (p->prereq & pTemplate->prereq)==p->prereq ){
108389
+ goto whereLoopInsert_noop;
108390
+ }
108391
+ }
108392
+#if WHERETRACE_ENABLED
108393
+ if( sqlite3WhereTrace & 0x8 ){
108394
+ sqlite3DebugPrintf(p->maskSelf==0 ? "ins-init: " : "ins-best: ");
108395
+ whereLoopPrint(pTemplate, pWInfo->pTabList);
108396
+ }
108397
+#endif
108398
+ whereLoopXfer(db, p, pTemplate);
108399
+ return SQLITE_OK;
108400
+ }
108401
+
108402
+ /* Search for an existing WhereLoop to overwrite, or which takes
108403
+ ** priority over pTemplate.
108404
+ */
108405
+ for(ppPrev=&pWInfo->pLoops, p=*ppPrev; p; ppPrev=&p->pNextLoop, p=*ppPrev){
108406
+ if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
108407
+ /* If either the iTab or iSortIdx values for two WhereLoop are different
108408
+ ** then those WhereLoops need to be considered separately. Neither is
108409
+ ** a candidate to replace the other. */
108410
+ continue;
108411
+ }
108412
+ /* In the current implementation, the rSetup value is either zero
108413
+ ** or the cost of building an automatic index (NlogN) and the NlogN
108414
+ ** is the same for compatible WhereLoops. */
108415
+ assert( p->rSetup==0 || pTemplate->rSetup==0
108416
+ || p->rSetup==pTemplate->rSetup );
108417
+
108418
+ /* whereLoopAddBtree() always generates and inserts the automatic index
108419
+ ** case first. Hence compatible candidate WhereLoops never have a larger
108420
+ ** rSetup. Call this SETUP-INVARIANT */
108421
+ assert( p->rSetup>=pTemplate->rSetup );
108422
+
108423
+ if( (p->prereq & pTemplate->prereq)==p->prereq
108424
+ && p->rSetup<=pTemplate->rSetup
108425
+ && p->rRun<=pTemplate->rRun
108426
+ ){
108427
+ /* This branch taken when p is equal or better than pTemplate in
108428
+ ** all of (1) dependences (2) setup-cost, and (3) run-cost. */
108429
+ assert( p->rSetup==pTemplate->rSetup );
108430
+ if( p->nLTerm<pTemplate->nLTerm
108431
+ && (p->wsFlags & WHERE_INDEXED)!=0
108432
+ && (pTemplate->wsFlags & WHERE_INDEXED)!=0
108433
+ && p->u.btree.pIndex==pTemplate->u.btree.pIndex
108434
+ && p->prereq==pTemplate->prereq
108435
+ ){
108436
+ /* Overwrite an existing WhereLoop with an similar one that uses
108437
+ ** more terms of the index */
108438
+ pNext = p->pNextLoop;
108439
+ break;
108440
+ }else{
108441
+ /* pTemplate is not helpful.
108442
+ ** Return without changing or adding anything */
108443
+ goto whereLoopInsert_noop;
108444
+ }
108445
+ }
108446
+ if( (p->prereq & pTemplate->prereq)==pTemplate->prereq
108447
+ && p->rRun>=pTemplate->rRun
108448
+ && ALWAYS(p->rSetup>=pTemplate->rSetup) /* See SETUP-INVARIANT above */
108449
+ ){
108450
+ /* Overwrite an existing WhereLoop with a better one: one that is
108451
+ ** better at one of (1) dependences, (2) setup-cost, or (3) run-cost
108452
+ ** and is no worse in any of those categories. */
108453
+ pNext = p->pNextLoop;
108454
+ break;
108455
+ }
108456
+ }
108457
+
108458
+ /* If we reach this point it means that either p[] should be overwritten
108459
+ ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
108460
+ ** WhereLoop and insert it.
108461
+ */
108462
+#if WHERETRACE_ENABLED
108463
+ if( sqlite3WhereTrace & 0x8 ){
108464
+ if( p!=0 ){
108465
+ sqlite3DebugPrintf("ins-del: ");
108466
+ whereLoopPrint(p, pWInfo->pTabList);
108467
+ }
108468
+ sqlite3DebugPrintf("ins-new: ");
108469
+ whereLoopPrint(pTemplate, pWInfo->pTabList);
108470
+ }
108471
+#endif
108472
+ if( p==0 ){
108473
+ p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
108474
+ if( p==0 ) return SQLITE_NOMEM;
108475
+ whereLoopInit(p);
108476
+ }
108477
+ whereLoopXfer(db, p, pTemplate);
108478
+ p->pNextLoop = pNext;
108479
+ *ppPrev = p;
108480
+ if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
108481
+ Index *pIndex = p->u.btree.pIndex;
108482
+ if( pIndex && pIndex->tnum==0 ){
108483
+ p->u.btree.pIndex = 0;
108484
+ }
108485
+ }
108486
+ return SQLITE_OK;
108487
+
108488
+ /* Jump here if the insert is a no-op */
108489
+whereLoopInsert_noop:
108490
+#if WHERETRACE_ENABLED
108491
+ if( sqlite3WhereTrace & 0x8 ){
108492
+ sqlite3DebugPrintf(pBuilder->pBest ? "ins-skip: " : "ins-noop: ");
108493
+ whereLoopPrint(pTemplate, pWInfo->pTabList);
108494
+ }
108495
+#endif
108496
+ return SQLITE_OK;
108497
+}
108498
+
108499
+/*
108500
+** We have so far matched pBuilder->pNew->u.btree.nEq terms of the index pIndex.
108501
+** Try to match one more.
108502
+**
108503
+** If pProbe->tnum==0, that means pIndex is a fake index used for the
108504
+** INTEGER PRIMARY KEY.
108505
+*/
108506
+static int whereLoopAddBtreeIndex(
108507
+ WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
108508
+ struct SrcList_item *pSrc, /* FROM clause term being analyzed */
108509
+ Index *pProbe, /* An index on pSrc */
108510
+ WhereCost nInMul /* log(Number of iterations due to IN) */
108511
+){
108512
+ WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
108513
+ Parse *pParse = pWInfo->pParse; /* Parsing context */
108514
+ sqlite3 *db = pParse->db; /* Database connection malloc context */
108515
+ WhereLoop *pNew; /* Template WhereLoop under construction */
108516
+ WhereTerm *pTerm; /* A WhereTerm under consideration */
108517
+ int opMask; /* Valid operators for constraints */
108518
+ WhereScan scan; /* Iterator for WHERE terms */
108519
+ Bitmask saved_prereq; /* Original value of pNew->prereq */
108520
+ u16 saved_nLTerm; /* Original value of pNew->nLTerm */
108521
+ int saved_nEq; /* Original value of pNew->u.btree.nEq */
108522
+ u32 saved_wsFlags; /* Original value of pNew->wsFlags */
108523
+ WhereCost saved_nOut; /* Original value of pNew->nOut */
108524
+ int iCol; /* Index of the column in the table */
108525
+ int rc = SQLITE_OK; /* Return code */
108526
+ WhereCost nRowEst; /* Estimated index selectivity */
108527
+ WhereCost rLogSize; /* Logarithm of table size */
108528
+ WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
108529
+
108530
+ pNew = pBuilder->pNew;
108531
+ if( db->mallocFailed ) return SQLITE_NOMEM;
108532
+
108533
+ assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
108534
+ assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
108535
+ if( pNew->wsFlags & WHERE_BTM_LIMIT ){
108536
+ opMask = WO_LT|WO_LE;
108537
+ }else if( pProbe->tnum<=0 || (pSrc->jointype & JT_LEFT)!=0 ){
108538
+ opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
108539
+ }else{
108540
+ opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE;
108541
+ }
108542
+ if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
108543
+
108544
+ assert( pNew->u.btree.nEq<=pProbe->nColumn );
108545
+ if( pNew->u.btree.nEq < pProbe->nColumn ){
108546
+ iCol = pProbe->aiColumn[pNew->u.btree.nEq];
108547
+ nRowEst = whereCost(pProbe->aiRowEst[pNew->u.btree.nEq+1]);
108548
+ if( nRowEst==0 && pProbe->onError==OE_None ) nRowEst = 1;
108549
+ }else{
108550
+ iCol = -1;
108551
+ nRowEst = 0;
108552
+ }
108553
+ pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
108554
+ opMask, pProbe);
108555
+ saved_nEq = pNew->u.btree.nEq;
108556
+ saved_nLTerm = pNew->nLTerm;
108557
+ saved_wsFlags = pNew->wsFlags;
108558
+ saved_prereq = pNew->prereq;
108559
+ saved_nOut = pNew->nOut;
108560
+ pNew->rSetup = 0;
108561
+ rLogSize = estLog(whereCost(pProbe->aiRowEst[0]));
108562
+ for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
108563
+ int nIn = 0;
108564
+ if( pTerm->prereqRight & pNew->maskSelf ) continue;
108565
+ pNew->wsFlags = saved_wsFlags;
108566
+ pNew->u.btree.nEq = saved_nEq;
108567
+ pNew->nLTerm = saved_nLTerm;
108568
+ if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
108569
+ pNew->aLTerm[pNew->nLTerm++] = pTerm;
108570
+ pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
108571
+ pNew->rRun = rLogSize; /* Baseline cost is log2(N). Adjustments below */
108572
+ if( pTerm->eOperator & WO_IN ){
108573
+ Expr *pExpr = pTerm->pExpr;
108574
+ pNew->wsFlags |= WHERE_COLUMN_IN;
108575
+ if( ExprHasProperty(pExpr, EP_xIsSelect) ){
108576
+ /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
108577
+ nIn = 46; assert( 46==whereCost(25) );
108578
+ }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
108579
+ /* "x IN (value, value, ...)" */
108580
+ nIn = whereCost(pExpr->x.pList->nExpr);
108581
+ }
108582
+ pNew->rRun += nIn;
108583
+ pNew->u.btree.nEq++;
108584
+ pNew->nOut = nRowEst + nInMul + nIn;
108585
+ }else if( pTerm->eOperator & (WO_EQ) ){
108586
+ assert( (pNew->wsFlags & (WHERE_COLUMN_NULL|WHERE_COLUMN_IN))!=0
108587
+ || nInMul==0 );
108588
+ pNew->wsFlags |= WHERE_COLUMN_EQ;
108589
+ if( iCol<0
108590
+ || (pProbe->onError!=OE_None && nInMul==0
108591
+ && pNew->u.btree.nEq==pProbe->nColumn-1)
108592
+ ){
108593
+ assert( (pNew->wsFlags & WHERE_COLUMN_IN)==0 || iCol<0 );
108594
+ pNew->wsFlags |= WHERE_ONEROW;
108595
+ }
108596
+ pNew->u.btree.nEq++;
108597
+ pNew->nOut = nRowEst + nInMul;
108598
+ }else if( pTerm->eOperator & (WO_ISNULL) ){
108599
+ pNew->wsFlags |= WHERE_COLUMN_NULL;
108600
+ pNew->u.btree.nEq++;
108601
+ /* TUNING: IS NULL selects 2 rows */
108602
+ nIn = 10; assert( 10==whereCost(2) );
108603
+ pNew->nOut = nRowEst + nInMul + nIn;
108604
+ }else if( pTerm->eOperator & (WO_GT|WO_GE) ){
108605
+ testcase( pTerm->eOperator & WO_GT );
108606
+ testcase( pTerm->eOperator & WO_GE );
108607
+ pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
108608
+ pBtm = pTerm;
108609
+ pTop = 0;
108610
+ }else{
108611
+ assert( pTerm->eOperator & (WO_LT|WO_LE) );
108612
+ testcase( pTerm->eOperator & WO_LT );
108613
+ testcase( pTerm->eOperator & WO_LE );
108614
+ pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
108615
+ pTop = pTerm;
108616
+ pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
108617
+ pNew->aLTerm[pNew->nLTerm-2] : 0;
108618
+ }
108619
+ if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
108620
+ /* Adjust nOut and rRun for STAT3 range values */
108621
+ WhereCost rDiv;
108622
+ whereRangeScanEst(pParse, pProbe, pNew->u.btree.nEq,
108623
+ pBtm, pTop, &rDiv);
108624
+ pNew->nOut = saved_nOut>rDiv+10 ? saved_nOut - rDiv : 10;
108625
+ }
108626
+#ifdef SQLITE_ENABLE_STAT3
108627
+ if( pNew->u.btree.nEq==1 && pProbe->nSample ){
108628
+ tRowcnt nOut = 0;
108629
+ if( (pTerm->eOperator & (WO_EQ|WO_ISNULL))!=0 ){
108630
+ testcase( pTerm->eOperator & WO_EQ );
108631
+ testcase( pTerm->eOperator & WO_ISNULL );
108632
+ rc = whereEqualScanEst(pParse, pProbe, pTerm->pExpr->pRight, &nOut);
108633
+ }else if( (pTerm->eOperator & WO_IN)
108634
+ && !ExprHasProperty(pTerm->pExpr, EP_xIsSelect) ){
108635
+ rc = whereInScanEst(pParse, pProbe, pTerm->pExpr->x.pList, &nOut);
108636
+ }
108637
+ if( rc==SQLITE_OK ) pNew->nOut = whereCost(nOut);
108638
+ }
108639
+#endif
108640
+ if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
108641
+ /* Each row involves a step of the index, then a binary search of
108642
+ ** the main table */
108643
+ pNew->rRun = whereCostAdd(pNew->rRun, rLogSize>27 ? rLogSize-17 : 10);
108644
+ }
108645
+ /* Step cost for each output row */
108646
+ pNew->rRun = whereCostAdd(pNew->rRun, pNew->nOut);
108647
+ /* TBD: Adjust nOut for additional constraints */
108648
+ rc = whereLoopInsert(pBuilder, pNew);
108649
+ if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
108650
+ && pNew->u.btree.nEq<(pProbe->nColumn + (pProbe->zName!=0))
108651
+ ){
108652
+ whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
108653
+ }
108654
+ }
108655
+ pNew->prereq = saved_prereq;
108656
+ pNew->u.btree.nEq = saved_nEq;
108657
+ pNew->wsFlags = saved_wsFlags;
108658
+ pNew->nOut = saved_nOut;
108659
+ pNew->nLTerm = saved_nLTerm;
108660
+ return rc;
108661
+}
108662
+
108663
+/*
108664
+** Return True if it is possible that pIndex might be useful in
108665
+** implementing the ORDER BY clause in pBuilder.
108666
+**
108667
+** Return False if pBuilder does not contain an ORDER BY clause or
108668
+** if there is no way for pIndex to be useful in implementing that
108669
+** ORDER BY clause.
108670
+*/
108671
+static int indexMightHelpWithOrderBy(
108672
+ WhereLoopBuilder *pBuilder,
108673
+ Index *pIndex,
108674
+ int iCursor
108675
+){
108676
+ ExprList *pOB;
108677
+ int ii, jj;
108678
+
108679
+ if( pIndex->bUnordered ) return 0;
108680
+ if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
108681
+ for(ii=0; ii<pOB->nExpr; ii++){
108682
+ Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
108683
+ if( pExpr->op!=TK_COLUMN ) return 0;
108684
+ if( pExpr->iTable==iCursor ){
108685
+ for(jj=0; jj<pIndex->nColumn; jj++){
108686
+ if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
108687
+ }
108688
+ }
108689
+ }
108690
+ return 0;
108691
+}
108692
+
108693
+/*
108694
+** Return a bitmask where 1s indicate that the corresponding column of
108695
+** the table is used by an index. Only the first 63 columns are considered.
108696
+*/
108697
+static Bitmask columnsInIndex(Index *pIdx){
108698
+ Bitmask m = 0;
108699
+ int j;
108700
+ for(j=pIdx->nColumn-1; j>=0; j--){
108701
+ int x = pIdx->aiColumn[j];
108702
+ testcase( x==BMS-1 );
108703
+ testcase( x==BMS-2 );
108704
+ if( x<BMS-1 ) m |= MASKBIT(x);
108705
+ }
108706
+ return m;
108707
+}
108708
+
108709
+
108710
+/*
108711
+** Add all WhereLoop objects a single table of the join were the table
108712
+** is idenfied by pBuilder->pNew->iTab. That table is guaranteed to be
108713
+** a b-tree table, not a virtual table.
108714
+*/
108715
+static int whereLoopAddBtree(
108716
+ WhereLoopBuilder *pBuilder, /* WHERE clause information */
108717
+ Bitmask mExtra /* Extra prerequesites for using this table */
108718
+){
108719
+ WhereInfo *pWInfo; /* WHERE analysis context */
108720
+ Index *pProbe; /* An index we are evaluating */
108721
+ Index sPk; /* A fake index object for the primary key */
108722
+ tRowcnt aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
108723
+ int aiColumnPk = -1; /* The aColumn[] value for the sPk index */
108724
+ SrcList *pTabList; /* The FROM clause */
108725
+ struct SrcList_item *pSrc; /* The FROM clause btree term to add */
108726
+ WhereLoop *pNew; /* Template WhereLoop object */
108727
+ int rc = SQLITE_OK; /* Return code */
108728
+ int iSortIdx = 1; /* Index number */
108729
+ int b; /* A boolean value */
108730
+ WhereCost rSize; /* number of rows in the table */
108731
+ WhereCost rLogSize; /* Logarithm of the number of rows in the table */
108732
+
108733
+ pNew = pBuilder->pNew;
108734
+ pWInfo = pBuilder->pWInfo;
108735
+ pTabList = pWInfo->pTabList;
108736
+ pSrc = pTabList->a + pNew->iTab;
108737
+ assert( !IsVirtual(pSrc->pTab) );
108738
+
108739
+ if( pSrc->pIndex ){
108740
+ /* An INDEXED BY clause specifies a particular index to use */
108741
+ pProbe = pSrc->pIndex;
108742
+ }else{
108743
+ /* There is no INDEXED BY clause. Create a fake Index object in local
108744
+ ** variable sPk to represent the rowid primary key index. Make this
108745
+ ** fake index the first in a chain of Index objects with all of the real
108746
+ ** indices to follow */
108747
+ Index *pFirst; /* First of real indices on the table */
108748
+ memset(&sPk, 0, sizeof(Index));
108749
+ sPk.nColumn = 1;
108750
+ sPk.aiColumn = &aiColumnPk;
108751
+ sPk.aiRowEst = aiRowEstPk;
108752
+ sPk.onError = OE_Replace;
108753
+ sPk.pTable = pSrc->pTab;
108754
+ aiRowEstPk[0] = pSrc->pTab->nRowEst;
108755
+ aiRowEstPk[1] = 1;
108756
+ pFirst = pSrc->pTab->pIndex;
108757
+ if( pSrc->notIndexed==0 ){
108758
+ /* The real indices of the table are only considered if the
108759
+ ** NOT INDEXED qualifier is omitted from the FROM clause */
108760
+ sPk.pNext = pFirst;
108761
+ }
108762
+ pProbe = &sPk;
108763
+ }
108764
+ rSize = whereCost(pSrc->pTab->nRowEst);
108765
+ rLogSize = estLog(rSize);
108766
+
108767
+ /* Automatic indexes */
108768
+ if( !pBuilder->pBest
108769
+ && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
108770
+ && pSrc->pIndex==0
108771
+ && !pSrc->viaCoroutine
108772
+ && !pSrc->notIndexed
108773
+ && !pSrc->isCorrelated
108774
+ ){
108775
+ /* Generate auto-index WhereLoops */
108776
+ WhereClause *pWC = pBuilder->pWC;
108777
+ WhereTerm *pTerm;
108778
+ WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
108779
+ for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
108780
+ if( pTerm->prereqRight & pNew->maskSelf ) continue;
108781
+ if( termCanDriveIndex(pTerm, pSrc, 0) ){
108782
+ pNew->u.btree.nEq = 1;
108783
+ pNew->u.btree.pIndex = 0;
108784
+ pNew->nLTerm = 1;
108785
+ pNew->aLTerm[0] = pTerm;
108786
+ /* TUNING: One-time cost for computing the automatic index is
108787
+ ** approximately 6*N*log2(N) where N is the number of rows in
108788
+ ** the table being indexed. */
108789
+ pNew->rSetup = rLogSize + rSize + 26; assert( 26==whereCost(6) );
108790
+ /* TUNING: Each index lookup yields 10 rows in the table */
108791
+ pNew->nOut = 33; assert( 33==whereCost(10) );
108792
+ pNew->rRun = whereCostAdd(rLogSize,pNew->nOut);
108793
+ pNew->wsFlags = WHERE_TEMP_INDEX;
108794
+ pNew->prereq = mExtra | pTerm->prereqRight;
108795
+ rc = whereLoopInsert(pBuilder, pNew);
108796
+ }
108797
+ }
108798
+ }
108799
+
108800
+ /* Loop over all indices
108801
+ */
108802
+ for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
108803
+ pNew->u.btree.nEq = 0;
108804
+ pNew->nLTerm = 0;
108805
+ pNew->iSortIdx = 0;
108806
+ pNew->rSetup = 0;
108807
+ pNew->prereq = mExtra;
108808
+ pNew->nOut = rSize;
108809
+ pNew->u.btree.pIndex = pProbe;
108810
+ b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
108811
+ /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
108812
+ assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
108813
+ if( pProbe->tnum<=0 ){
108814
+ /* Integer primary key index */
108815
+ pNew->wsFlags = WHERE_IPK;
108816
+
108817
+ /* Full table scan */
108818
+ pNew->iSortIdx = b ? iSortIdx : 0;
108819
+ /* TUNING: Cost of full table scan is 3*(N + log2(N)).
108820
+ ** + The extra 3 factor is to encourage the use of indexed lookups
108821
+ ** over full scans. A smaller constant 2 is used for covering
108822
+ ** index scans so that a covering index scan will be favored over
108823
+ ** a table scan. */
108824
+ pNew->rRun = whereCostAdd(rSize,rLogSize) + 16;
108825
+ rc = whereLoopInsert(pBuilder, pNew);
108826
+ if( rc ) break;
108827
+ }else{
108828
+ Bitmask m = pSrc->colUsed & ~columnsInIndex(pProbe);
108829
+ pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
108830
+
108831
+ /* Full scan via index */
108832
+ if( b
108833
+ || ( m==0
108834
+ && pProbe->bUnordered==0
108835
+ && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
108836
+ && sqlite3GlobalConfig.bUseCis
108837
+ && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
108838
+ )
108839
+ ){
108840
+ pNew->iSortIdx = b ? iSortIdx : 0;
108841
+ if( m==0 ){
108842
+ /* TUNING: Cost of a covering index scan is 2*(N + log2(N)).
108843
+ ** + The extra 2 factor is to encourage the use of indexed lookups
108844
+ ** over index scans. A table scan uses a factor of 3 so that
108845
+ ** index scans are favored over table scans.
108846
+ ** + If this covering index might also help satisfy the ORDER BY
108847
+ ** clause, then the cost is fudged down slightly so that this
108848
+ ** index is favored above other indices that have no hope of
108849
+ ** helping with the ORDER BY. */
108850
+ pNew->rRun = 10 + whereCostAdd(rSize,rLogSize) - b;
108851
+ }else{
108852
+ assert( b!=0 );
108853
+ /* TUNING: Cost of scanning a non-covering index is (N+1)*log2(N)
108854
+ ** which we will simplify to just N*log2(N) */
108855
+ pNew->rRun = rSize + rLogSize;
108856
+ }
108857
+ rc = whereLoopInsert(pBuilder, pNew);
108858
+ if( rc ) break;
108859
+ }
108860
+ }
108861
+ rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
108862
+
108863
+ /* If there was an INDEXED BY clause, then only that one index is
108864
+ ** considered. */
108865
+ if( pSrc->pIndex ) break;
108866
+ }
108867
+ return rc;
108868
+}
108869
+
108870
+#ifndef SQLITE_OMIT_VIRTUALTABLE
108871
+/*
108872
+** Add all WhereLoop objects for a table of the join identified by
108873
+** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
108874
+*/
108875
+static int whereLoopAddVirtual(
108876
+ WhereLoopBuilder *pBuilder /* WHERE clause information */
108877
+){
108878
+ WhereInfo *pWInfo; /* WHERE analysis context */
108879
+ Parse *pParse; /* The parsing context */
108880
+ WhereClause *pWC; /* The WHERE clause */
108881
+ struct SrcList_item *pSrc; /* The FROM clause term to search */
108882
+ Table *pTab;
108883
+ sqlite3 *db;
108884
+ sqlite3_index_info *pIdxInfo;
108885
+ struct sqlite3_index_constraint *pIdxCons;
108886
+ struct sqlite3_index_constraint_usage *pUsage;
108887
+ WhereTerm *pTerm;
108888
+ int i, j;
108889
+ int iTerm, mxTerm;
108890
+ int nConstraint;
108891
+ int seenIn = 0; /* True if an IN operator is seen */
108892
+ int seenVar = 0; /* True if a non-constant constraint is seen */
108893
+ int iPhase; /* 0: const w/o IN, 1: const, 2: no IN, 2: IN */
108894
+ WhereLoop *pNew;
108895
+ int rc = SQLITE_OK;
108896
+
108897
+ pWInfo = pBuilder->pWInfo;
108898
+ pParse = pWInfo->pParse;
108899
+ db = pParse->db;
108900
+ pWC = pBuilder->pWC;
108901
+ pNew = pBuilder->pNew;
108902
+ pSrc = &pWInfo->pTabList->a[pNew->iTab];
108903
+ pTab = pSrc->pTab;
108904
+ assert( IsVirtual(pTab) );
108905
+ pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy);
108906
+ if( pIdxInfo==0 ) return SQLITE_NOMEM;
108907
+ pNew->prereq = 0;
108908
+ pNew->rSetup = 0;
108909
+ pNew->wsFlags = WHERE_VIRTUALTABLE;
108910
+ pNew->nLTerm = 0;
108911
+ pNew->u.vtab.needFree = 0;
108912
+ pUsage = pIdxInfo->aConstraintUsage;
108913
+ nConstraint = pIdxInfo->nConstraint;
108914
+ if( whereLoopResize(db, pNew, nConstraint) ){
108915
+ sqlite3DbFree(db, pIdxInfo);
108916
+ return SQLITE_NOMEM;
108917
+ }
108918
+
108919
+ for(iPhase=0; iPhase<=3; iPhase++){
108920
+ if( !seenIn && (iPhase&1)!=0 ){
108921
+ iPhase++;
108922
+ if( iPhase>3 ) break;
108923
+ }
108924
+ if( !seenVar && iPhase>1 ) break;
108925
+ pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
108926
+ for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
108927
+ j = pIdxCons->iTermOffset;
108928
+ pTerm = &pWC->a[j];
108929
+ switch( iPhase ){
108930
+ case 0: /* Constants without IN operator */
108931
+ pIdxCons->usable = 0;
108932
+ if( (pTerm->eOperator & WO_IN)!=0 ){
108933
+ seenIn = 1;
108934
+ }
108935
+ if( pTerm->prereqRight!=0 ){
108936
+ seenVar = 1;
108937
+ }else if( (pTerm->eOperator & WO_IN)==0 ){
108938
+ pIdxCons->usable = 1;
108939
+ }
108940
+ break;
108941
+ case 1: /* Constants with IN operators */
108942
+ assert( seenIn );
108943
+ pIdxCons->usable = (pTerm->prereqRight==0);
108944
+ break;
108945
+ case 2: /* Variables without IN */
108946
+ assert( seenVar );
108947
+ pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
108948
+ break;
108949
+ default: /* Variables with IN */
108950
+ assert( seenVar && seenIn );
108951
+ pIdxCons->usable = 1;
108952
+ break;
108953
+ }
108954
+ }
108955
+ memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
108956
+ if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
108957
+ pIdxInfo->idxStr = 0;
108958
+ pIdxInfo->idxNum = 0;
108959
+ pIdxInfo->needToFreeIdxStr = 0;
108960
+ pIdxInfo->orderByConsumed = 0;
108961
+ pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
108962
+ rc = vtabBestIndex(pParse, pTab, pIdxInfo);
108963
+ if( rc ) goto whereLoopAddVtab_exit;
108964
+ pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
108965
+ pNew->prereq = 0;
108966
+ mxTerm = -1;
108967
+ assert( pNew->nLSlot>=nConstraint );
108968
+ for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
108969
+ pNew->u.vtab.omitMask = 0;
108970
+ for(i=0; i<nConstraint; i++, pIdxCons++){
108971
+ if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
108972
+ j = pIdxCons->iTermOffset;
108973
+ if( iTerm>=nConstraint
108974
+ || j<0
108975
+ || j>=pWC->nTerm
108976
+ || pNew->aLTerm[iTerm]!=0
108977
+ ){
108978
+ rc = SQLITE_ERROR;
108979
+ sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
108980
+ goto whereLoopAddVtab_exit;
108981
+ }
108982
+ testcase( iTerm==nConstraint-1 );
108983
+ testcase( j==0 );
108984
+ testcase( j==pWC->nTerm-1 );
108985
+ pTerm = &pWC->a[j];
108986
+ pNew->prereq |= pTerm->prereqRight;
108987
+ assert( iTerm<pNew->nLSlot );
108988
+ pNew->aLTerm[iTerm] = pTerm;
108989
+ if( iTerm>mxTerm ) mxTerm = iTerm;
108990
+ testcase( iTerm==15 );
108991
+ testcase( iTerm==16 );
108992
+ if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
108993
+ if( (pTerm->eOperator & WO_IN)!=0 ){
108994
+ if( pUsage[i].omit==0 ){
108995
+ /* Do not attempt to use an IN constraint if the virtual table
108996
+ ** says that the equivalent EQ constraint cannot be safely omitted.
108997
+ ** If we do attempt to use such a constraint, some rows might be
108998
+ ** repeated in the output. */
108999
+ break;
109000
+ }
109001
+ /* A virtual table that is constrained by an IN clause may not
109002
+ ** consume the ORDER BY clause because (1) the order of IN terms
109003
+ ** is not necessarily related to the order of output terms and
109004
+ ** (2) Multiple outputs from a single IN value will not merge
109005
+ ** together. */
109006
+ pIdxInfo->orderByConsumed = 0;
109007
+ }
109008
+ }
109009
+ }
109010
+ if( i>=nConstraint ){
109011
+ pNew->nLTerm = mxTerm+1;
109012
+ assert( pNew->nLTerm<=pNew->nLSlot );
109013
+ pNew->u.vtab.idxNum = pIdxInfo->idxNum;
109014
+ pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
109015
+ pIdxInfo->needToFreeIdxStr = 0;
109016
+ pNew->u.vtab.idxStr = pIdxInfo->idxStr;
109017
+ pNew->u.vtab.isOrdered = (u8)((pIdxInfo->nOrderBy!=0)
109018
+ && pIdxInfo->orderByConsumed);
109019
+ pNew->rSetup = 0;
109020
+ pNew->rRun = whereCostFromDouble(pIdxInfo->estimatedCost);
109021
+ /* TUNING: Every virtual table query returns 25 rows */
109022
+ pNew->nOut = 46; assert( 46==whereCost(25) );
109023
+ whereLoopInsert(pBuilder, pNew);
109024
+ if( pNew->u.vtab.needFree ){
109025
+ sqlite3_free(pNew->u.vtab.idxStr);
109026
+ pNew->u.vtab.needFree = 0;
109027
+ }
109028
+ }
109029
+ }
109030
+
109031
+whereLoopAddVtab_exit:
109032
+ if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
109033
+ sqlite3DbFree(db, pIdxInfo);
109034
+ return rc;
109035
+}
109036
+#endif /* SQLITE_OMIT_VIRTUALTABLE */
109037
+
109038
+/*
109039
+** Add WhereLoop entries to handle OR terms. This works for either
109040
+** btrees or virtual tables.
109041
+*/
109042
+static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){
109043
+ WhereInfo *pWInfo = pBuilder->pWInfo;
109044
+ WhereClause *pWC;
109045
+ WhereLoop *pNew;
109046
+ WhereTerm *pTerm, *pWCEnd;
109047
+ int rc = SQLITE_OK;
109048
+ int iCur;
109049
+ WhereClause tempWC;
109050
+ WhereLoopBuilder sSubBuild;
109051
+ WhereLoop sBest;
109052
+ struct SrcList_item *pItem;
109053
+
109054
+ pWC = pBuilder->pWC;
109055
+ if( pWInfo->wctrlFlags & WHERE_AND_ONLY ) return SQLITE_OK;
109056
+ pWCEnd = pWC->a + pWC->nTerm;
109057
+ pNew = pBuilder->pNew;
109058
+
109059
+ for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
109060
+ if( (pTerm->eOperator & WO_OR)!=0
109061
+ && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
109062
+ ){
109063
+ WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
109064
+ WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
109065
+ WhereTerm *pOrTerm;
109066
+ WhereCost rTotal = 0;
109067
+ WhereCost nRow = 0;
109068
+ Bitmask prereq = mExtra;
109069
+
109070
+ whereLoopInit(&sBest);
109071
+ pItem = pWInfo->pTabList->a + pNew->iTab;
109072
+ iCur = pItem->iCursor;
109073
+ sSubBuild = *pBuilder;
109074
+ sSubBuild.pOrderBy = 0;
109075
+ sSubBuild.pBest = &sBest;
109076
+
109077
+ for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
109078
+ if( (pOrTerm->eOperator & WO_AND)!=0 ){
109079
+ sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
109080
+ }else if( pOrTerm->leftCursor==iCur ){
109081
+ tempWC.pWInfo = pWC->pWInfo;
109082
+ tempWC.pOuter = pWC;
109083
+ tempWC.op = TK_AND;
109084
+ tempWC.nTerm = 1;
109085
+ tempWC.a = pOrTerm;
109086
+ sSubBuild.pWC = &tempWC;
109087
+ }else{
109088
+ continue;
109089
+ }
109090
+ sBest.maskSelf = 0;
109091
+ sBest.rSetup = 0;
109092
+ sBest.rRun = 0;
109093
+#ifndef SQLITE_OMIT_VIRTUALTABLE
109094
+ if( IsVirtual(pItem->pTab) ){
109095
+ rc = whereLoopAddVirtual(&sSubBuild);
109096
+ }else
109097
+#endif
109098
+ {
109099
+ rc = whereLoopAddBtree(&sSubBuild, mExtra);
109100
+ }
109101
+ /* sBest.maskSelf is always zero if an error occurs */
109102
+ assert( rc==SQLITE_OK || sBest.maskSelf==0 );
109103
+ if( sBest.maskSelf==0 ) break;
109104
+ assert( sBest.rSetup==0 );
109105
+ rTotal = whereCostAdd(rTotal, sBest.rRun);
109106
+ nRow = whereCostAdd(nRow, sBest.nOut);
109107
+ prereq |= sBest.prereq;
109108
+ }
109109
+ assert( pNew->nLSlot>=1 );
109110
+ if( sBest.maskSelf ){
109111
+ pNew->nLTerm = 1;
109112
+ pNew->aLTerm[0] = pTerm;
109113
+ pNew->wsFlags = WHERE_MULTI_OR;
109114
+ pNew->rSetup = 0;
109115
+ /* TUNING: Multiple by 3.5 for the secondary table lookup */
109116
+ pNew->rRun = rTotal + 18; assert( 18==whereCost(7)-whereCost(2) );
109117
+ pNew->nOut = nRow;
109118
+ pNew->prereq = prereq;
109119
+ memset(&pNew->u, 0, sizeof(pNew->u));
109120
+ rc = whereLoopInsert(pBuilder, pNew);
109121
+ }
109122
+ whereLoopClear(pWInfo->pParse->db, &sBest);
109123
+ }
109124
+ }
109125
+ return rc;
109126
+}
109127
+
109128
+/*
109129
+** Add all WhereLoop objects for all tables
109130
+*/
109131
+static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
109132
+ WhereInfo *pWInfo = pBuilder->pWInfo;
109133
+ Bitmask mExtra = 0;
109134
+ Bitmask mPrior = 0;
109135
+ int iTab;
109136
+ SrcList *pTabList = pWInfo->pTabList;
109137
+ struct SrcList_item *pItem;
109138
+ sqlite3 *db = pWInfo->pParse->db;
109139
+ int nTabList = pWInfo->nLevel;
109140
+ int rc = SQLITE_OK;
109141
+ u8 priorJoinType = 0;
109142
+ WhereLoop *pNew;
109143
+
109144
+ /* Loop over the tables in the join, from left to right */
109145
+ pNew = pBuilder->pNew;
109146
+ whereLoopInit(pNew);
109147
+ for(iTab=0, pItem=pTabList->a; iTab<nTabList; iTab++, pItem++){
109148
+ pNew->iTab = iTab;
109149
+ pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor);
109150
+ if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){
109151
+ mExtra = mPrior;
109152
+ }
109153
+ priorJoinType = pItem->jointype;
109154
+ if( IsVirtual(pItem->pTab) ){
109155
+ rc = whereLoopAddVirtual(pBuilder);
109156
+ }else{
109157
+ rc = whereLoopAddBtree(pBuilder, mExtra);
109158
+ }
109159
+ if( rc==SQLITE_OK ){
109160
+ rc = whereLoopAddOr(pBuilder, mExtra);
109161
+ }
109162
+ mPrior |= pNew->maskSelf;
109163
+ if( rc || db->mallocFailed ) break;
109164
+ }
109165
+ whereLoopClear(db, pNew);
109166
+ return rc;
109167
+}
109168
+
109169
+/*
109170
+** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
109171
+** parameters) to see if it outputs rows in the requested ORDER BY
109172
+** (or GROUP BY) without requiring a separate source operation. Return:
109173
+**
109174
+** 0: ORDER BY is not satisfied. Sorting required
109175
+** 1: ORDER BY is satisfied. Omit sorting
109176
+** -1: Unknown at this time
109177
+**
109178
+*/
109179
+static int wherePathSatisfiesOrderBy(
109180
+ WhereInfo *pWInfo, /* The WHERE clause */
109181
+ ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
109182
+ WherePath *pPath, /* The WherePath to check */
109183
+ u16 wctrlFlags, /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
109184
+ u16 nLoop, /* Number of entries in pPath->aLoop[] */
109185
+ WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
109186
+ Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
109187
+){
109188
+ u8 revSet; /* True if rev is known */
109189
+ u8 rev; /* Composite sort order */
109190
+ u8 revIdx; /* Index sort order */
109191
+ u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
109192
+ u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
109193
+ u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
109194
+ u16 nColumn; /* Number of columns in pIndex */
109195
+ u16 nOrderBy; /* Number terms in the ORDER BY clause */
109196
+ int iLoop; /* Index of WhereLoop in pPath being processed */
109197
+ int i, j; /* Loop counters */
109198
+ int iCur; /* Cursor number for current WhereLoop */
109199
+ int iColumn; /* A column number within table iCur */
109200
+ WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
109201
+ WhereTerm *pTerm; /* A single term of the WHERE clause */
109202
+ Expr *pOBExpr; /* An expression from the ORDER BY clause */
109203
+ CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
109204
+ Index *pIndex; /* The index associated with pLoop */
109205
+ sqlite3 *db = pWInfo->pParse->db; /* Database connection */
109206
+ Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
109207
+ Bitmask obDone; /* Mask of all ORDER BY terms */
109208
+ Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
109209
+ Bitmask ready; /* Mask of inner loops */
109210
+
109211
+ /*
109212
+ ** We say the WhereLoop is "one-row" if it generates no more than one
109213
+ ** row of output. A WhereLoop is one-row if all of the following are true:
109214
+ ** (a) All index columns match with WHERE_COLUMN_EQ.
109215
+ ** (b) The index is unique
109216
+ ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
109217
+ ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
109218
+ **
109219
+ ** We say the WhereLoop is "order-distinct" if the set of columns from
109220
+ ** that WhereLoop that are in the ORDER BY clause are different for every
109221
+ ** row of the WhereLoop. Every one-row WhereLoop is automatically
109222
+ ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
109223
+ ** is not order-distinct. To be order-distinct is not quite the same as being
109224
+ ** UNIQUE since a UNIQUE column or index can have multiple rows that
109225
+ ** are NULL and NULL values are equivalent for the purpose of order-distinct.
109226
+ ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
109227
+ **
109228
+ ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
109229
+ ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
109230
+ ** automatically order-distinct.
109231
+ */
109232
+
109233
+ assert( pOrderBy!=0 );
109234
+
109235
+ /* Sortability of virtual tables is determined by the xBestIndex method
109236
+ ** of the virtual table itself */
109237
+ if( pLast->wsFlags & WHERE_VIRTUALTABLE ){
109238
+ testcase( nLoop>0 ); /* True when outer loops are one-row and match
109239
+ ** no ORDER BY terms */
109240
+ return pLast->u.vtab.isOrdered;
109241
+ }
109242
+ if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
109243
+
109244
+ nOrderBy = pOrderBy->nExpr;
109245
+ testcase( nOrderBy==BMS-1 );
109246
+ if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
109247
+ isOrderDistinct = 1;
109248
+ obDone = MASKBIT(nOrderBy)-1;
109249
+ orderDistinctMask = 0;
109250
+ ready = 0;
109251
+ for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
109252
+ if( iLoop>0 ) ready |= pLoop->maskSelf;
109253
+ pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
109254
+ assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
109255
+ iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
109256
+
109257
+ /* Mark off any ORDER BY term X that is a column in the table of
109258
+ ** the current loop for which there is term in the WHERE
109259
+ ** clause of the form X IS NULL or X=? that reference only outer
109260
+ ** loops.
109261
+ */
109262
+ for(i=0; i<nOrderBy; i++){
109263
+ if( MASKBIT(i) & obSat ) continue;
109264
+ pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
109265
+ if( pOBExpr->op!=TK_COLUMN ) continue;
109266
+ if( pOBExpr->iTable!=iCur ) continue;
109267
+ pTerm = findTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
109268
+ ~ready, WO_EQ|WO_ISNULL, 0);
109269
+ if( pTerm==0 ) continue;
109270
+ if( (pTerm->eOperator&WO_EQ)!=0 && pOBExpr->iColumn>=0 ){
109271
+ const char *z1, *z2;
109272
+ pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
109273
+ if( !pColl ) pColl = db->pDfltColl;
109274
+ z1 = pColl->zName;
109275
+ pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
109276
+ if( !pColl ) pColl = db->pDfltColl;
109277
+ z2 = pColl->zName;
109278
+ if( sqlite3StrICmp(z1, z2)!=0 ) continue;
109279
+ }
109280
+ obSat |= MASKBIT(i);
109281
+ }
109282
+
109283
+ if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
109284
+ if( pLoop->wsFlags & WHERE_IPK ){
109285
+ pIndex = 0;
109286
+ nColumn = 0;
109287
+ }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
109288
+ return 0;
109289
+ }else{
109290
+ nColumn = pIndex->nColumn;
109291
+ isOrderDistinct = pIndex->onError!=OE_None;
109292
+ }
109293
+
109294
+ /* Loop through all columns of the index and deal with the ones
109295
+ ** that are not constrained by == or IN.
109296
+ */
109297
+ rev = revSet = 0;
109298
+ distinctColumns = 0;
109299
+ for(j=0; j<=nColumn; j++){
109300
+ u8 bOnce; /* True to run the ORDER BY search loop */
109301
+
109302
+ /* Skip over == and IS NULL terms */
109303
+ if( j<pLoop->u.btree.nEq
109304
+ && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL))!=0
109305
+ ){
109306
+ if( i & WO_ISNULL ){
109307
+ testcase( isOrderDistinct );
109308
+ isOrderDistinct = 0;
109309
+ }
109310
+ continue;
109311
+ }
109312
+
109313
+ /* Get the column number in the table (iColumn) and sort order
109314
+ ** (revIdx) for the j-th column of the index.
109315
+ */
109316
+ if( j<nColumn ){
109317
+ /* Normal index columns */
109318
+ iColumn = pIndex->aiColumn[j];
109319
+ revIdx = pIndex->aSortOrder[j];
109320
+ if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
109321
+ }else{
109322
+ /* The ROWID column at the end */
109323
+ assert( j==nColumn );
109324
+ iColumn = -1;
109325
+ revIdx = 0;
109326
+ }
109327
+
109328
+ /* An unconstrained column that might be NULL means that this
109329
+ ** WhereLoop is not well-ordered
109330
+ */
109331
+ if( isOrderDistinct
109332
+ && iColumn>=0
109333
+ && j>=pLoop->u.btree.nEq
109334
+ && pIndex->pTable->aCol[iColumn].notNull==0
109335
+ ){
109336
+ isOrderDistinct = 0;
109337
+ }
109338
+
109339
+ /* Find the ORDER BY term that corresponds to the j-th column
109340
+ ** of the index and and mark that ORDER BY term off
109341
+ */
109342
+ bOnce = 1;
109343
+ isMatch = 0;
109344
+ for(i=0; bOnce && i<nOrderBy; i++){
109345
+ if( MASKBIT(i) & obSat ) continue;
109346
+ pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
109347
+ testcase( wctrlFlags & WHERE_GROUPBY );
109348
+ testcase( wctrlFlags & WHERE_DISTINCTBY );
109349
+ if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
109350
+ if( pOBExpr->op!=TK_COLUMN ) continue;
109351
+ if( pOBExpr->iTable!=iCur ) continue;
109352
+ if( pOBExpr->iColumn!=iColumn ) continue;
109353
+ if( iColumn>=0 ){
109354
+ pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
109355
+ if( !pColl ) pColl = db->pDfltColl;
109356
+ if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
109357
+ }
109358
+ isMatch = 1;
109359
+ break;
109360
+ }
109361
+ if( isMatch ){
109362
+ if( iColumn<0 ){
109363
+ testcase( distinctColumns==0 );
109364
+ distinctColumns = 1;
109365
+ }
109366
+ obSat |= MASKBIT(i);
109367
+ if( (pWInfo->wctrlFlags & WHERE_GROUPBY)==0 ){
109368
+ /* Make sure the sort order is compatible in an ORDER BY clause.
109369
+ ** Sort order is irrelevant for a GROUP BY clause. */
109370
+ if( revSet ){
109371
+ if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) return 0;
109372
+ }else{
109373
+ rev = revIdx ^ pOrderBy->a[i].sortOrder;
109374
+ if( rev ) *pRevMask |= MASKBIT(iLoop);
109375
+ revSet = 1;
109376
+ }
109377
+ }
109378
+ }else{
109379
+ /* No match found */
109380
+ if( j==0 || j<nColumn ){
109381
+ testcase( isOrderDistinct!=0 );
109382
+ isOrderDistinct = 0;
109383
+ }
109384
+ break;
109385
+ }
109386
+ } /* end Loop over all index columns */
109387
+ if( distinctColumns ){
109388
+ testcase( isOrderDistinct==0 );
109389
+ isOrderDistinct = 1;
109390
+ }
109391
+ } /* end-if not one-row */
109392
+
109393
+ /* Mark off any other ORDER BY terms that reference pLoop */
109394
+ if( isOrderDistinct ){
109395
+ orderDistinctMask |= pLoop->maskSelf;
109396
+ for(i=0; i<nOrderBy; i++){
109397
+ Expr *p;
109398
+ if( MASKBIT(i) & obSat ) continue;
109399
+ p = pOrderBy->a[i].pExpr;
109400
+ if( (exprTableUsage(&pWInfo->sMaskSet, p)&~orderDistinctMask)==0 ){
109401
+ obSat |= MASKBIT(i);
109402
+ }
109403
+ }
109404
+ }
109405
+ } /* End the loop over all WhereLoops from outer-most down to inner-most */
109406
+ if( obSat==obDone ) return 1;
109407
+ if( !isOrderDistinct ) return 0;
109408
+ return -1;
109409
+}
109410
+
109411
+#ifdef WHERETRACE_ENABLED
109412
+/* For debugging use only: */
109413
+static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
109414
+ static char zName[65];
109415
+ int i;
109416
+ for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
109417
+ if( pLast ) zName[i++] = pLast->cId;
109418
+ zName[i] = 0;
109419
+ return zName;
109420
+}
109421
+#endif
109422
+
109423
+
109424
+/*
109425
+** Given the list of WhereLoop objects on pWInfo->pLoops, this routine
109426
+** attempts to find the lowest cost path that visits each WhereLoop
109427
+** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
109428
+**
109429
+** Assume that the total number of output rows that will need to be sorted
109430
+** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
109431
+** costs if nRowEst==0.
109432
+**
109433
+** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
109434
+** error occurs.
109435
+*/
109436
+static int wherePathSolver(WhereInfo *pWInfo, WhereCost nRowEst){
109437
+ int mxChoice; /* Maximum number of simultaneous paths tracked */
109438
+ int nLoop; /* Number of terms in the join */
109439
+ Parse *pParse; /* Parsing context */
109440
+ sqlite3 *db; /* The database connection */
109441
+ int iLoop; /* Loop counter over the terms of the join */
109442
+ int ii, jj; /* Loop counters */
109443
+ WhereCost rCost; /* Cost of a path */
109444
+ WhereCost mxCost = 0; /* Maximum cost of a set of paths */
109445
+ WhereCost rSortCost; /* Cost to do a sort */
109446
+ int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
109447
+ WherePath *aFrom; /* All nFrom paths at the previous level */
109448
+ WherePath *aTo; /* The nTo best paths at the current level */
109449
+ WherePath *pFrom; /* An element of aFrom[] that we are working on */
109450
+ WherePath *pTo; /* An element of aTo[] that we are working on */
109451
+ WhereLoop *pWLoop; /* One of the WhereLoop objects */
109452
+ WhereLoop **pX; /* Used to divy up the pSpace memory */
109453
+ char *pSpace; /* Temporary memory used by this routine */
109454
+
109455
+ pParse = pWInfo->pParse;
109456
+ db = pParse->db;
109457
+ nLoop = pWInfo->nLevel;
109458
+ /* TUNING: For simple queries, only the best path is tracked.
109459
+ ** For 2-way joins, the 5 best paths are followed.
109460
+ ** For joins of 3 or more tables, track the 10 best paths */
109461
+ mxChoice = (nLoop==1) ? 1 : (nLoop==2 ? 5 : 10);
109462
+ assert( nLoop<=pWInfo->pTabList->nSrc );
109463
+ WHERETRACE(0x002, ("---- begin solver\n"));
109464
+
109465
+ /* Allocate and initialize space for aTo and aFrom */
109466
+ ii = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
109467
+ pSpace = sqlite3DbMallocRaw(db, ii);
109468
+ if( pSpace==0 ) return SQLITE_NOMEM;
109469
+ aTo = (WherePath*)pSpace;
109470
+ aFrom = aTo+mxChoice;
109471
+ memset(aFrom, 0, sizeof(aFrom[0]));
109472
+ pX = (WhereLoop**)(aFrom+mxChoice);
109473
+ for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
109474
+ pFrom->aLoop = pX;
109475
+ }
109476
+
109477
+ /* Seed the search with a single WherePath containing zero WhereLoops.
109478
+ **
109479
+ ** TUNING: Do not let the number of iterations go above 25. If the cost
109480
+ ** of computing an automatic index is not paid back within the first 25
109481
+ ** rows, then do not use the automatic index. */
109482
+ aFrom[0].nRow = MIN(pParse->nQueryLoop, 46); assert( 46==whereCost(25) );
109483
+ nFrom = 1;
109484
+
109485
+ /* Precompute the cost of sorting the final result set, if the caller
109486
+ ** to sqlite3WhereBegin() was concerned about sorting */
109487
+ rSortCost = 0;
109488
+ if( pWInfo->pOrderBy==0 || nRowEst==0 ){
109489
+ aFrom[0].isOrderedValid = 1;
109490
+ }else{
109491
+ /* TUNING: Estimated cost of sorting is N*log2(N) where N is the
109492
+ ** number of output rows. */
109493
+ rSortCost = nRowEst + estLog(nRowEst);
109494
+ WHERETRACE(0x002,("---- sort cost=%-3d\n", rSortCost));
109495
+ }
109496
+
109497
+ /* Compute successively longer WherePaths using the previous generation
109498
+ ** of WherePaths as the basis for the next. Keep track of the mxChoice
109499
+ ** best paths at each generation */
109500
+ for(iLoop=0; iLoop<nLoop; iLoop++){
109501
+ nTo = 0;
109502
+ for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
109503
+ for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
109504
+ Bitmask maskNew;
109505
+ Bitmask revMask = 0;
109506
+ u8 isOrderedValid = pFrom->isOrderedValid;
109507
+ u8 isOrdered = pFrom->isOrdered;
109508
+ if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
109509
+ if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
109510
+ /* At this point, pWLoop is a candidate to be the next loop.
109511
+ ** Compute its cost */
109512
+ rCost = whereCostAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
109513
+ rCost = whereCostAdd(rCost, pFrom->rCost);
109514
+ maskNew = pFrom->maskLoop | pWLoop->maskSelf;
109515
+ if( !isOrderedValid ){
109516
+ switch( wherePathSatisfiesOrderBy(pWInfo,
109517
+ pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
109518
+ iLoop, pWLoop, &revMask) ){
109519
+ case 1: /* Yes. pFrom+pWLoop does satisfy the ORDER BY clause */
109520
+ isOrdered = 1;
109521
+ isOrderedValid = 1;
109522
+ break;
109523
+ case 0: /* No. pFrom+pWLoop will require a separate sort */
109524
+ isOrdered = 0;
109525
+ isOrderedValid = 1;
109526
+ rCost = whereCostAdd(rCost, rSortCost);
109527
+ break;
109528
+ default: /* Cannot tell yet. Try again on the next iteration */
109529
+ break;
109530
+ }
109531
+ }else{
109532
+ revMask = pFrom->revLoop;
109533
+ }
109534
+ /* Check to see if pWLoop should be added to the mxChoice best so far */
109535
+ for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
109536
+ if( pTo->maskLoop==maskNew && pTo->isOrderedValid==isOrderedValid ){
109537
+ testcase( jj==nTo-1 );
109538
+ break;
109539
+ }
109540
+ }
109541
+ if( jj>=nTo ){
109542
+ if( nTo>=mxChoice && rCost>=mxCost ){
109543
+#ifdef WHERETRACE_ENABLED
109544
+ if( sqlite3WhereTrace&0x4 ){
109545
+ sqlite3DebugPrintf("Skip %s cost=%3d order=%c\n",
109546
+ wherePathName(pFrom, iLoop, pWLoop), rCost,
109547
+ isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
109548
+ }
109549
+#endif
109550
+ continue;
109551
+ }
109552
+ /* Add a new Path to the aTo[] set */
109553
+ if( nTo<mxChoice ){
109554
+ /* Increase the size of the aTo set by one */
109555
+ jj = nTo++;
109556
+ }else{
109557
+ /* New path replaces the prior worst to keep count below mxChoice */
109558
+ for(jj=nTo-1; aTo[jj].rCost<mxCost; jj--){ assert(jj>0); }
109559
+ }
109560
+ pTo = &aTo[jj];
109561
+#ifdef WHERETRACE_ENABLED
109562
+ if( sqlite3WhereTrace&0x4 ){
109563
+ sqlite3DebugPrintf("New %s cost=%-3d order=%c\n",
109564
+ wherePathName(pFrom, iLoop, pWLoop), rCost,
109565
+ isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
109566
+ }
109567
+#endif
109568
+ }else{
109569
+ if( pTo->rCost<=rCost ){
109570
+#ifdef WHERETRACE_ENABLED
109571
+ if( sqlite3WhereTrace&0x4 ){
109572
+ sqlite3DebugPrintf(
109573
+ "Skip %s cost=%-3d order=%c",
109574
+ wherePathName(pFrom, iLoop, pWLoop), rCost,
109575
+ isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
109576
+ sqlite3DebugPrintf(" vs %s cost=%-3d order=%c\n",
109577
+ wherePathName(pTo, iLoop+1, 0), pTo->rCost,
109578
+ pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
109579
+ }
109580
+#endif
109581
+ testcase( pTo->rCost==rCost );
109582
+ continue;
109583
+ }
109584
+ testcase( pTo->rCost==rCost+1 );
109585
+ /* A new and better score for a previously created equivalent path */
109586
+#ifdef WHERETRACE_ENABLED
109587
+ if( sqlite3WhereTrace&0x4 ){
109588
+ sqlite3DebugPrintf(
109589
+ "Update %s cost=%-3d order=%c",
109590
+ wherePathName(pFrom, iLoop, pWLoop), rCost,
109591
+ isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
109592
+ sqlite3DebugPrintf(" was %s cost=%-3d order=%c\n",
109593
+ wherePathName(pTo, iLoop+1, 0), pTo->rCost,
109594
+ pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
109595
+ }
109596
+#endif
109597
+ }
109598
+ /* pWLoop is a winner. Add it to the set of best so far */
109599
+ pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
109600
+ pTo->revLoop = revMask;
109601
+ pTo->nRow = pFrom->nRow + pWLoop->nOut;
109602
+ pTo->rCost = rCost;
109603
+ pTo->isOrderedValid = isOrderedValid;
109604
+ pTo->isOrdered = isOrdered;
109605
+ memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
109606
+ pTo->aLoop[iLoop] = pWLoop;
109607
+ if( nTo>=mxChoice ){
109608
+ mxCost = aTo[0].rCost;
109609
+ for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
109610
+ if( pTo->rCost>mxCost ) mxCost = pTo->rCost;
109611
+ }
109612
+ }
109613
+ }
109614
+ }
109615
+
109616
+#ifdef WHERETRACE_ENABLED
109617
+ if( sqlite3WhereTrace>=2 ){
109618
+ sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
109619
+ for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
109620
+ sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
109621
+ wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
109622
+ pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
109623
+ if( pTo->isOrderedValid && pTo->isOrdered ){
109624
+ sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
109625
+ }else{
109626
+ sqlite3DebugPrintf("\n");
109627
+ }
109628
+ }
109629
+ }
109630
+#endif
109631
+
109632
+ /* Swap the roles of aFrom and aTo for the next generation */
109633
+ pFrom = aTo;
109634
+ aTo = aFrom;
109635
+ aFrom = pFrom;
109636
+ nFrom = nTo;
109637
+ }
109638
+
109639
+ if( nFrom==0 ){
109640
+ sqlite3ErrorMsg(pParse, "no query solution");
109641
+ sqlite3DbFree(db, pSpace);
109642
+ return SQLITE_ERROR;
109643
+ }
109644
+
109645
+ /* Find the lowest cost path. pFrom will be left pointing to that path */
109646
+ pFrom = aFrom;
109647
+ assert( nFrom==1 );
109648
+#if 0 /* The following is needed if nFrom is ever more than 1 */
109649
+ for(ii=1; ii<nFrom; ii++){
109650
+ if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
109651
+ }
109652
+#endif
109653
+ assert( pWInfo->nLevel==nLoop );
109654
+ /* Load the lowest cost path into pWInfo */
109655
+ for(iLoop=0; iLoop<nLoop; iLoop++){
109656
+ WhereLevel *pLevel = pWInfo->a + iLoop;
109657
+ pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
109658
+ pLevel->iFrom = pWLoop->iTab;
109659
+ pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
109660
+ }
109661
+ if( (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
109662
+ && pWInfo->pDistinct
109663
+ && nRowEst
109664
+ ){
109665
+ Bitmask notUsed;
109666
+ int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pDistinct, pFrom,
109667
+ WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
109668
+ if( rc==1 ) pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
109669
+ }
109670
+ if( pFrom->isOrdered ){
109671
+ if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
109672
+ pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
109673
+ }else{
109674
+ pWInfo->bOBSat = 1;
109675
+ pWInfo->revMask = pFrom->revLoop;
109676
+ }
109677
+ }
109678
+ pWInfo->nRowOut = pFrom->nRow;
109679
+
109680
+ /* Free temporary memory and return success */
109681
+ sqlite3DbFree(db, pSpace);
109682
+ return SQLITE_OK;
109683
+}
109684
+
109685
+/*
109686
+** Most queries use only a single table (they are not joins) and have
109687
+** simple == constraints against indexed fields. This routine attempts
109688
+** to plan those simple cases using much less ceremony than the
109689
+** general-purpose query planner, and thereby yield faster sqlite3_prepare()
109690
+** times for the common case.
109691
+**
109692
+** Return non-zero on success, if this query can be handled by this
109693
+** no-frills query planner. Return zero if this query needs the
109694
+** general-purpose query planner.
109695
+*/
109696
+static int whereShortCut(WhereLoopBuilder *pBuilder){
109697
+ WhereInfo *pWInfo;
109698
+ struct SrcList_item *pItem;
109699
+ WhereClause *pWC;
109700
+ WhereTerm *pTerm;
109701
+ WhereLoop *pLoop;
109702
+ int iCur;
109703
+ int j;
109704
+ Table *pTab;
109705
+ Index *pIdx;
109706
+
109707
+ pWInfo = pBuilder->pWInfo;
109708
+ if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
109709
+ assert( pWInfo->pTabList->nSrc>=1 );
109710
+ pItem = pWInfo->pTabList->a;
109711
+ pTab = pItem->pTab;
109712
+ if( IsVirtual(pTab) ) return 0;
109713
+ if( pItem->zIndex ) return 0;
109714
+ iCur = pItem->iCursor;
109715
+ pWC = &pWInfo->sWC;
109716
+ pLoop = pBuilder->pNew;
109717
+ pLoop->wsFlags = 0;
109718
+ pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ, 0);
109719
+ if( pTerm ){
109720
+ pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
109721
+ pLoop->aLTerm[0] = pTerm;
109722
+ pLoop->nLTerm = 1;
109723
+ pLoop->u.btree.nEq = 1;
109724
+ /* TUNING: Cost of a rowid lookup is 10 */
109725
+ pLoop->rRun = 33; /* 33==whereCost(10) */
109726
+ }else{
109727
+ for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
109728
+ if( pIdx->onError==OE_None ) continue;
109729
+ for(j=0; j<pIdx->nColumn; j++){
109730
+ pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx);
109731
+ if( pTerm==0 ) break;
109732
+ whereLoopResize(pWInfo->pParse->db, pLoop, j);
109733
+ pLoop->aLTerm[j] = pTerm;
109734
+ }
109735
+ if( j!=pIdx->nColumn ) continue;
109736
+ pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
109737
+ if( (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
109738
+ pLoop->wsFlags |= WHERE_IDX_ONLY;
109739
+ }
109740
+ pLoop->nLTerm = j;
109741
+ pLoop->u.btree.nEq = j;
109742
+ pLoop->u.btree.pIndex = pIdx;
109743
+ /* TUNING: Cost of a unique index lookup is 15 */
109744
+ pLoop->rRun = 39; /* 39==whereCost(15) */
109745
+ break;
109746
+ }
109747
+ }
109748
+ if( pLoop->wsFlags ){
109749
+ pLoop->nOut = (WhereCost)1;
109750
+ pWInfo->a[0].pWLoop = pLoop;
109751
+ pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur);
109752
+ pWInfo->a[0].iTabCur = iCur;
109753
+ pWInfo->nRowOut = 1;
109754
+ if( pWInfo->pOrderBy ) pWInfo->bOBSat = 1;
109755
+ if( pWInfo->pDistinct ) pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
109756
+#ifdef SQLITE_DEBUG
109757
+ pLoop->cId = '0';
109758
+#endif
109759
+ return 1;
109760
+ }
109761
+ return 0;
109762
+}
109336109763
109337109764
/*
109338109765
** Generate the beginning of the loop used for WHERE clause processing.
109339109766
** The return value is a pointer to an opaque structure that contains
109340109767
** information needed to terminate the loop. Later, the calling routine
@@ -109410,19 +109837,10 @@
109410109837
** ORDER BY CLAUSE PROCESSING
109411109838
**
109412109839
** pOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
109413109840
** if there is one. If there is no ORDER BY clause or if this routine
109414109841
** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
109415
-**
109416
-** If an index can be used so that the natural output order of the table
109417
-** scan is correct for the ORDER BY clause, then that index is used and
109418
-** the returned WhereInfo.nOBSat field is set to pOrderBy->nExpr. This
109419
-** is an optimization that prevents an unnecessary sort of the result set
109420
-** if an index appropriate for the ORDER BY clause already exists.
109421
-**
109422
-** If the where clause loops cannot be arranged to provide the correct
109423
-** output order, then WhereInfo.nOBSat is 0.
109424109842
*/
109425109843
SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
109426109844
Parse *pParse, /* The parser context */
109427109845
SrcList *pTabList, /* A list of all tables to be scanned */
109428109846
Expr *pWhere, /* The WHERE clause */
@@ -109434,22 +109852,21 @@
109434109852
int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
109435109853
int nTabList; /* Number of elements in pTabList */
109436109854
WhereInfo *pWInfo; /* Will become the return value of this function */
109437109855
Vdbe *v = pParse->pVdbe; /* The virtual database engine */
109438109856
Bitmask notReady; /* Cursors that are not yet positioned */
109439
- WhereBestIdx sWBI; /* Best index search context */
109857
+ WhereLoopBuilder sWLB; /* The WhereLoop builder */
109440109858
WhereMaskSet *pMaskSet; /* The expression mask set */
109441109859
WhereLevel *pLevel; /* A single level in pWInfo->a[] */
109442
- int iFrom; /* First unused FROM clause element */
109443
- int andFlags; /* AND-ed combination of all pWC->a[].wtFlags */
109444109860
int ii; /* Loop counter */
109445109861
sqlite3 *db; /* Database connection */
109862
+ int rc; /* Return code */
109446109863
109447109864
109448109865
/* Variable initialization */
109449
- memset(&sWBI, 0, sizeof(sWBI));
109450
- sWBI.pParse = pParse;
109866
+ memset(&sWLB, 0, sizeof(sWLB));
109867
+ sWLB.pOrderBy = pOrderBy;
109451109868
109452109869
/* The number of tables in the FROM clause is limited by the number of
109453109870
** bits in a Bitmask
109454109871
*/
109455109872
testcase( pTabList->nSrc==BMS );
@@ -109472,49 +109889,59 @@
109472109889
** field (type Bitmask) it must be aligned on an 8-byte boundary on
109473109890
** some architectures. Hence the ROUND8() below.
109474109891
*/
109475109892
db = pParse->db;
109476109893
nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
109477
- pWInfo = sqlite3DbMallocZero(db,
109478
- nByteWInfo +
109479
- sizeof(WhereClause) +
109480
- sizeof(WhereMaskSet)
109481
- );
109894
+ pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
109482109895
if( db->mallocFailed ){
109483109896
sqlite3DbFree(db, pWInfo);
109484109897
pWInfo = 0;
109485109898
goto whereBeginError;
109486109899
}
109487109900
pWInfo->nLevel = nTabList;
109488109901
pWInfo->pParse = pParse;
109489109902
pWInfo->pTabList = pTabList;
109903
+ pWInfo->pOrderBy = pOrderBy;
109904
+ pWInfo->pDistinct = pDistinct;
109490109905
pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
109491
- pWInfo->pWC = sWBI.pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
109492109906
pWInfo->wctrlFlags = wctrlFlags;
109493109907
pWInfo->savedNQueryLoop = pParse->nQueryLoop;
109494
- pMaskSet = (WhereMaskSet*)&sWBI.pWC[1];
109495
- sWBI.aLevel = pWInfo->a;
109908
+ pMaskSet = &pWInfo->sMaskSet;
109909
+ sWLB.pWInfo = pWInfo;
109910
+ sWLB.pWC = &pWInfo->sWC;
109911
+ sWLB.pNew = (WhereLoop*)&pWInfo->a[nTabList];
109912
+ whereLoopInit(sWLB.pNew);
109913
+#ifdef SQLITE_DEBUG
109914
+ sWLB.pNew->cId = '*';
109915
+#endif
109496109916
109497109917
/* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
109498109918
** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
109499109919
if( OptimizationDisabled(db, SQLITE_DistinctOpt) ) pDistinct = 0;
109500109920
109501109921
/* Split the WHERE clause into separate subexpressions where each
109502109922
** subexpression is separated by an AND operator.
109503109923
*/
109504109924
initMaskSet(pMaskSet);
109505
- whereClauseInit(sWBI.pWC, pParse, pMaskSet, wctrlFlags);
109925
+ whereClauseInit(&pWInfo->sWC, pWInfo);
109506109926
sqlite3ExprCodeConstants(pParse, pWhere);
109507
- whereSplit(sWBI.pWC, pWhere, TK_AND); /* IMP: R-15842-53296 */
109927
+ whereSplit(&pWInfo->sWC, pWhere, TK_AND); /* IMP: R-15842-53296 */
109508109928
109509109929
/* Special case: a WHERE clause that is constant. Evaluate the
109510109930
** expression and either jump over all of the code or fall thru.
109511109931
*/
109512109932
if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
109513109933
sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
109514109934
pWhere = 0;
109515109935
}
109936
+
109937
+ /* Special case: No FROM clause
109938
+ */
109939
+ if( nTabList==0 ){
109940
+ if( pOrderBy ) pWInfo->bOBSat = 1;
109941
+ if( pDistinct ) pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
109942
+ }
109516109943
109517109944
/* Assign a bit from the bitmask to every term in the FROM clause.
109518109945
**
109519109946
** When assigning bitmask values to FROM clause cursors, it must be
109520109947
** the case that if X is the bitmask for the N-th FROM clause term then
@@ -109547,337 +109974,153 @@
109547109974
/* Analyze all of the subexpressions. Note that exprAnalyze() might
109548109975
** add new virtual terms onto the end of the WHERE clause. We do not
109549109976
** want to analyze these virtual terms, so start analyzing at the end
109550109977
** and work forward so that the added virtual terms are never processed.
109551109978
*/
109552
- exprAnalyzeAll(pTabList, sWBI.pWC);
109979
+ exprAnalyzeAll(pTabList, &pWInfo->sWC);
109553109980
if( db->mallocFailed ){
109554109981
goto whereBeginError;
109555109982
}
109983
+
109984
+ /* If the ORDER BY (or GROUP BY) clause contains references to general
109985
+ ** expressions, then we won't be able to satisfy it using indices, so
109986
+ ** go ahead and disable it now.
109987
+ */
109988
+ if( pOrderBy && pDistinct ){
109989
+ for(ii=0; ii<pOrderBy->nExpr; ii++){
109990
+ Expr *pExpr = sqlite3ExprSkipCollate(pOrderBy->a[ii].pExpr);
109991
+ if( pExpr->op!=TK_COLUMN ){
109992
+ pWInfo->pOrderBy = pOrderBy = 0;
109993
+ break;
109994
+ }else if( pExpr->iColumn<0 ){
109995
+ break;
109996
+ }
109997
+ }
109998
+ }
109556109999
109557110000
/* Check if the DISTINCT qualifier, if there is one, is redundant.
109558110001
** If it is, then set pDistinct to NULL and WhereInfo.eDistinct to
109559110002
** WHERE_DISTINCT_UNIQUE to tell the caller to ignore the DISTINCT.
109560110003
*/
109561
- if( pDistinct && isDistinctRedundant(pParse, pTabList, sWBI.pWC, pDistinct) ){
109562
- pDistinct = 0;
109563
- pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
109564
- }
109565
-
109566
- /* Chose the best index to use for each table in the FROM clause.
109567
- **
109568
- ** This loop fills in the following fields:
109569
- **
109570
- ** pWInfo->a[].pIdx The index to use for this level of the loop.
109571
- ** pWInfo->a[].wsFlags WHERE_xxx flags associated with pIdx
109572
- ** pWInfo->a[].nEq The number of == and IN constraints
109573
- ** pWInfo->a[].iFrom Which term of the FROM clause is being coded
109574
- ** pWInfo->a[].iTabCur The VDBE cursor for the database table
109575
- ** pWInfo->a[].iIdxCur The VDBE cursor for the index
109576
- ** pWInfo->a[].pTerm When wsFlags==WO_OR, the OR-clause term
109577
- **
109578
- ** This loop also figures out the nesting order of tables in the FROM
109579
- ** clause.
109580
- */
109581
- sWBI.notValid = ~(Bitmask)0;
109582
- sWBI.pOrderBy = pOrderBy;
109583
- sWBI.n = nTabList;
109584
- sWBI.pDistinct = pDistinct;
109585
- andFlags = ~0;
109586
- WHERETRACE(("*** Optimizer Start ***\n"));
109587
- for(sWBI.i=iFrom=0, pLevel=pWInfo->a; sWBI.i<nTabList; sWBI.i++, pLevel++){
109588
- WhereCost bestPlan; /* Most efficient plan seen so far */
109589
- Index *pIdx; /* Index for FROM table at pTabItem */
109590
- int j; /* For looping over FROM tables */
109591
- int bestJ = -1; /* The value of j */
109592
- Bitmask m; /* Bitmask value for j or bestJ */
109593
- int isOptimal; /* Iterator for optimal/non-optimal search */
109594
- int ckOptimal; /* Do the optimal scan check */
109595
- int nUnconstrained; /* Number tables without INDEXED BY */
109596
- Bitmask notIndexed; /* Mask of tables that cannot use an index */
109597
-
109598
- memset(&bestPlan, 0, sizeof(bestPlan));
109599
- bestPlan.rCost = SQLITE_BIG_DBL;
109600
- WHERETRACE(("*** Begin search for loop %d ***\n", sWBI.i));
109601
-
109602
- /* Loop through the remaining entries in the FROM clause to find the
109603
- ** next nested loop. The loop tests all FROM clause entries
109604
- ** either once or twice.
109605
- **
109606
- ** The first test is always performed if there are two or more entries
109607
- ** remaining and never performed if there is only one FROM clause entry
109608
- ** to choose from. The first test looks for an "optimal" scan. In
109609
- ** this context an optimal scan is one that uses the same strategy
109610
- ** for the given FROM clause entry as would be selected if the entry
109611
- ** were used as the innermost nested loop. In other words, a table
109612
- ** is chosen such that the cost of running that table cannot be reduced
109613
- ** by waiting for other tables to run first. This "optimal" test works
109614
- ** by first assuming that the FROM clause is on the inner loop and finding
109615
- ** its query plan, then checking to see if that query plan uses any
109616
- ** other FROM clause terms that are sWBI.notValid. If no notValid terms
109617
- ** are used then the "optimal" query plan works.
109618
- **
109619
- ** Note that the WhereCost.nRow parameter for an optimal scan might
109620
- ** not be as small as it would be if the table really were the innermost
109621
- ** join. The nRow value can be reduced by WHERE clause constraints
109622
- ** that do not use indices. But this nRow reduction only happens if the
109623
- ** table really is the innermost join.
109624
- **
109625
- ** The second loop iteration is only performed if no optimal scan
109626
- ** strategies were found by the first iteration. This second iteration
109627
- ** is used to search for the lowest cost scan overall.
109628
- **
109629
- ** Without the optimal scan step (the first iteration) a suboptimal
109630
- ** plan might be chosen for queries like this:
109631
- **
109632
- ** CREATE TABLE t1(a, b);
109633
- ** CREATE TABLE t2(c, d);
109634
- ** SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
109635
- **
109636
- ** The best strategy is to iterate through table t1 first. However it
109637
- ** is not possible to determine this with a simple greedy algorithm.
109638
- ** Since the cost of a linear scan through table t2 is the same
109639
- ** as the cost of a linear scan through table t1, a simple greedy
109640
- ** algorithm may choose to use t2 for the outer loop, which is a much
109641
- ** costlier approach.
109642
- */
109643
- nUnconstrained = 0;
109644
- notIndexed = 0;
109645
-
109646
- /* The optimal scan check only occurs if there are two or more tables
109647
- ** available to be reordered */
109648
- if( iFrom==nTabList-1 ){
109649
- ckOptimal = 0; /* Common case of just one table in the FROM clause */
109650
- }else{
109651
- ckOptimal = -1;
109652
- for(j=iFrom, sWBI.pSrc=&pTabList->a[j]; j<nTabList; j++, sWBI.pSrc++){
109653
- m = getMask(pMaskSet, sWBI.pSrc->iCursor);
109654
- if( (m & sWBI.notValid)==0 ){
109655
- if( j==iFrom ) iFrom++;
109656
- continue;
109657
- }
109658
- if( j>iFrom && (sWBI.pSrc->jointype & (JT_LEFT|JT_CROSS))!=0 ) break;
109659
- if( ++ckOptimal ) break;
109660
- if( (sWBI.pSrc->jointype & JT_LEFT)!=0 ) break;
109661
- }
109662
- }
109663
- assert( ckOptimal==0 || ckOptimal==1 );
109664
-
109665
- for(isOptimal=ckOptimal; isOptimal>=0 && bestJ<0; isOptimal--){
109666
- for(j=iFrom, sWBI.pSrc=&pTabList->a[j]; j<nTabList; j++, sWBI.pSrc++){
109667
- if( j>iFrom && (sWBI.pSrc->jointype & (JT_LEFT|JT_CROSS))!=0 ){
109668
- /* This break and one like it in the ckOptimal computation loop
109669
- ** above prevent table reordering across LEFT and CROSS JOINs.
109670
- ** The LEFT JOIN case is necessary for correctness. The prohibition
109671
- ** against reordering across a CROSS JOIN is an SQLite feature that
109672
- ** allows the developer to control table reordering */
109673
- break;
109674
- }
109675
- m = getMask(pMaskSet, sWBI.pSrc->iCursor);
109676
- if( (m & sWBI.notValid)==0 ){
109677
- assert( j>iFrom );
109678
- continue;
109679
- }
109680
- sWBI.notReady = (isOptimal ? m : sWBI.notValid);
109681
- if( sWBI.pSrc->pIndex==0 ) nUnconstrained++;
109682
-
109683
- WHERETRACE((" === trying table %d (%s) with isOptimal=%d ===\n",
109684
- j, sWBI.pSrc->pTab->zName, isOptimal));
109685
- assert( sWBI.pSrc->pTab );
109686
-#ifndef SQLITE_OMIT_VIRTUALTABLE
109687
- if( IsVirtual(sWBI.pSrc->pTab) ){
109688
- sWBI.ppIdxInfo = &pWInfo->a[j].pIdxInfo;
109689
- bestVirtualIndex(&sWBI);
109690
- }else
109691
-#endif
109692
- {
109693
- bestBtreeIndex(&sWBI);
109694
- }
109695
- assert( isOptimal || (sWBI.cost.used&sWBI.notValid)==0 );
109696
-
109697
- /* If an INDEXED BY clause is present, then the plan must use that
109698
- ** index if it uses any index at all */
109699
- assert( sWBI.pSrc->pIndex==0
109700
- || (sWBI.cost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
109701
- || sWBI.cost.plan.u.pIdx==sWBI.pSrc->pIndex );
109702
-
109703
- if( isOptimal && (sWBI.cost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
109704
- notIndexed |= m;
109705
- }
109706
- if( isOptimal ){
109707
- pWInfo->a[j].rOptCost = sWBI.cost.rCost;
109708
- }else if( ckOptimal ){
109709
- /* If two or more tables have nearly the same outer loop cost, but
109710
- ** very different inner loop (optimal) cost, we want to choose
109711
- ** for the outer loop that table which benefits the least from
109712
- ** being in the inner loop. The following code scales the
109713
- ** outer loop cost estimate to accomplish that. */
109714
- WHERETRACE((" scaling cost from %.1f to %.1f\n",
109715
- sWBI.cost.rCost,
109716
- sWBI.cost.rCost/pWInfo->a[j].rOptCost));
109717
- sWBI.cost.rCost /= pWInfo->a[j].rOptCost;
109718
- }
109719
-
109720
- /* Conditions under which this table becomes the best so far:
109721
- **
109722
- ** (1) The table must not depend on other tables that have not
109723
- ** yet run. (In other words, it must not depend on tables
109724
- ** in inner loops.)
109725
- **
109726
- ** (2) (This rule was removed on 2012-11-09. The scaling of the
109727
- ** cost using the optimal scan cost made this rule obsolete.)
109728
- **
109729
- ** (3) All tables have an INDEXED BY clause or this table lacks an
109730
- ** INDEXED BY clause or this table uses the specific
109731
- ** index specified by its INDEXED BY clause. This rule ensures
109732
- ** that a best-so-far is always selected even if an impossible
109733
- ** combination of INDEXED BY clauses are given. The error
109734
- ** will be detected and relayed back to the application later.
109735
- ** The NEVER() comes about because rule (2) above prevents
109736
- ** An indexable full-table-scan from reaching rule (3).
109737
- **
109738
- ** (4) The plan cost must be lower than prior plans, where "cost"
109739
- ** is defined by the compareCost() function above.
109740
- */
109741
- if( (sWBI.cost.used&sWBI.notValid)==0 /* (1) */
109742
- && (nUnconstrained==0 || sWBI.pSrc->pIndex==0 /* (3) */
109743
- || NEVER((sWBI.cost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0))
109744
- && (bestJ<0 || compareCost(&sWBI.cost, &bestPlan)) /* (4) */
109745
- ){
109746
- WHERETRACE((" === table %d (%s) is best so far\n"
109747
- " cost=%.1f, nRow=%.1f, nOBSat=%d, wsFlags=%08x\n",
109748
- j, sWBI.pSrc->pTab->zName,
109749
- sWBI.cost.rCost, sWBI.cost.plan.nRow,
109750
- sWBI.cost.plan.nOBSat, sWBI.cost.plan.wsFlags));
109751
- bestPlan = sWBI.cost;
109752
- bestJ = j;
109753
- }
109754
-
109755
- /* In a join like "w JOIN x LEFT JOIN y JOIN z" make sure that
109756
- ** table y (and not table z) is always the next inner loop inside
109757
- ** of table x. */
109758
- if( (sWBI.pSrc->jointype & JT_LEFT)!=0 ) break;
109759
- }
109760
- }
109761
- assert( bestJ>=0 );
109762
- assert( sWBI.notValid & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
109763
- assert( bestJ==iFrom || (pTabList->a[iFrom].jointype & JT_LEFT)==0 );
109764
- testcase( bestJ>iFrom && (pTabList->a[iFrom].jointype & JT_CROSS)!=0 );
109765
- testcase( bestJ>iFrom && bestJ<nTabList-1
109766
- && (pTabList->a[bestJ+1].jointype & JT_LEFT)!=0 );
109767
- WHERETRACE(("*** Optimizer selects table %d (%s) for loop %d with:\n"
109768
- " cost=%.1f, nRow=%.1f, nOBSat=%d, wsFlags=0x%08x\n",
109769
- bestJ, pTabList->a[bestJ].pTab->zName,
109770
- pLevel-pWInfo->a, bestPlan.rCost, bestPlan.plan.nRow,
109771
- bestPlan.plan.nOBSat, bestPlan.plan.wsFlags));
109772
- if( (bestPlan.plan.wsFlags & WHERE_DISTINCT)!=0 ){
109773
- assert( pWInfo->eDistinct==0 );
109774
- pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
109775
- }
109776
- andFlags &= bestPlan.plan.wsFlags;
109777
- pLevel->plan = bestPlan.plan;
109778
- pLevel->iTabCur = pTabList->a[bestJ].iCursor;
109779
- testcase( bestPlan.plan.wsFlags & WHERE_INDEXED );
109780
- testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX );
109781
- if( bestPlan.plan.wsFlags & (WHERE_INDEXED|WHERE_TEMP_INDEX) ){
109782
- if( (wctrlFlags & WHERE_ONETABLE_ONLY)
109783
- && (bestPlan.plan.wsFlags & WHERE_TEMP_INDEX)==0
109784
- ){
109785
- pLevel->iIdxCur = iIdxCur;
109786
- }else{
109787
- pLevel->iIdxCur = pParse->nTab++;
109788
- }
109789
- }else{
109790
- pLevel->iIdxCur = -1;
109791
- }
109792
- sWBI.notValid &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
109793
- pLevel->iFrom = (u8)bestJ;
109794
- if( bestPlan.plan.nRow>=(double)1 ){
109795
- pParse->nQueryLoop *= bestPlan.plan.nRow;
109796
- }
109797
-
109798
- /* Check that if the table scanned by this loop iteration had an
109799
- ** INDEXED BY clause attached to it, that the named index is being
109800
- ** used for the scan. If not, then query compilation has failed.
109801
- ** Return an error.
109802
- */
109803
- pIdx = pTabList->a[bestJ].pIndex;
109804
- if( pIdx ){
109805
- if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
109806
- sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
109807
- goto whereBeginError;
109808
- }else{
109809
- /* If an INDEXED BY clause is used, the bestIndex() function is
109810
- ** guaranteed to find the index specified in the INDEXED BY clause
109811
- ** if it find an index at all. */
109812
- assert( bestPlan.plan.u.pIdx==pIdx );
109813
- }
109814
- }
109815
- }
109816
- WHERETRACE(("*** Optimizer Finished ***\n"));
109817
- if( pParse->nErr || db->mallocFailed ){
109818
- goto whereBeginError;
109819
- }
109820
- if( nTabList ){
109821
- pLevel--;
109822
- pWInfo->nOBSat = pLevel->plan.nOBSat;
109823
- }else{
109824
- pWInfo->nOBSat = 0;
109825
- }
109826
-
109827
- /* If the total query only selects a single row, then the ORDER BY
109828
- ** clause is irrelevant.
109829
- */
109830
- if( (andFlags & WHERE_UNIQUE)!=0 && pOrderBy ){
109831
- assert( nTabList==0 || (pLevel->plan.wsFlags & WHERE_ALL_UNIQUE)!=0 );
109832
- pWInfo->nOBSat = pOrderBy->nExpr;
109833
- }
110004
+ if( pDistinct ){
110005
+ if( isDistinctRedundant(pParse,pTabList,&pWInfo->sWC,pDistinct) ){
110006
+ pDistinct = 0;
110007
+ pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
110008
+ }else if( pOrderBy==0 ){
110009
+ pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
110010
+ pWInfo->pOrderBy = pDistinct;
110011
+ }
110012
+ }
110013
+
110014
+ /* Construct the WhereLoop objects */
110015
+ WHERETRACE(0xffff,("*** Optimizer Start ***\n"));
110016
+ if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
110017
+ rc = whereLoopAddAll(&sWLB);
110018
+ if( rc ) goto whereBeginError;
110019
+
110020
+ /* Display all of the WhereLoop objects if wheretrace is enabled */
110021
+#ifdef WHERETRACE_ENABLED
110022
+ if( sqlite3WhereTrace ){
110023
+ WhereLoop *p;
110024
+ int i = 0;
110025
+ static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
110026
+ "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
110027
+ for(p=pWInfo->pLoops; p; p=p->pNextLoop){
110028
+ p->cId = zLabel[(i++)%sizeof(zLabel)];
110029
+ whereLoopPrint(p, pTabList);
110030
+ }
110031
+ }
110032
+#endif
110033
+
110034
+ wherePathSolver(pWInfo, 0);
110035
+ if( db->mallocFailed ) goto whereBeginError;
110036
+ if( pWInfo->pOrderBy ){
110037
+ wherePathSolver(pWInfo, pWInfo->nRowOut+1);
110038
+ if( db->mallocFailed ) goto whereBeginError;
110039
+ }
110040
+ }
110041
+ if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
110042
+ pWInfo->revMask = (Bitmask)(-1);
110043
+ }
110044
+ if( pParse->nErr || NEVER(db->mallocFailed) ){
110045
+ goto whereBeginError;
110046
+ }
110047
+#ifdef WHERETRACE_ENABLED
110048
+ if( sqlite3WhereTrace ){
110049
+ int ii;
110050
+ sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
110051
+ if( pWInfo->bOBSat ){
110052
+ sqlite3DebugPrintf(" ORDERBY=0x%llx", pWInfo->revMask);
110053
+ }
110054
+ switch( pWInfo->eDistinct ){
110055
+ case WHERE_DISTINCT_UNIQUE: {
110056
+ sqlite3DebugPrintf(" DISTINCT=unique");
110057
+ break;
110058
+ }
110059
+ case WHERE_DISTINCT_ORDERED: {
110060
+ sqlite3DebugPrintf(" DISTINCT=ordered");
110061
+ break;
110062
+ }
110063
+ case WHERE_DISTINCT_UNORDERED: {
110064
+ sqlite3DebugPrintf(" DISTINCT=unordered");
110065
+ break;
110066
+ }
110067
+ }
110068
+ sqlite3DebugPrintf("\n");
110069
+ for(ii=0; ii<nTabList; ii++){
110070
+ whereLoopPrint(pWInfo->a[ii].pWLoop, pTabList);
110071
+ }
110072
+ }
110073
+#endif
110074
+ WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
110075
+ pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
109834110076
109835110077
/* If the caller is an UPDATE or DELETE statement that is requesting
109836110078
** to use a one-pass algorithm, determine if this is appropriate.
109837110079
** The one-pass algorithm only works if the WHERE clause constraints
109838110080
** the statement to update a single row.
109839110081
*/
109840110082
assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
109841
- if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
110083
+ if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
110084
+ && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){
109842110085
pWInfo->okOnePass = 1;
109843
- pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
110086
+ pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
109844110087
}
109845110088
109846110089
/* Open all tables in the pTabList and any indices selected for
109847110090
** searching those tables.
109848110091
*/
109849110092
sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
109850110093
notReady = ~(Bitmask)0;
109851
- pWInfo->nRowOut = (double)1;
109852110094
for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
109853110095
Table *pTab; /* Table to open */
109854110096
int iDb; /* Index of database containing table/index */
109855110097
struct SrcList_item *pTabItem;
110098
+ WhereLoop *pLoop;
109856110099
109857110100
pTabItem = &pTabList->a[pLevel->iFrom];
109858110101
pTab = pTabItem->pTab;
109859
- pWInfo->nRowOut *= pLevel->plan.nRow;
109860110102
iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
110103
+ pLoop = pLevel->pWLoop;
109861110104
if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
109862110105
/* Do nothing */
109863110106
}else
109864110107
#ifndef SQLITE_OMIT_VIRTUALTABLE
109865
- if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
110108
+ if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
109866110109
const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
109867110110
int iCur = pTabItem->iCursor;
109868110111
sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
109869110112
}else if( IsVirtual(pTab) ){
109870110113
/* noop */
109871110114
}else
109872110115
#endif
109873
- if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
110116
+ if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
109874110117
&& (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
109875110118
int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
109876110119
sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
109877
- testcase( pTab->nCol==BMS-1 );
109878
- testcase( pTab->nCol==BMS );
110120
+ testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 );
110121
+ testcase( !pWInfo->okOnePass && pTab->nCol==BMS );
109879110122
if( !pWInfo->okOnePass && pTab->nCol<BMS ){
109880110123
Bitmask b = pTabItem->colUsed;
109881110124
int n = 0;
109882110125
for(; b; b=b>>1, n++){}
109883110126
sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
@@ -109886,26 +110129,27 @@
109886110129
}
109887110130
}else{
109888110131
sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
109889110132
}
109890110133
#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
109891
- if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
109892
- constructAutomaticIndex(pParse, sWBI.pWC, pTabItem, notReady, pLevel);
110134
+ if( (pLoop->wsFlags & WHERE_TEMP_INDEX)!=0 ){
110135
+ constructAutomaticIndex(pParse, &pWInfo->sWC, pTabItem, notReady, pLevel);
109893110136
}else
109894110137
#endif
109895
- if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
109896
- Index *pIx = pLevel->plan.u.pIdx;
110138
+ if( pLoop->wsFlags & WHERE_INDEXED ){
110139
+ Index *pIx = pLoop->u.btree.pIndex;
109897110140
KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
109898
- int iIndexCur = pLevel->iIdxCur;
110141
+ /* FIXME: As an optimization use pTabItem->iCursor if WHERE_IDX_ONLY */
110142
+ int iIndexCur = pLevel->iIdxCur = iIdxCur ? iIdxCur : pParse->nTab++;
109899110143
assert( pIx->pSchema==pTab->pSchema );
109900110144
assert( iIndexCur>=0 );
109901110145
sqlite3VdbeAddOp4(v, OP_OpenRead, iIndexCur, pIx->tnum, iDb,
109902110146
(char*)pKey, P4_KEYINFO_HANDOFF);
109903110147
VdbeComment((v, "%s", pIx->zName));
109904110148
}
109905110149
sqlite3CodeVerifySchema(pParse, iDb);
109906
- notReady &= ~getMask(sWBI.pWC->pMaskSet, pTabItem->iCursor);
110150
+ notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor);
109907110151
}
109908110152
pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
109909110153
if( db->mallocFailed ) goto whereBeginError;
109910110154
109911110155
/* Generate the code to do the search. Each iteration of the for
@@ -109914,70 +110158,15 @@
109914110158
*/
109915110159
notReady = ~(Bitmask)0;
109916110160
for(ii=0; ii<nTabList; ii++){
109917110161
pLevel = &pWInfo->a[ii];
109918110162
explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
109919
- notReady = codeOneLoopStart(pWInfo, ii, wctrlFlags, notReady);
110163
+ notReady = codeOneLoopStart(pWInfo, ii, notReady);
109920110164
pWInfo->iContinue = pLevel->addrCont;
109921110165
}
109922110166
109923
-#ifdef SQLITE_TEST /* For testing and debugging use only */
109924
- /* Record in the query plan information about the current table
109925
- ** and the index used to access it (if any). If the table itself
109926
- ** is not used, its name is just '{}'. If no index is used
109927
- ** the index is listed as "{}". If the primary key is used the
109928
- ** index name is '*'.
109929
- */
109930
- for(ii=0; ii<nTabList; ii++){
109931
- char *z;
109932
- int n;
109933
- int w;
109934
- struct SrcList_item *pTabItem;
109935
-
109936
- pLevel = &pWInfo->a[ii];
109937
- w = pLevel->plan.wsFlags;
109938
- pTabItem = &pTabList->a[pLevel->iFrom];
109939
- z = pTabItem->zAlias;
109940
- if( z==0 ) z = pTabItem->pTab->zName;
109941
- n = sqlite3Strlen30(z);
109942
- if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
109943
- if( (w & WHERE_IDX_ONLY)!=0 && (w & WHERE_COVER_SCAN)==0 ){
109944
- memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
109945
- nQPlan += 2;
109946
- }else{
109947
- memcpy(&sqlite3_query_plan[nQPlan], z, n);
109948
- nQPlan += n;
109949
- }
109950
- sqlite3_query_plan[nQPlan++] = ' ';
109951
- }
109952
- testcase( w & WHERE_ROWID_EQ );
109953
- testcase( w & WHERE_ROWID_RANGE );
109954
- if( w & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
109955
- memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
109956
- nQPlan += 2;
109957
- }else if( (w & WHERE_INDEXED)!=0 && (w & WHERE_COVER_SCAN)==0 ){
109958
- n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
109959
- if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
109960
- memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
109961
- nQPlan += n;
109962
- sqlite3_query_plan[nQPlan++] = ' ';
109963
- }
109964
- }else{
109965
- memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
109966
- nQPlan += 3;
109967
- }
109968
- }
109969
- while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
109970
- sqlite3_query_plan[--nQPlan] = 0;
109971
- }
109972
- sqlite3_query_plan[nQPlan] = 0;
109973
- nQPlan = 0;
109974
-#endif /* SQLITE_TEST // Testing and debugging use only */
109975
-
109976
- /* Record the continuation address in the WhereInfo structure. Then
109977
- ** clean up and return.
109978
- */
110167
+ /* Done. */
109979110168
return pWInfo;
109980110169
109981110170
/* Jump here if malloc fails */
109982110171
whereBeginError:
109983110172
if( pWInfo ){
@@ -109994,24 +110183,26 @@
109994110183
SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
109995110184
Parse *pParse = pWInfo->pParse;
109996110185
Vdbe *v = pParse->pVdbe;
109997110186
int i;
109998110187
WhereLevel *pLevel;
110188
+ WhereLoop *pLoop;
109999110189
SrcList *pTabList = pWInfo->pTabList;
110000110190
sqlite3 *db = pParse->db;
110001110191
110002110192
/* Generate loop termination code.
110003110193
*/
110004110194
sqlite3ExprCacheClear(pParse);
110005110195
for(i=pWInfo->nLevel-1; i>=0; i--){
110006110196
pLevel = &pWInfo->a[i];
110197
+ pLoop = pLevel->pWLoop;
110007110198
sqlite3VdbeResolveLabel(v, pLevel->addrCont);
110008110199
if( pLevel->op!=OP_Noop ){
110009110200
sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
110010110201
sqlite3VdbeChangeP5(v, pLevel->p5);
110011110202
}
110012
- if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
110203
+ if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
110013110204
struct InLoop *pIn;
110014110205
int j;
110015110206
sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
110016110207
for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
110017110208
sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
@@ -110022,16 +110213,16 @@
110022110213
}
110023110214
sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
110024110215
if( pLevel->iLeftJoin ){
110025110216
int addr;
110026110217
addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
110027
- assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
110028
- || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
110029
- if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
110218
+ assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
110219
+ || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
110220
+ if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
110030110221
sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
110031110222
}
110032
- if( pLevel->iIdxCur>=0 ){
110223
+ if( pLoop->wsFlags & WHERE_INDEXED ){
110033110224
sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
110034110225
}
110035110226
if( pLevel->op==OP_Return ){
110036110227
sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
110037110228
}else{
@@ -110052,42 +110243,41 @@
110052110243
for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
110053110244
Index *pIdx = 0;
110054110245
struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
110055110246
Table *pTab = pTabItem->pTab;
110056110247
assert( pTab!=0 );
110248
+ pLoop = pLevel->pWLoop;
110057110249
if( (pTab->tabFlags & TF_Ephemeral)==0
110058110250
&& pTab->pSelect==0
110059110251
&& (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
110060110252
){
110061
- int ws = pLevel->plan.wsFlags;
110253
+ int ws = pLoop->wsFlags;
110062110254
if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
110063110255
sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
110064110256
}
110065
- if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){
110257
+ if( (ws & WHERE_INDEXED)!=0 && (ws & (WHERE_IPK|WHERE_TEMP_INDEX))==0 ){
110066110258
sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
110067110259
}
110068110260
}
110069110261
110070
- /* If this scan uses an index, make code substitutions to read data
110071
- ** from the index in preference to the table. Sometimes, this means
110072
- ** the table need never be read from. This is a performance boost,
110073
- ** as the vdbe level waits until the table is read before actually
110074
- ** seeking the table cursor to the record corresponding to the current
110075
- ** position in the index.
110262
+ /* If this scan uses an index, make VDBE code substitutions to read data
110263
+ ** from the index instead of from the table where possible. In some cases
110264
+ ** this optimization prevents the table from ever being read, which can
110265
+ ** yield a significant performance boost.
110076110266
**
110077110267
** Calls to the code generator in between sqlite3WhereBegin and
110078110268
** sqlite3WhereEnd will have created code that references the table
110079110269
** directly. This loop scans all that code looking for opcodes
110080110270
** that reference the table and converts them into opcodes that
110081110271
** reference the index.
110082110272
*/
110083
- if( pLevel->plan.wsFlags & WHERE_INDEXED ){
110084
- pIdx = pLevel->plan.u.pIdx;
110085
- }else if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
110273
+ if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
110274
+ pIdx = pLoop->u.btree.pIndex;
110275
+ }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
110086110276
pIdx = pLevel->u.pCovidx;
110087110277
}
110088
- if( pIdx && !db->mallocFailed){
110278
+ if( pIdx && !db->mallocFailed ){
110089110279
int k, j, last;
110090110280
VdbeOp *pOp;
110091110281
110092110282
pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
110093110283
last = sqlite3VdbeCurrentAddr(v);
@@ -110099,12 +110289,11 @@
110099110289
pOp->p2 = j;
110100110290
pOp->p1 = pLevel->iIdxCur;
110101110291
break;
110102110292
}
110103110293
}
110104
- assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
110105
- || j<pIdx->nColumn );
110294
+ assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || j<pIdx->nColumn );
110106110295
}else if( pOp->opcode==OP_Rowid ){
110107110296
pOp->p1 = pLevel->iIdxCur;
110108110297
pOp->opcode = OP_IdxRowid;
110109110298
}
110110110299
}
@@ -115480,11 +115669,11 @@
115480115669
}
115481115670
115482115671
/*
115483115672
** Another built-in collating sequence: NOCASE.
115484115673
**
115485
-** This collating sequence is intended to be used for "case independant
115674
+** This collating sequence is intended to be used for "case independent
115486115675
** comparison". SQLite's knowledge of upper and lower case equivalents
115487115676
** extends only to the 26 characters used in the English language.
115488115677
**
115489115678
** At the moment there is only a UTF-8 implementation.
115490115679
*/
@@ -115627,16 +115816,10 @@
115627115816
"statements or unfinished backups");
115628115817
sqlite3_mutex_leave(db->mutex);
115629115818
return SQLITE_BUSY;
115630115819
}
115631115820
115632
- /* If a transaction is open, roll it back. This also ensures that if
115633
- ** any database schemas have been modified by the current transaction
115634
- ** they are reset. And that the required b-tree mutex is held to make
115635
- ** the the pager rollback and schema reset an atomic operation. */
115636
- sqlite3RollbackAll(db, SQLITE_OK);
115637
-
115638115821
#ifdef SQLITE_ENABLE_SQLLOG
115639115822
if( sqlite3GlobalConfig.xSqllog ){
115640115823
/* Closing the handle. Fourth parameter is passed the value 2. */
115641115824
sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
115642115825
}
@@ -115686,10 +115869,16 @@
115686115869
/* If we reach this point, it means that the database connection has
115687115870
** closed all sqlite3_stmt and sqlite3_backup objects and has been
115688115871
** passed to sqlite3_close (meaning that it is a zombie). Therefore,
115689115872
** go ahead and free all resources.
115690115873
*/
115874
+
115875
+ /* If a transaction is open, roll it back. This also ensures that if
115876
+ ** any database schemas have been modified by an uncommitted transaction
115877
+ ** they are reset. And that the required b-tree mutex is held to make
115878
+ ** the pager rollback and schema reset an atomic operation. */
115879
+ sqlite3RollbackAll(db, SQLITE_OK);
115691115880
115692115881
/* Free any outstanding Savepoint structures. */
115693115882
sqlite3CloseSavepoints(db);
115694115883
115695115884
/* Close all database connections */
@@ -115787,19 +115976,26 @@
115787115976
SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
115788115977
int i;
115789115978
int inTrans = 0;
115790115979
assert( sqlite3_mutex_held(db->mutex) );
115791115980
sqlite3BeginBenignMalloc();
115981
+
115982
+ /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
115983
+ ** This is important in case the transaction being rolled back has
115984
+ ** modified the database schema. If the b-tree mutexes are not taken
115985
+ ** here, then another shared-cache connection might sneak in between
115986
+ ** the database rollback and schema reset, which can cause false
115987
+ ** corruption reports in some cases. */
115792115988
sqlite3BtreeEnterAll(db);
115989
+
115793115990
for(i=0; i<db->nDb; i++){
115794115991
Btree *p = db->aDb[i].pBt;
115795115992
if( p ){
115796115993
if( sqlite3BtreeIsInTrans(p) ){
115797115994
inTrans = 1;
115798115995
}
115799115996
sqlite3BtreeRollback(p, tripCode);
115800
- db->aDb[i].inTrans = 0;
115801115997
}
115802115998
}
115803115999
sqlite3VtabRollback(db);
115804116000
sqlite3EndBenignMalloc();
115805116001
@@ -117562,12 +117758,10 @@
117562117758
/*
117563117759
** Test to see whether or not the database connection is in autocommit
117564117760
** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
117565117761
** by default. Autocommit is disabled by a BEGIN statement and reenabled
117566117762
** by the next COMMIT or ROLLBACK.
117567
-**
117568
-******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
117569117763
*/
117570117764
SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
117571117765
return db->autoCommit;
117572117766
}
117573117767
@@ -119051,10 +119245,22 @@
119051119245
119052119246
#endif /* _FTS3_HASH_H_ */
119053119247
119054119248
/************** End of fts3_hash.h *******************************************/
119055119249
/************** Continuing where we left off in fts3Int.h ********************/
119250
+
119251
+/*
119252
+** This constant determines the maximum depth of an FTS expression tree
119253
+** that the library will create and use. FTS uses recursion to perform
119254
+** various operations on the query tree, so the disadvantage of a large
119255
+** limit is that it may allow very large queries to use large amounts
119256
+** of stack space (perhaps causing a stack overflow).
119257
+*/
119258
+#ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
119259
+# define SQLITE_FTS3_MAX_EXPR_DEPTH 12
119260
+#endif
119261
+
119056119262
119057119263
/*
119058119264
** This constant controls how often segments are merged. Once there are
119059119265
** FTS3_MERGE_COUNT segments of level N, they are merged into a single
119060119266
** segment of level N+1.
@@ -120709,11 +120915,11 @@
120709120915
/* By default use a full table scan. This is an expensive option,
120710120916
** so search through the constraints to see if a more efficient
120711120917
** strategy is possible.
120712120918
*/
120713120919
pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
120714
- pInfo->estimatedCost = 500000;
120920
+ pInfo->estimatedCost = 5000000;
120715120921
for(i=0; i<pInfo->nConstraint; i++){
120716120922
struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
120717120923
if( pCons->usable==0 ) continue;
120718120924
120719120925
/* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
@@ -122270,15 +122476,11 @@
122270122476
);
122271122477
if( rc!=SQLITE_OK ){
122272122478
return rc;
122273122479
}
122274122480
122275
- rc = sqlite3Fts3ReadLock(p);
122276
- if( rc!=SQLITE_OK ) return rc;
122277
-
122278122481
rc = fts3EvalStart(pCsr);
122279
-
122280122482
sqlite3Fts3SegmentsClose(p);
122281122483
if( rc!=SQLITE_OK ) return rc;
122282122484
pCsr->pNextId = pCsr->aDoclist;
122283122485
pCsr->iPrevId = 0;
122284122486
}
@@ -126129,30 +126331,30 @@
126129126331
int iDefaultCol, /* Default column to query */
126130126332
const char *z, int n, /* Text of MATCH query */
126131126333
Fts3Expr **ppExpr, /* OUT: Parsed query structure */
126132126334
char **pzErr /* OUT: Error message (sqlite3_malloc) */
126133126335
){
126134
- static const int MAX_EXPR_DEPTH = 12;
126135126336
int rc = fts3ExprParseUnbalanced(
126136126337
pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
126137126338
);
126138126339
126139126340
/* Rebalance the expression. And check that its depth does not exceed
126140
- ** MAX_EXPR_DEPTH. */
126341
+ ** SQLITE_FTS3_MAX_EXPR_DEPTH. */
126141126342
if( rc==SQLITE_OK && *ppExpr ){
126142
- rc = fts3ExprBalance(ppExpr, MAX_EXPR_DEPTH);
126343
+ rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
126143126344
if( rc==SQLITE_OK ){
126144
- rc = fts3ExprCheckDepth(*ppExpr, MAX_EXPR_DEPTH);
126345
+ rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
126145126346
}
126146126347
}
126147126348
126148126349
if( rc!=SQLITE_OK ){
126149126350
sqlite3Fts3ExprFree(*ppExpr);
126150126351
*ppExpr = 0;
126151126352
if( rc==SQLITE_TOOBIG ){
126152126353
*pzErr = sqlite3_mprintf(
126153
- "FTS expression tree is too large (maximum depth %d)", MAX_EXPR_DEPTH
126354
+ "FTS expression tree is too large (maximum depth %d)",
126355
+ SQLITE_FTS3_MAX_EXPR_DEPTH
126154126356
);
126155126357
rc = SQLITE_ERROR;
126156126358
}else if( rc==SQLITE_ERROR ){
126157126359
*pzErr = sqlite3_mprintf("malformed MATCH expression: [%s]", z);
126158126360
}
@@ -129110,41 +129312,34 @@
129110129312
*pRC = rc;
129111129313
}
129112129314
129113129315
129114129316
/*
129115
-** This function ensures that the caller has obtained a shared-cache
129116
-** table-lock on the %_content table. This is required before reading
129117
-** data from the fts3 table. If this lock is not acquired first, then
129118
-** the caller may end up holding read-locks on the %_segments and %_segdir
129119
-** tables, but no read-lock on the %_content table. If this happens
129120
-** a second connection will be able to write to the fts3 table, but
129121
-** attempting to commit those writes might return SQLITE_LOCKED or
129122
-** SQLITE_LOCKED_SHAREDCACHE (because the commit attempts to obtain
129123
-** write-locks on the %_segments and %_segdir ** tables).
129124
-**
129125
-** We try to avoid this because if FTS3 returns any error when committing
129126
-** a transaction, the whole transaction will be rolled back. And this is
129127
-** not what users expect when they get SQLITE_LOCKED_SHAREDCACHE. It can
129128
-** still happen if the user reads data directly from the %_segments or
129129
-** %_segdir tables instead of going through FTS3 though.
129130
-**
129131
-** This reasoning does not apply to a content=xxx table.
129132
-*/
129133
-SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *p){
129134
- int rc; /* Return code */
129135
- sqlite3_stmt *pStmt; /* Statement used to obtain lock */
129136
-
129137
- if( p->zContentTbl==0 ){
129138
- rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pStmt, 0);
129317
+** This function ensures that the caller has obtained an exclusive
129318
+** shared-cache table-lock on the %_segdir table. This is required before
129319
+** writing data to the fts3 table. If this lock is not acquired first, then
129320
+** the caller may end up attempting to take this lock as part of committing
129321
+** a transaction, causing SQLite to return SQLITE_LOCKED or
129322
+** LOCKED_SHAREDCACHEto a COMMIT command.
129323
+**
129324
+** It is best to avoid this because if FTS3 returns any error when
129325
+** committing a transaction, the whole transaction will be rolled back.
129326
+** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
129327
+** It can still happen if the user locks the underlying tables directly
129328
+** instead of accessing them via FTS.
129329
+*/
129330
+static int fts3Writelock(Fts3Table *p){
129331
+ int rc = SQLITE_OK;
129332
+
129333
+ if( p->nPendingData==0 ){
129334
+ sqlite3_stmt *pStmt;
129335
+ rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
129139129336
if( rc==SQLITE_OK ){
129140129337
sqlite3_bind_null(pStmt, 1);
129141129338
sqlite3_step(pStmt);
129142129339
rc = sqlite3_reset(pStmt);
129143129340
}
129144
- }else{
129145
- rc = SQLITE_OK;
129146129341
}
129147129342
129148129343
return rc;
129149129344
}
129150129345
@@ -133918,10 +134113,13 @@
133918134113
goto update_out;
133919134114
}
133920134115
aSzIns = &aSzDel[p->nColumn+1];
133921134116
memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
133922134117
134118
+ rc = fts3Writelock(p);
134119
+ if( rc!=SQLITE_OK ) goto update_out;
134120
+
133923134121
/* If this is an INSERT operation, or an UPDATE that modifies the rowid
133924134122
** value, then this operation requires constraint handling.
133925134123
**
133926134124
** If the on-conflict mode is REPLACE, this means that the existing row
133927134125
** should be deleted from the database before inserting the new row. Or,
@@ -136051,32 +136249,31 @@
136051136249
0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
136052136250
0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
136053136251
0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
136054136252
0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
136055136253
0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
136056
- 0x037FFC02, 0x03E3FC01, 0x03EC7801, 0x03ECA401, 0x03EEC810,
136057
- 0x03F4F802, 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023,
136058
- 0x03F95013, 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807,
136059
- 0x03FCEC06, 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405,
136060
- 0x04040003, 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E,
136061
- 0x040E7C01, 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01,
136062
- 0x04280403, 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01,
136063
- 0x04294009, 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016,
136064
- 0x04420003, 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004,
136065
- 0x04460003, 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004,
136066
- 0x05BD442E, 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5,
136067
- 0x07480046, 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01,
136068
- 0x075C5401, 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401,
136069
- 0x075EA401, 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064,
136070
- 0x07C2800F, 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F,
136071
- 0x07C4C03C, 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009,
136072
- 0x07C94002, 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014,
136073
- 0x07CE8025, 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001,
136074
- 0x07D108B6, 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018,
136075
- 0x07D7EC46, 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401,
136076
- 0x38008060, 0x380400F0, 0x3C000001, 0x3FFFF401, 0x40000001,
136077
- 0x43FFF401,
136254
+ 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
136255
+ 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
136256
+ 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
136257
+ 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
136258
+ 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
136259
+ 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
136260
+ 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
136261
+ 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
136262
+ 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
136263
+ 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
136264
+ 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
136265
+ 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
136266
+ 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
136267
+ 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
136268
+ 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
136269
+ 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
136270
+ 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
136271
+ 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
136272
+ 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
136273
+ 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
136274
+ 0x380400F0,
136078136275
};
136079136276
static const unsigned int aAscii[4] = {
136080136277
0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
136081136278
};
136082136279
@@ -139705,11 +139902,11 @@
139705139902
** operator) using the ICU uregex_XX() APIs.
139706139903
**
139707139904
** * Implementations of the SQL scalar upper() and lower() functions
139708139905
** for case mapping.
139709139906
**
139710
-** * Integration of ICU and SQLite collation seqences.
139907
+** * Integration of ICU and SQLite collation sequences.
139711139908
**
139712139909
** * An implementation of the LIKE operator that uses ICU to
139713139910
** provide case-independent matching.
139714139911
*/
139715139912
139716139913
--- src/sqlite3.c
+++ src/sqlite3.c
@@ -352,11 +352,11 @@
352
353 /*
354 ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
355 ** 0 means mutexes are permanently disable and the library is never
356 ** threadsafe. 1 means the library is serialized which is the highest
357 ** level of threadsafety. 2 means the libary is multithreaded - multiple
358 ** threads can use SQLite as long as no two threads try to use the same
359 ** database connection at the same time.
360 **
361 ** Older versions of SQLite used an optional THREADSAFE macro.
362 ** We support that for legacy.
@@ -431,24 +431,16 @@
431 # define SQLITE_MALLOC_SOFT_LIMIT 1024
432 #endif
433
434 /*
435 ** We need to define _XOPEN_SOURCE as follows in order to enable
436 ** recursive mutexes on most Unix systems. But Mac OS X is different.
437 ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
438 ** so it is omitted there. See ticket #2673.
439 **
440 ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
441 ** implemented on some systems. So we avoid defining it at all
442 ** if it is already defined or if it is unneeded because we are
443 ** not doing a threadsafe build. Ticket #2681.
444 **
445 ** See also ticket #2741.
446 */
447 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) \
448 && !defined(__APPLE__) && SQLITE_THREADSAFE
449 # define _XOPEN_SOURCE 500 /* Needed to enable pthread recursive mutexes */
450 #endif
451
452 /*
453 ** The TCL headers are only needed when compiling the TCL bindings.
454 */
@@ -678,11 +670,11 @@
678 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
679 ** [sqlite_version()] and [sqlite_source_id()].
680 */
681 #define SQLITE_VERSION "3.7.17"
682 #define SQLITE_VERSION_NUMBER 3007017
683 #define SQLITE_SOURCE_ID "2013-05-15 18:34:17 00231fb0127960d700de3549e34e82f8ec1b5819"
684
685 /*
686 ** CAPI3REF: Run-Time Library Version Numbers
687 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
688 **
@@ -5087,10 +5079,15 @@
5087 */
5088 SQLITE_API int sqlite3_key(
5089 sqlite3 *db, /* Database to be rekeyed */
5090 const void *pKey, int nKey /* The key */
5091 );
 
 
 
 
 
5092
5093 /*
5094 ** Change the key on an open database. If the current database is not
5095 ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
5096 ** database is decrypted.
@@ -5100,10 +5097,15 @@
5100 */
5101 SQLITE_API int sqlite3_rekey(
5102 sqlite3 *db, /* Database to be rekeyed */
5103 const void *pKey, int nKey /* The new key */
5104 );
 
 
 
 
 
5105
5106 /*
5107 ** Specify the activation key for a SEE database. Unless
5108 ** activated, none of the SEE routines will work.
5109 */
@@ -8151,10 +8153,16 @@
8151 */
8152 #ifndef offsetof
8153 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
8154 #endif
8155
 
 
 
 
 
 
8156 /*
8157 ** Check to see if this machine uses EBCDIC. (Yes, believe it or
8158 ** not, there are still machines out there that use EBCDIC.)
8159 */
8160 #if 'A' == '\301'
@@ -8476,13 +8484,11 @@
8476 typedef struct TriggerStep TriggerStep;
8477 typedef struct UnpackedRecord UnpackedRecord;
8478 typedef struct VTable VTable;
8479 typedef struct VtabCtx VtabCtx;
8480 typedef struct Walker Walker;
8481 typedef struct WherePlan WherePlan;
8482 typedef struct WhereInfo WhereInfo;
8483 typedef struct WhereLevel WhereLevel;
8484
8485 /*
8486 ** Defer sourcing vdbe.h and btree.h until after the "u8" and
8487 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
8488 ** pointer types (i.e. FuncDef) defined above.
@@ -9915,11 +9921,10 @@
9915 ** databases may be attached.
9916 */
9917 struct Db {
9918 char *zName; /* Name of this database */
9919 Btree *pBt; /* The B*Tree structure for this database file */
9920 u8 inTrans; /* 0: not writable. 1: Transaction. 2: Checkpoint */
9921 u8 safety_level; /* How aggressive at syncing data to disk */
9922 Schema *pSchema; /* Pointer to database schema (possibly shared) */
9923 };
9924
9925 /*
@@ -10713,10 +10718,11 @@
10713 int tnum; /* DB Page containing root of this index */
10714 u16 nColumn; /* Number of columns in table used by this index */
10715 u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
10716 unsigned autoIndex:2; /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
10717 unsigned bUnordered:1; /* Use this index for == or IN queries only */
 
10718 #ifdef SQLITE_ENABLE_STAT3
10719 int nSample; /* Number of elements in aSample[] */
10720 tRowcnt avgEq; /* Average nEq value for key values not in aSample */
10721 IndexSample *aSample; /* Samples of the left-most key */
10722 #endif
@@ -11058,10 +11064,15 @@
11058 /*
11059 ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
11060 */
11061 #define BMS ((int)(sizeof(Bitmask)*8))
11062
 
 
 
 
 
11063 /*
11064 ** The following structure describes the FROM clause of a SELECT statement.
11065 ** Each table or subquery in the FROM clause is a separate element of
11066 ** the SrcList.a[] array.
11067 **
@@ -11078,12 +11089,12 @@
11078 **
11079 ** In the colUsed field, the high-order bit (bit 63) is set if the table
11080 ** contains more than 63 columns and the 64-th or later column is used.
11081 */
11082 struct SrcList {
11083 i16 nSrc; /* Number of tables or subqueries in the FROM clause */
11084 i16 nAlloc; /* Number of entries allocated in a[] below */
11085 struct SrcList_item {
11086 Schema *pSchema; /* Schema to which this item is fixed */
11087 char *zDatabase; /* Name of database holding this table */
11088 char *zName; /* Name of the table */
11089 char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
@@ -11117,83 +11128,10 @@
11117 #define JT_RIGHT 0x0010 /* Right outer join */
11118 #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
11119 #define JT_ERROR 0x0040 /* unknown or unsupported join type */
11120
11121
11122 /*
11123 ** A WherePlan object holds information that describes a lookup
11124 ** strategy.
11125 **
11126 ** This object is intended to be opaque outside of the where.c module.
11127 ** It is included here only so that that compiler will know how big it
11128 ** is. None of the fields in this object should be used outside of
11129 ** the where.c module.
11130 **
11131 ** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
11132 ** pTerm is only used when wsFlags&WHERE_MULTI_OR is true. And pVtabIdx
11133 ** is only used when wsFlags&WHERE_VIRTUALTABLE is true. It is never the
11134 ** case that more than one of these conditions is true.
11135 */
11136 struct WherePlan {
11137 u32 wsFlags; /* WHERE_* flags that describe the strategy */
11138 u16 nEq; /* Number of == constraints */
11139 u16 nOBSat; /* Number of ORDER BY terms satisfied */
11140 double nRow; /* Estimated number of rows (for EQP) */
11141 union {
11142 Index *pIdx; /* Index when WHERE_INDEXED is true */
11143 struct WhereTerm *pTerm; /* WHERE clause term for OR-search */
11144 sqlite3_index_info *pVtabIdx; /* Virtual table index to use */
11145 } u;
11146 };
11147
11148 /*
11149 ** For each nested loop in a WHERE clause implementation, the WhereInfo
11150 ** structure contains a single instance of this structure. This structure
11151 ** is intended to be private to the where.c module and should not be
11152 ** access or modified by other modules.
11153 **
11154 ** The pIdxInfo field is used to help pick the best index on a
11155 ** virtual table. The pIdxInfo pointer contains indexing
11156 ** information for the i-th table in the FROM clause before reordering.
11157 ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
11158 ** All other information in the i-th WhereLevel object for the i-th table
11159 ** after FROM clause ordering.
11160 */
11161 struct WhereLevel {
11162 WherePlan plan; /* query plan for this element of the FROM clause */
11163 int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
11164 int iTabCur; /* The VDBE cursor used to access the table */
11165 int iIdxCur; /* The VDBE cursor used to access pIdx */
11166 int addrBrk; /* Jump here to break out of the loop */
11167 int addrNxt; /* Jump here to start the next IN combination */
11168 int addrCont; /* Jump here to continue with the next loop cycle */
11169 int addrFirst; /* First instruction of interior of the loop */
11170 u8 iFrom; /* Which entry in the FROM clause */
11171 u8 op, p5; /* Opcode and P5 of the opcode that ends the loop */
11172 int p1, p2; /* Operands of the opcode used to ends the loop */
11173 union { /* Information that depends on plan.wsFlags */
11174 struct {
11175 int nIn; /* Number of entries in aInLoop[] */
11176 struct InLoop {
11177 int iCur; /* The VDBE cursor used by this IN operator */
11178 int addrInTop; /* Top of the IN loop */
11179 u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
11180 } *aInLoop; /* Information about each nested IN operator */
11181 } in; /* Used when plan.wsFlags&WHERE_IN_ABLE */
11182 Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
11183 } u;
11184 double rOptCost; /* "Optimal" cost for this level */
11185
11186 /* The following field is really not part of the current level. But
11187 ** we need a place to cache virtual table index information for each
11188 ** virtual table in the FROM clause and the WhereLevel structure is
11189 ** a convenient place since there is one WhereLevel for each FROM clause
11190 ** element.
11191 */
11192 sqlite3_index_info *pIdxInfo; /* Index info for n-th source table */
11193 };
11194
11195 /*
11196 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
11197 ** and the WhereInfo.wctrlFlags member.
11198 */
11199 #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
@@ -11203,37 +11141,15 @@
11203 #define WHERE_DUPLICATES_OK 0x0008 /* Ok to return a row more than once */
11204 #define WHERE_OMIT_OPEN_CLOSE 0x0010 /* Table cursors are already open */
11205 #define WHERE_FORCE_TABLE 0x0020 /* Do not use an index-only search */
11206 #define WHERE_ONETABLE_ONLY 0x0040 /* Only code the 1st table in pTabList */
11207 #define WHERE_AND_ONLY 0x0080 /* Don't use indices for OR terms */
11208
11209 /*
11210 ** The WHERE clause processing routine has two halves. The
11211 ** first part does the start of the WHERE loop and the second
11212 ** half does the tail of the WHERE loop. An instance of
11213 ** this structure is returned by the first half and passed
11214 ** into the second half to give some continuity.
11215 */
11216 struct WhereInfo {
11217 Parse *pParse; /* Parsing and code generating context */
11218 SrcList *pTabList; /* List of tables in the join */
11219 u16 nOBSat; /* Number of ORDER BY terms satisfied by indices */
11220 u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
11221 u8 okOnePass; /* Ok to use one-pass algorithm for UPDATE/DELETE */
11222 u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
11223 u8 eDistinct; /* One of the WHERE_DISTINCT_* values below */
11224 int iTop; /* The very beginning of the WHERE loop */
11225 int iContinue; /* Jump here to continue with next record */
11226 int iBreak; /* Jump here to break out of the loop */
11227 int nLevel; /* Number of nested loop */
11228 struct WhereClause *pWC; /* Decomposition of the WHERE clause */
11229 double savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
11230 double nRowOut; /* Estimated number of output rows */
11231 WhereLevel a[1]; /* Information about each nest loop in WHERE */
11232 };
11233
11234 /* Allowed values for WhereInfo.eDistinct and DistinctCtx.eTnctType */
11235 #define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
11236 #define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
11237 #define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */
11238 #define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */
11239
@@ -11303,11 +11219,11 @@
11303 ExprList *pEList; /* The fields of the result */
11304 u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
11305 u16 selFlags; /* Various SF_* values */
11306 int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
11307 int addrOpenEphm[3]; /* OP_OpenEphem opcodes related to this select */
11308 double nSelectRow; /* Estimated number of result rows */
11309 SrcList *pSrc; /* The FROM clause */
11310 Expr *pWhere; /* The WHERE clause */
11311 ExprList *pGroupBy; /* The GROUP BY clause */
11312 Expr *pHaving; /* The HAVING clause */
11313 ExprList *pOrderBy; /* The ORDER BY clause */
@@ -11487,11 +11403,11 @@
11487 AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
11488
11489 /* Information used while coding trigger programs. */
11490 Parse *pToplevel; /* Parse structure for main program (or NULL) */
11491 Table *pTriggerTab; /* Table triggers are being coded for */
11492 double nQueryLoop; /* Estimated number of iterations of a query */
11493 u32 oldmask; /* Mask of old.* columns referenced */
11494 u32 newmask; /* Mask of new.* columns referenced */
11495 u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
11496 u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
11497 u8 disableTriggers; /* True to disable triggers */
@@ -12057,10 +11973,16 @@
12057 #endif
12058 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
12059 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
12060 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
12061 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
 
 
 
 
 
 
12062 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
12063 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
12064 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
12065 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
12066 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
@@ -19960,17 +19882,11 @@
19960 if( flag_plussign ) prefix = '+';
19961 else if( flag_blanksign ) prefix = ' ';
19962 else prefix = 0;
19963 }
19964 if( xtype==etGENERIC && precision>0 ) precision--;
19965 #if 0
19966 /* Rounding works like BSD when the constant 0.4999 is used. Wierd! */
19967 for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
19968 #else
19969 /* It makes more sense to use 0.5 */
19970 for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
19971 #endif
19972 if( xtype==etFLOAT ) realvalue += rounder;
19973 /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
19974 exp = 0;
19975 if( sqlite3IsNaN((double)realvalue) ){
19976 bufpt = "NaN";
@@ -22931,12 +22847,11 @@
22931 */
22932 #if SQLITE_OS_UNIX /* This file is used on unix only */
22933
22934 /* Use posix_fallocate() if it is available
22935 */
22936 #if !defined(HAVE_POSIX_FALLOCATE) \
22937 && (_XOPEN_SOURCE >= 600 || _POSIX_C_SOURCE >= 200112L)
22938 # define HAVE_POSIX_FALLOCATE 1
22939 #endif
22940
22941 /*
22942 ** There are various methods for file locking used for concurrency
@@ -26866,19 +26781,23 @@
26866 }
26867 return SQLITE_OK;
26868 }
26869 case SQLITE_FCNTL_MMAP_SIZE: {
26870 i64 newLimit = *(i64*)pArg;
 
26871 if( newLimit>sqlite3GlobalConfig.mxMmap ){
26872 newLimit = sqlite3GlobalConfig.mxMmap;
26873 }
26874 *(i64*)pArg = pFile->mmapSizeMax;
26875 if( newLimit>=0 ){
26876 pFile->mmapSizeMax = newLimit;
26877 if( newLimit<pFile->mmapSize ) pFile->mmapSize = newLimit;
 
 
 
26878 }
26879 return SQLITE_OK;
26880 }
26881 #ifdef SQLITE_DEBUG
26882 /* The pager calls this method to signal that it has done
26883 ** a rollback and that the database is therefore unchanged and
26884 ** it hence it is OK for the transaction change counter to be
@@ -28244,11 +28163,11 @@
28244 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
28245 pNew->h = h;
28246 pNew->pVfs = pVfs;
28247 pNew->zPath = zFilename;
28248 pNew->ctrlFlags = (u8)ctrlFlags;
28249 pNew->mmapSizeMax = sqlite3GlobalConfig.mxMmap;
28250 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
28251 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
28252 pNew->ctrlFlags |= UNIXFILE_PSOW;
28253 }
28254 if( strcmp(pVfs->zName,"unix-excl")==0 ){
@@ -30799,17 +30718,10 @@
30799 ** This file mapping API is common to both Win32 and WinRT.
30800 */
30801 WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
30802 #endif /* SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL) */
30803
30804 /*
30805 ** Macro to find the minimum of two numeric values.
30806 */
30807 #ifndef MIN
30808 # define MIN(x,y) ((x)<(y)?(x):(y))
30809 #endif
30810
30811 /*
30812 ** Some Microsoft compilers lack this definition.
30813 */
30814 #ifndef INVALID_FILE_ATTRIBUTES
30815 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
@@ -33531,10 +33443,13 @@
33531 }
33532 }
33533
33534 /* Forward declaration */
33535 static int getTempname(int nBuf, char *zBuf);
 
 
 
33536
33537 /*
33538 ** Control and query of the open file handle.
33539 */
33540 static int winFileControl(sqlite3_file *id, int op, void *pArg){
@@ -33614,17 +33529,24 @@
33614 return SQLITE_OK;
33615 }
33616 #if SQLITE_MAX_MMAP_SIZE>0
33617 case SQLITE_FCNTL_MMAP_SIZE: {
33618 i64 newLimit = *(i64*)pArg;
 
33619 if( newLimit>sqlite3GlobalConfig.mxMmap ){
33620 newLimit = sqlite3GlobalConfig.mxMmap;
33621 }
33622 *(i64*)pArg = pFile->mmapSizeMax;
33623 if( newLimit>=0 ) pFile->mmapSizeMax = newLimit;
33624 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
33625 return SQLITE_OK;
 
 
 
 
 
 
33626 }
33627 #endif
33628 }
33629 OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
33630 return SQLITE_NOTFOUND;
@@ -33652,19 +33574,19 @@
33652 winFile *p = (winFile*)id;
33653 return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
33654 ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
33655 }
33656
33657 #ifndef SQLITE_OMIT_WAL
33658
33659 /*
33660 ** Windows will only let you create file view mappings
33661 ** on allocation size granularity boundaries.
33662 ** During sqlite3_os_init() we do a GetSystemInfo()
33663 ** to get the granularity size.
33664 */
33665 SYSTEM_INFO winSysInfo;
 
 
33666
33667 /*
33668 ** Helper functions to obtain and relinquish the global mutex. The
33669 ** global mutex is used to protect the winLockInfo objects used by
33670 ** this file, all of which may be shared by multiple threads.
@@ -34961,11 +34883,11 @@
34961 #if SQLITE_MAX_MMAP_SIZE>0
34962 pFile->hMap = NULL;
34963 pFile->pMapRegion = 0;
34964 pFile->mmapSize = 0;
34965 pFile->mmapSizeActual = 0;
34966 pFile->mmapSizeMax = sqlite3GlobalConfig.mxMmap;
34967 #endif
34968
34969 OpenCounter(+1);
34970 return rc;
34971 }
@@ -37220,11 +37142,11 @@
37220 PCache1 *pCache; /* The newly created page cache */
37221 PGroup *pGroup; /* The group the new page cache will belong to */
37222 int sz; /* Bytes of memory required to allocate the new cache */
37223
37224 /*
37225 ** The seperateCache variable is true if each PCache has its own private
37226 ** PGroup. In other words, separateCache is true for mode (1) where no
37227 ** mutexing is required.
37228 **
37229 ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
37230 **
@@ -42544,11 +42466,12 @@
42544 /* Before the first write, give the VFS a hint of what the final
42545 ** file size will be.
42546 */
42547 assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
42548 if( rc==SQLITE_OK
42549 && (pList->pDirty ? pPager->dbSize : pList->pgno+1)>pPager->dbHintSize
 
42550 ){
42551 sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
42552 sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
42553 pPager->dbHintSize = pPager->dbSize;
42554 }
@@ -43509,11 +43432,11 @@
43509 ** requested page is not already stored in the cache, then no
43510 ** actual disk read occurs. In this case the memory image of the
43511 ** page is initialized to all zeros.
43512 **
43513 ** If noContent is true, it means that we do not care about the contents
43514 ** of the page. This occurs in two seperate scenarios:
43515 **
43516 ** a) When reading a free-list leaf page from the database, and
43517 **
43518 ** b) When a savepoint is being rolled back and we need to load
43519 ** a new page into the cache to be filled with the data read
@@ -44919,11 +44842,31 @@
44919 pagerReportSize(pPager);
44920 }
44921 SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
44922 return pPager->pCodec;
44923 }
44924 #endif
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44925
44926 #ifndef SQLITE_OMIT_AUTOVACUUM
44927 /*
44928 ** Move the page pPg to location pgno in the file.
44929 **
@@ -45474,25 +45417,10 @@
45474 assert( pPager->eState==PAGER_READER );
45475 return sqlite3WalFramesize(pPager->pWal);
45476 }
45477 #endif
45478
45479 #ifdef SQLITE_HAS_CODEC
45480 /*
45481 ** This function is called by the wal module when writing page content
45482 ** into the log file.
45483 **
45484 ** This function returns a pointer to a buffer containing the encrypted
45485 ** page content. If a malloc fails, this function may return NULL.
45486 */
45487 SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
45488 void *aData = 0;
45489 CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
45490 return aData;
45491 }
45492 #endif /* SQLITE_HAS_CODEC */
45493
45494 #endif /* SQLITE_OMIT_DISKIO */
45495
45496 /************** End of pager.c ***********************************************/
45497 /************** Begin file wal.c *********************************************/
45498 /*
@@ -50759,11 +50687,11 @@
50759 if( rc ) return rc;
50760 top = get2byteNotZero(&data[hdr+5]);
50761 }else if( gap+2<=top ){
50762 /* Search the freelist looking for a free slot big enough to satisfy
50763 ** the request. The allocation is made from the first free slot in
50764 ** the list that is large enough to accomadate it.
50765 */
50766 int pc, addr;
50767 for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
50768 int size; /* Size of the free slot */
50769 if( pc>usableSize-4 || pc<addr+4 ){
@@ -52702,11 +52630,11 @@
52702 return rc;
52703 }
52704
52705 /*
52706 ** This routine is called prior to sqlite3PagerCommit when a transaction
52707 ** is commited for an auto-vacuum database.
52708 **
52709 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
52710 ** the database file should be truncated to during the commit process.
52711 ** i.e. the database has been reorganized so that only the first *pnTrunc
52712 ** pages are in use.
@@ -58045,16 +57973,10 @@
58045 *************************************************************************
58046 ** This file contains the implementation of the sqlite3_backup_XXX()
58047 ** API functions and the related features.
58048 */
58049
58050 /* Macro to find the minimum of two numeric values.
58051 */
58052 #ifndef MIN
58053 # define MIN(x,y) ((x)<(y)?(x):(y))
58054 #endif
58055
58056 /*
58057 ** Structure allocated for each backup operation.
58058 */
58059 struct sqlite3_backup {
58060 sqlite3* pDestDb; /* Destination database handle */
@@ -61942,11 +61864,11 @@
61942 /*
61943 ** If the Vdbe passed as the first argument opened a statement-transaction,
61944 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
61945 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
61946 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
61947 ** statement transaction is commtted.
61948 **
61949 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
61950 ** Otherwise SQLITE_OK.
61951 */
61952 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
@@ -64011,17 +63933,10 @@
64011 int iType = sqlite3_value_type( columnMem(pStmt,i) );
64012 columnMallocFailure(pStmt);
64013 return iType;
64014 }
64015
64016 /* The following function is experimental and subject to change or
64017 ** removal */
64018 /*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
64019 ** return sqlite3_value_numeric_type( columnMem(pStmt,i) );
64020 **}
64021 */
64022
64023 /*
64024 ** Convert the N-th element of pStmt->pColName[] into a string using
64025 ** xFunc() then return that string. If N is out of range, return 0.
64026 **
64027 ** There are up to 5 names for each column. useType determines which
@@ -64643,18 +64558,18 @@
64643 pVar = &utf8;
64644 }
64645 #endif
64646 nOut = pVar->n;
64647 #ifdef SQLITE_TRACE_SIZE_LIMIT
64648 if( n>SQLITE_TRACE_SIZE_LIMIT ){
64649 nOut = SQLITE_TRACE_SIZE_LIMIT;
64650 while( nOut<pVar->n && (pVar->z[n]&0xc0)==0x80 ){ n++; }
64651 }
64652 #endif
64653 sqlite3XPrintf(&out, "'%.*q'", nOut, pVar->z);
64654 #ifdef SQLITE_TRACE_SIZE_LIMIT
64655 if( nOut<pVar->n ) sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-n);
64656 #endif
64657 #ifndef SQLITE_OMIT_UTF16
64658 if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
64659 #endif
64660 }else if( pVar->flags & MEM_Zero ){
@@ -64670,11 +64585,11 @@
64670 for(i=0; i<nOut; i++){
64671 sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
64672 }
64673 sqlite3StrAccumAppend(&out, "'", 1);
64674 #ifdef SQLITE_TRACE_SIZE_LIMIT
64675 if( nOut<pVar->n ) sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-n);
64676 #endif
64677 }
64678 }
64679 }
64680 return sqlite3StrAccumFinish(&out);
@@ -68269,12 +68184,12 @@
68269 ** If P2 is non-zero, then a write-transaction is started. A RESERVED lock is
68270 ** obtained on the database file when a write-transaction is started. No
68271 ** other process can start another write transaction while this transaction is
68272 ** underway. Starting a write transaction also creates a rollback journal. A
68273 ** write transaction must be started before any changes can be made to the
68274 ** database. If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
68275 ** on the file.
68276 **
68277 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
68278 ** true (this flag is set if the Vdbe may modify more than one row and may
68279 ** throw an ABORT exception), a statement transaction may also be opened.
68280 ** More specifically, a statement transaction is opened iff the database
@@ -72224,11 +72139,11 @@
72224 **
72225 ** For the purposes of this comparison, EOF is considered greater than any
72226 ** other key value. If the keys are equal (only possible with two EOF
72227 ** values), it doesn't matter which index is stored.
72228 **
72229 ** The (N/4) elements of aTree[] that preceed the final (N/2) described
72230 ** above contains the index of the smallest of each block of 4 iterators.
72231 ** And so on. So that aTree[1] contains the index of the iterator that
72232 ** currently points to the smallest key value. aTree[0] is unused.
72233 **
72234 ** Example:
@@ -73499,16 +73414,10 @@
73499 ** a power-of-two allocation. This mimimizes wasted space in power-of-two
73500 ** memory allocators.
73501 */
73502 #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
73503
73504 /* Macro to find the minimum of two numeric values.
73505 */
73506 #ifndef MIN
73507 # define MIN(x,y) ((x)<(y)?(x):(y))
73508 #endif
73509
73510 /*
73511 ** The rollback journal is composed of a linked list of these structures.
73512 */
73513 struct FileChunk {
73514 FileChunk *pNext; /* Next chunk in the journal */
@@ -75045,12 +74954,12 @@
75045 **
75046 ** Minor point: If this is the case, then the expression will be
75047 ** re-evaluated for each reference to it.
75048 */
75049 sNC.pEList = p->pEList;
75050 if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
75051 sNC.ncFlags |= NC_AsMaybe;
 
75052 if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
75053 sNC.ncFlags &= ~NC_AsMaybe;
75054
75055 /* The ORDER BY and GROUP BY clauses may not refer to terms in
75056 ** outer queries
@@ -76817,19 +76726,19 @@
76817
76818 if( eType==0 ){
76819 /* Could not found an existing table or index to use as the RHS b-tree.
76820 ** We will have to generate an ephemeral table to do the job.
76821 */
76822 double savedNQueryLoop = pParse->nQueryLoop;
76823 int rMayHaveNull = 0;
76824 eType = IN_INDEX_EPH;
76825 if( prNotFound ){
76826 *prNotFound = rMayHaveNull = ++pParse->nMem;
76827 sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
76828 }else{
76829 testcase( pParse->nQueryLoop>(double)1 );
76830 pParse->nQueryLoop = (double)1;
76831 if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
76832 eType = IN_INDEX_ROWID;
76833 }
76834 }
76835 sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
@@ -76867,11 +76776,11 @@
76867 ** the register given by rMayHaveNull to NULL. Calling routines will take
76868 ** care of changing this register value to non-NULL if the RHS is NULL-free.
76869 **
76870 ** If rMayHaveNull is zero, that means that the subquery is being used
76871 ** for membership testing only. There is no need to initialize any
76872 ** registers to indicate the presense or absence of NULLs on the RHS.
76873 **
76874 ** For a SELECT or EXISTS operator, return the register that holds the
76875 ** result. For IN operators or if an error occurs, the return value is 0.
76876 */
76877 #ifndef SQLITE_OMIT_SUBQUERY
@@ -80267,11 +80176,11 @@
80267 **
80268 ** Additional tables might be added in future releases of SQLite.
80269 ** The sqlite_stat2 table is not created or used unless the SQLite version
80270 ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
80271 ** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated.
80272 ** The sqlite_stat2 table is superceded by sqlite_stat3, which is only
80273 ** created and used by SQLite versions 3.7.9 and later and with
80274 ** SQLITE_ENABLE_STAT3 defined. The fucntionality of sqlite_stat3
80275 ** is a superset of sqlite_stat2.
80276 **
80277 ** Format of sqlite_stat1:
@@ -83455,10 +83364,11 @@
83455 zColl = sqlite3NameFromToken(db, pToken);
83456 if( !zColl ) return;
83457
83458 if( sqlite3LocateCollSeq(pParse, zColl) ){
83459 Index *pIdx;
 
83460 p->aCol[i].zColl = zColl;
83461
83462 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
83463 ** then an index may have been created on this column before the
83464 ** collation type was added. Correct this if it is the case.
@@ -84874,10 +84784,11 @@
84874 zExtra = (char *)(&pIndex->zName[nName+1]);
84875 memcpy(pIndex->zName, zName, nName+1);
84876 pIndex->pTable = pTab;
84877 pIndex->nColumn = pList->nExpr;
84878 pIndex->onError = (u8)onError;
 
84879 pIndex->autoIndex = (u8)(pName==0);
84880 pIndex->pSchema = db->aDb[iDb].pSchema;
84881 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
84882
84883 /* Check to see if we should honor DESC requests on index columns
@@ -84932,10 +84843,11 @@
84932 goto exit_create_index;
84933 }
84934 pIndex->azColl[i] = zColl;
84935 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
84936 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
 
84937 }
84938 sqlite3DefaultRowEst(pIndex);
84939
84940 if( pTab==pParse->pNewTable ){
84941 /* This routine has been called to create an automatic index as a
@@ -85363,19 +85275,19 @@
85363 assert( db->mallocFailed );
85364 return pSrc;
85365 }
85366 pSrc = pNew;
85367 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
85368 pSrc->nAlloc = (u16)nGot;
85369 }
85370
85371 /* Move existing slots that come after the newly inserted slots
85372 ** out of the way */
85373 for(i=pSrc->nSrc-1; i>=iStart; i--){
85374 pSrc->a[i+nExtra] = pSrc->a[i];
85375 }
85376 pSrc->nSrc += (i16)nExtra;
85377
85378 /* Zero the newly allocated slots */
85379 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
85380 for(i=iStart; i<iStart+nExtra; i++){
85381 pSrc->a[i].iCursor = -1;
@@ -87378,11 +87290,11 @@
87378 ** of x. If x is text, then we actually count UTF-8 characters.
87379 ** If x is a blob, then we count bytes.
87380 **
87381 ** If p1 is negative, then we begin abs(p1) from the end of x[].
87382 **
87383 ** If p2 is negative, return the p2 characters preceeding p1.
87384 */
87385 static void substrFunc(
87386 sqlite3_context *context,
87387 int argc,
87388 sqlite3_value **argv
@@ -88037,14 +87949,10 @@
88037 '0', '1', '2', '3', '4', '5', '6', '7',
88038 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
88039 };
88040
88041 /*
88042 ** EXPERIMENTAL - This is not an official function. The interface may
88043 ** change. This function may disappear. Do not write code that depends
88044 ** on this function.
88045 **
88046 ** Implementation of the QUOTE() function. This function takes a single
88047 ** argument. If the argument is numeric, the return value is the same as
88048 ** the argument. If the argument is NULL, the return value is the string
88049 ** "NULL". Otherwise, the argument is enclosed in single quotes with
88050 ** single-quote escapes.
@@ -88229,11 +88137,11 @@
88229 }
88230
88231 /*
88232 ** The replace() function. Three arguments are all strings: call
88233 ** them A, B, and C. The result is also a string which is derived
88234 ** from A by replacing every occurance of B with C. The match
88235 ** must be exact. Collating sequences are not used.
88236 */
88237 static void replaceFunc(
88238 sqlite3_context *context,
88239 int argc,
@@ -94147,15 +94055,19 @@
94147 sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
94148 }
94149 }
94150 }
94151 sz = -1;
94152 if( sqlite3_file_control(db,zDb,SQLITE_FCNTL_MMAP_SIZE,&sz)==SQLITE_OK ){
94153 #if SQLITE_MAX_MMAP_SIZE==0
94154 sz = 0;
94155 #endif
 
94156 returnSingleInt(pParse, "mmap_size", sz);
 
 
 
94157 }
94158 }else
94159
94160 /*
94161 ** PRAGMA temp_store
@@ -94682,11 +94594,11 @@
94682 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
94683 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
94684 #endif
94685
94686 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
94687 /* Pragma "quick_check" is an experimental reduced version of
94688 ** integrity_check designed to detect most database corruption
94689 ** without most of the overhead of a full integrity-check.
94690 */
94691 if( sqlite3StrICmp(zLeft, "integrity_check")==0
94692 || sqlite3StrICmp(zLeft, "quick_check")==0
@@ -95140,14 +95052,14 @@
95140 }else
95141 #endif
95142
95143 #ifdef SQLITE_HAS_CODEC
95144 if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
95145 sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
95146 }else
95147 if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
95148 sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
95149 }else
95150 if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
95151 sqlite3StrICmp(zLeft, "hexrekey")==0) ){
95152 int i, h1, h2;
95153 char zKey[40];
@@ -95155,13 +95067,13 @@
95155 h1 += 9*(1&(h1>>6));
95156 h2 += 9*(1&(h2>>6));
95157 zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
95158 }
95159 if( (zLeft[3] & 0xf)==0xb ){
95160 sqlite3_key(db, zKey, i/2);
95161 }else{
95162 sqlite3_rekey(db, zKey, i/2);
95163 }
95164 }else
95165 #endif
95166 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
95167 if( sqlite3StrICmp(zLeft, "activate_extensions")==0 && zRight ){
@@ -95792,11 +95704,11 @@
95792 }
95793
95794 sqlite3VtabUnlockList(db);
95795
95796 pParse->db = db;
95797 pParse->nQueryLoop = (double)1;
95798 if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
95799 char *zSqlCopy;
95800 int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
95801 testcase( nBytes==mxLen );
95802 testcase( nBytes==mxLen+1 );
@@ -95814,11 +95726,11 @@
95814 pParse->zTail = &zSql[nBytes];
95815 }
95816 }else{
95817 sqlite3RunParser(pParse, zSql, &zErrMsg);
95818 }
95819 assert( 1==(int)pParse->nQueryLoop );
95820
95821 if( db->mallocFailed ){
95822 pParse->rc = SQLITE_NOMEM;
95823 }
95824 if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
@@ -96178,11 +96090,11 @@
96178 sqlite3DbFree(db, p);
96179 }
96180 }
96181
96182 /*
96183 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
96184 ** type of join. Return an integer constant that expresses that type
96185 ** in terms of the following bit values:
96186 **
96187 ** JT_INNER
96188 ** JT_CROSS
@@ -97592,11 +97504,11 @@
97592 int addr1, n;
97593 if( p->iLimit ) return;
97594
97595 /*
97596 ** "LIMIT -1" always shows all rows. There is some
97597 ** contraversy about what the correct behavior should be.
97598 ** The current implementation interprets "LIMIT 0" to mean
97599 ** no rows.
97600 */
97601 sqlite3ExprCacheClear(pParse);
97602 assert( p->pOffset==0 || p->pLimit!=0 );
@@ -97607,12 +97519,12 @@
97607 if( sqlite3ExprIsInteger(p->pLimit, &n) ){
97608 sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
97609 VdbeComment((v, "LIMIT counter"));
97610 if( n==0 ){
97611 sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
97612 }else{
97613 if( p->nSelectRow > (double)n ) p->nSelectRow = (double)n;
97614 }
97615 }else{
97616 sqlite3ExprCode(pParse, p->pLimit, iLimit);
97617 sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
97618 VdbeComment((v, "LIMIT counter"));
@@ -97802,13 +97714,13 @@
97802 pDelete = p->pPrior;
97803 p->pPrior = pPrior;
97804 p->nSelectRow += pPrior->nSelectRow;
97805 if( pPrior->pLimit
97806 && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
97807 && p->nSelectRow > (double)nLimit
97808 ){
97809 p->nSelectRow = (double)nLimit;
97810 }
97811 if( addr ){
97812 sqlite3VdbeJumpHere(v, addr);
97813 }
97814 break;
@@ -99953,15 +99865,14 @@
99953 Parse *pParse, /* Parse context */
99954 Table *pTab, /* Table being queried */
99955 Index *pIdx /* Index used to optimize scan, or NULL */
99956 ){
99957 if( pParse->explain==2 ){
99958 char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s %s%s(~%d rows)",
99959 pTab->zName,
99960 pIdx ? "USING COVERING INDEX " : "",
99961 pIdx ? pIdx->zName : "",
99962 pTab->nRowEst
99963 );
99964 sqlite3VdbeAddOp4(
99965 pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
99966 );
99967 }
@@ -100115,11 +100026,11 @@
100115 }
100116 continue;
100117 }
100118
100119 /* Increment Parse.nHeight by the height of the largest expression
100120 ** tree refered to by this, the parent select. The child select
100121 ** may contain expression trees of at most
100122 ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
100123 ** more conservative than necessary, but much easier than enforcing
100124 ** an exact limit.
100125 */
@@ -100308,11 +100219,11 @@
100308 }
100309
100310 /* Set the limiter.
100311 */
100312 iEnd = sqlite3VdbeMakeLabel(v);
100313 p->nSelectRow = (double)LARGEST_INT64;
100314 computeLimitRegisters(pParse, p, iEnd);
100315 if( p->iLimit==0 && addrSortIndex>=0 ){
100316 sqlite3VdbeGetOp(v, addrSortIndex)->opcode = OP_SorterOpen;
100317 p->selFlags |= SF_UseSorter;
100318 }
@@ -100336,13 +100247,17 @@
100336 ExprList *pDist = (sDistinct.isTnct ? p->pEList : 0);
100337
100338 /* Begin the database scan. */
100339 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pOrderBy, pDist, 0,0);
100340 if( pWInfo==0 ) goto select_end;
100341 if( pWInfo->nRowOut < p->nSelectRow ) p->nSelectRow = pWInfo->nRowOut;
100342 if( pWInfo->eDistinct ) sDistinct.eTnctType = pWInfo->eDistinct;
100343 if( pOrderBy && pWInfo->nOBSat==pOrderBy->nExpr ) pOrderBy = 0;
 
 
 
 
100344
100345 /* If sorting index that was created by a prior OP_OpenEphemeral
100346 ** instruction ended up not being needed, then change the OP_OpenEphemeral
100347 ** into an OP_Noop.
100348 */
@@ -100351,11 +100266,12 @@
100351 p->addrOpenEphm[2] = -1;
100352 }
100353
100354 /* Use the standard inner loop. */
100355 selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, &sDistinct, pDest,
100356 pWInfo->iContinue, pWInfo->iBreak);
 
100357
100358 /* End the database scan loop.
100359 */
100360 sqlite3WhereEnd(pWInfo);
100361 }else{
@@ -100384,13 +100300,13 @@
100384 pItem->iAlias = 0;
100385 }
100386 for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
100387 pItem->iAlias = 0;
100388 }
100389 if( p->nSelectRow>(double)100 ) p->nSelectRow = (double)100;
100390 }else{
100391 p->nSelectRow = (double)1;
100392 }
100393
100394
100395 /* Create a label to jump to when we want to abort the query */
100396 addrEnd = sqlite3VdbeMakeLabel(v);
@@ -100466,13 +100382,14 @@
100466 ** This might involve two separate loops with an OP_Sort in between, or
100467 ** it might be a single loop that uses an index to extract information
100468 ** in the right order to begin with.
100469 */
100470 sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
100471 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0, 0, 0);
 
100472 if( pWInfo==0 ) goto select_end;
100473 if( pWInfo->nOBSat==pGroupBy->nExpr ){
100474 /* The optimizer is able to deliver rows in group by order so
100475 ** we do not have to sort. The OP_OpenEphemeral table will be
100476 ** cancelled later because we still need to use the pKeyInfo
100477 */
100478 groupBySort = 0;
@@ -100749,12 +100666,12 @@
100749 sqlite3ExprListDelete(db, pDel);
100750 goto select_end;
100751 }
100752 updateAccumulator(pParse, &sAggInfo);
100753 assert( pMinMax==0 || pMinMax->nExpr==1 );
100754 if( pWInfo->nOBSat>0 ){
100755 sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
100756 VdbeComment((v, "%s() by index",
100757 (flag==WHERE_ORDERBY_MIN?"min":"max")));
100758 }
100759 sqlite3WhereEnd(pWInfo);
100760 finalizeAggFunctions(pParse, &sAggInfo);
@@ -102109,11 +102026,11 @@
102109 }
102110
102111 /*
102112 ** This is called to code the required FOR EACH ROW triggers for an operation
102113 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
102114 ** is given by the op paramater. The tr_tm parameter determines whether the
102115 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
102116 ** parameter pChanges is passed the list of columns being modified.
102117 **
102118 ** If there are no triggers that fire at the specified time for the specified
102119 ** operation on pTab, this function is a no-op.
@@ -102560,11 +102477,11 @@
102560 sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
102561 pWInfo = sqlite3WhereBegin(
102562 pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, 0
102563 );
102564 if( pWInfo==0 ) goto update_cleanup;
102565 okOnePass = pWInfo->okOnePass;
102566
102567 /* Remember the rowid of every item to be updated.
102568 */
102569 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
102570 if( !okOnePass ){
@@ -104397,22 +104314,165 @@
104397 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
104398 /***/ int sqlite3WhereTrace = 0;
104399 #endif
104400 #if defined(SQLITE_DEBUG) \
104401 && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
104402 # define WHERETRACE(X) if(sqlite3WhereTrace) sqlite3DebugPrintf X
 
104403 #else
104404 # define WHERETRACE(X)
104405 #endif
104406
104407 /* Forward reference
104408 */
104409 typedef struct WhereClause WhereClause;
104410 typedef struct WhereMaskSet WhereMaskSet;
104411 typedef struct WhereOrInfo WhereOrInfo;
104412 typedef struct WhereAndInfo WhereAndInfo;
104413 typedef struct WhereCost WhereCost;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104414
104415 /*
104416 ** The query generator uses an array of instances of this structure to
104417 ** help it analyze the subexpressions of the WHERE clause. Each WHERE
104418 ** clause subexpression is separated from the others by AND operators,
@@ -104461,11 +104521,10 @@
104461 **
104462 ** The number of terms in a join is limited by the number of bits
104463 ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
104464 ** is only able to process joins with 64 or fewer tables.
104465 */
104466 typedef struct WhereTerm WhereTerm;
104467 struct WhereTerm {
104468 Expr *pExpr; /* Pointer to the subexpression that is this term */
104469 int iParent; /* Disable pWC->a[iParent] when this term disabled */
104470 int leftCursor; /* Cursor number of X in "X <op> <expr>" */
104471 union {
@@ -104495,10 +104554,26 @@
104495 # define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
104496 #else
104497 # define TERM_VNULL 0x00 /* Disabled if not using stat3 */
104498 #endif
104499
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104500 /*
104501 ** An instance of the following structure holds all information about a
104502 ** WHERE clause. Mostly this is a container for one or more WhereTerms.
104503 **
104504 ** Explanation of pOuter: For a WHERE clause of the form
@@ -104508,15 +104583,13 @@
104508 ** There are separate WhereClause objects for the whole clause and for
104509 ** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
104510 ** subclauses points to the WhereClause object for the whole clause.
104511 */
104512 struct WhereClause {
104513 Parse *pParse; /* The parser context */
104514 WhereMaskSet *pMaskSet; /* Mapping of table cursor numbers to bitmasks */
104515 WhereClause *pOuter; /* Outer conjunction */
104516 u8 op; /* Split operator. TK_AND or TK_OR */
104517 u16 wctrlFlags; /* Might include WHERE_AND_ONLY */
104518 int nTerm; /* Number of terms */
104519 int nSlot; /* Number of entries in a[] */
104520 WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
104521 #if defined(SQLITE_SMALL_STACK)
104522 WhereTerm aStatic[1]; /* Initial static space for a[] */
@@ -104572,23 +104645,59 @@
104572 int n; /* Number of assigned cursor values */
104573 int ix[BMS]; /* Cursor assigned to each bit */
104574 };
104575
104576 /*
104577 ** A WhereCost object records a lookup strategy and the estimated
104578 ** cost of pursuing that strategy.
104579 */
104580 struct WhereCost {
104581 WherePlan plan; /* The lookup strategy */
104582 double rCost; /* Overall cost of pursuing this search strategy */
104583 Bitmask used; /* Bitmask of cursors used by this plan */
 
 
104584 };
104585
104586 /*
104587 ** Bitmasks for the operators that indices are able to exploit. An
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104588 ** OR-ed combination of these values can be used when searching for
104589 ** terms in the where clause.
104590 */
104591 #define WO_IN 0x001
104592 #define WO_EQ 0x002
104593 #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
104594 #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
@@ -104603,96 +104712,106 @@
104603
104604 #define WO_ALL 0xfff /* Mask of all possible WO_* values */
104605 #define WO_SINGLE 0x0ff /* Mask of all non-compound WO_* values */
104606
104607 /*
104608 ** Value for wsFlags returned by bestIndex() and stored in
104609 ** WhereLevel.wsFlags. These flags determine which search
104610 ** strategies are appropriate.
104611 **
104612 ** The least significant 12 bits is reserved as a mask for WO_ values above.
104613 ** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
104614 ** But if the table is the right table of a left join, WhereLevel.wsFlags
104615 ** is set to WO_IN|WO_EQ. The WhereLevel.wsFlags field can then be used as
104616 ** the "op" parameter to findTerm when we are resolving equality constraints.
104617 ** ISNULL constraints will then not be used on the right table of a left
104618 ** join. Tickets #2177 and #2189.
104619 */
104620 #define WHERE_ROWID_EQ 0x00001000 /* rowid=EXPR or rowid IN (...) */
104621 #define WHERE_ROWID_RANGE 0x00002000 /* rowid<EXPR and/or rowid>EXPR */
104622 #define WHERE_COLUMN_EQ 0x00010000 /* x=EXPR or x IN (...) or x IS NULL */
104623 #define WHERE_COLUMN_RANGE 0x00020000 /* x<EXPR and/or x>EXPR */
104624 #define WHERE_COLUMN_IN 0x00040000 /* x IN (...) */
104625 #define WHERE_COLUMN_NULL 0x00080000 /* x IS NULL */
104626 #define WHERE_INDEXED 0x000f0000 /* Anything that uses an index */
104627 #define WHERE_NOT_FULLSCAN 0x100f3000 /* Does not do a full table scan */
104628 #define WHERE_IN_ABLE 0x080f1000 /* Able to support an IN operator */
104629 #define WHERE_TOP_LIMIT 0x00100000 /* x<EXPR or x<=EXPR constraint */
104630 #define WHERE_BTM_LIMIT 0x00200000 /* x>EXPR or x>=EXPR constraint */
104631 #define WHERE_BOTH_LIMIT 0x00300000 /* Both x>EXPR and x<EXPR */
104632 #define WHERE_IDX_ONLY 0x00400000 /* Use index only - omit table */
104633 #define WHERE_ORDERED 0x00800000 /* Output will appear in correct order */
104634 #define WHERE_REVERSE 0x01000000 /* Scan in reverse order */
104635 #define WHERE_UNIQUE 0x02000000 /* Selects no more than one row */
104636 #define WHERE_ALL_UNIQUE 0x04000000 /* This and all prior have one row */
104637 #define WHERE_OB_UNIQUE 0x00004000 /* Values in ORDER BY columns are
104638 ** different for every output row */
104639 #define WHERE_VIRTUALTABLE 0x08000000 /* Use virtual-table processing */
104640 #define WHERE_MULTI_OR 0x10000000 /* OR using multiple indices */
104641 #define WHERE_TEMP_INDEX 0x20000000 /* Uses an ephemeral index */
104642 #define WHERE_DISTINCT 0x40000000 /* Correct order for DISTINCT */
104643 #define WHERE_COVER_SCAN 0x80000000 /* Full scan of a covering index */
104644
104645 /*
104646 ** This module contains many separate subroutines that work together to
104647 ** find the best indices to use for accessing a particular table in a query.
104648 ** An instance of the following structure holds context information about the
104649 ** index search so that it can be more easily passed between the various
104650 ** routines.
104651 */
104652 typedef struct WhereBestIdx WhereBestIdx;
104653 struct WhereBestIdx {
104654 Parse *pParse; /* Parser context */
104655 WhereClause *pWC; /* The WHERE clause */
104656 struct SrcList_item *pSrc; /* The FROM clause term to search */
104657 Bitmask notReady; /* Mask of cursors not available */
104658 Bitmask notValid; /* Cursors not available for any purpose */
104659 ExprList *pOrderBy; /* The ORDER BY clause */
104660 ExprList *pDistinct; /* The select-list if query is DISTINCT */
104661 sqlite3_index_info **ppIdxInfo; /* Index information passed to xBestIndex */
104662 int i, n; /* Which loop is being coded; # of loops */
104663 WhereLevel *aLevel; /* Info about outer loops */
104664 WhereCost cost; /* Lowest cost query plan */
104665 };
104666
104667 /*
104668 ** Return TRUE if the probe cost is less than the baseline cost
104669 */
104670 static int compareCost(const WhereCost *pProbe, const WhereCost *pBaseline){
104671 if( pProbe->rCost<pBaseline->rCost ) return 1;
104672 if( pProbe->rCost>pBaseline->rCost ) return 0;
104673 if( pProbe->plan.nOBSat>pBaseline->plan.nOBSat ) return 1;
104674 if( pProbe->plan.nRow<pBaseline->plan.nRow ) return 1;
104675 return 0;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104676 }
104677
104678 /*
104679 ** Initialize a preallocated WhereClause structure.
104680 */
104681 static void whereClauseInit(
104682 WhereClause *pWC, /* The WhereClause to be initialized */
104683 Parse *pParse, /* The parsing context */
104684 WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmasks */
104685 u16 wctrlFlags /* Might include WHERE_AND_ONLY */
104686 ){
104687 pWC->pParse = pParse;
104688 pWC->pMaskSet = pMaskSet;
104689 pWC->pOuter = 0;
104690 pWC->nTerm = 0;
104691 pWC->nSlot = ArraySize(pWC->aStatic);
104692 pWC->a = pWC->aStatic;
104693 pWC->wctrlFlags = wctrlFlags;
104694 }
104695
104696 /* Forward reference */
104697 static void whereClauseClear(WhereClause*);
104698
@@ -104717,11 +104836,11 @@
104717 ** itself is not freed. This routine is the inverse of whereClauseInit().
104718 */
104719 static void whereClauseClear(WhereClause *pWC){
104720 int i;
104721 WhereTerm *a;
104722 sqlite3 *db = pWC->pParse->db;
104723 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
104724 if( a->wtFlags & TERM_DYNAMIC ){
104725 sqlite3ExprDelete(db, a->pExpr);
104726 }
104727 if( a->wtFlags & TERM_ORINFO ){
@@ -104758,11 +104877,11 @@
104758 WhereTerm *pTerm;
104759 int idx;
104760 testcase( wtFlags & TERM_VIRTUAL ); /* EV: R-00211-15100 */
104761 if( pWC->nTerm>=pWC->nSlot ){
104762 WhereTerm *pOld = pWC->a;
104763 sqlite3 *db = pWC->pParse->db;
104764 pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
104765 if( pWC->a==0 ){
104766 if( wtFlags & TERM_DYNAMIC ){
104767 sqlite3ExprDelete(db, p);
104768 }
@@ -104798,12 +104917,12 @@
104798 **
104799 ** In the previous sentence and in the diagram, "slot[]" refers to
104800 ** the WhereClause.a[] array. The slot[] array grows as needed to contain
104801 ** all terms of the WHERE clause.
104802 */
104803 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
104804 pWC->op = (u8)op;
104805 if( pExpr==0 ) return;
104806 if( pExpr->op!=op ){
104807 whereClauseInsert(pWC, pExpr, 0);
104808 }else{
104809 whereSplit(pWC, pExpr->pLeft, op);
@@ -104810,13 +104929,13 @@
104810 whereSplit(pWC, pExpr->pRight, op);
104811 }
104812 }
104813
104814 /*
104815 ** Initialize an expression mask set (a WhereMaskSet object)
104816 */
104817 #define initMaskSet(P) memset(P, 0, sizeof(*P))
104818
104819 /*
104820 ** Return the bitmask for the given cursor number. Return 0 if
104821 ** iCursor is not in the set.
104822 */
@@ -104823,11 +104942,11 @@
104823 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
104824 int i;
104825 assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
104826 for(i=0; i<pMaskSet->n; i++){
104827 if( pMaskSet->ix[i]==iCursor ){
104828 return ((Bitmask)1)<<i;
104829 }
104830 }
104831 return 0;
104832 }
104833
@@ -104843,22 +104962,13 @@
104843 assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
104844 pMaskSet->ix[pMaskSet->n++] = iCursor;
104845 }
104846
104847 /*
104848 ** This routine walks (recursively) an expression tree and generates
104849 ** a bitmask indicating which tables are used in that expression
104850 ** tree.
104851 **
104852 ** In order for this routine to work, the calling function must have
104853 ** previously invoked sqlite3ResolveExprNames() on the expression. See
104854 ** the header comment on that routine for additional information.
104855 ** The sqlite3ResolveExprNames() routines looks for column names and
104856 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
104857 ** the VDBE cursor number of the table. This routine just has to
104858 ** translate the cursor numbers into bitmask values and OR all
104859 ** the bitmasks together.
104860 */
104861 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
104862 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
104863 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
104864 Bitmask mask = 0;
@@ -104908,11 +105018,11 @@
104908 }
104909
104910 /*
104911 ** Return TRUE if the given operator is one of the operators that is
104912 ** allowed for an indexable WHERE clause term. The allowed operators are
104913 ** "=", "<", ">", "<=", ">=", and "IN".
104914 **
104915 ** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
104916 ** of one of the following forms: column = expression column > expression
104917 ** column >= expression column < expression column <= expression
104918 ** expression = column expression > column expression >= column
@@ -104935,14 +105045,13 @@
104935 /*
104936 ** Commute a comparison operator. Expressions of the form "X op Y"
104937 ** are converted into "Y op X".
104938 **
104939 ** If left/right precedence rules come into play when determining the
104940 ** collating
104941 ** side of the comparison, it remains associated with the same side after
104942 ** the commutation. So "Y collate NOCASE op X" becomes
104943 ** "X op Y". This is because any collation sequence on
104944 ** the left hand side of a comparison overrides any collation sequence
104945 ** attached to the right. For the same reason the EP_Collate flag
104946 ** is not commuted.
104947 */
104948 static void exprCommute(Parse *pParse, Expr *pExpr){
@@ -104994,10 +105103,134 @@
104994 assert( op!=TK_LE || c==WO_LE );
104995 assert( op!=TK_GT || c==WO_GT );
104996 assert( op!=TK_GE || c==WO_GE );
104997 return c;
104998 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104999
105000 /*
105001 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
105002 ** where X is a reference to the iColumn of table iCur and <op> is one of
105003 ** the WO_xx operator codes specified by the op parameter.
@@ -105026,98 +105259,32 @@
105026 int iColumn, /* Column number of LHS */
105027 Bitmask notReady, /* RHS must not overlap with this mask */
105028 u32 op, /* Mask of WO_xx values describing operator */
105029 Index *pIdx /* Must be compatible with this index, if not NULL */
105030 ){
105031 WhereTerm *pTerm; /* Term being examined as possible result */
105032 WhereTerm *pResult = 0; /* The answer to return */
105033 WhereClause *pWCOrig = pWC; /* Original pWC value */
105034 int j, k; /* Loop counters */
105035 Expr *pX; /* Pointer to an expression */
105036 Parse *pParse; /* Parsing context */
105037 int iOrigCol = iColumn; /* Original value of iColumn */
105038 int nEquiv = 2; /* Number of entires in aEquiv[] */
105039 int iEquiv = 2; /* Number of entries of aEquiv[] processed so far */
105040 int aEquiv[22]; /* iCur,iColumn and up to 10 other equivalents */
105041
105042 assert( iCur>=0 );
105043 aEquiv[0] = iCur;
105044 aEquiv[1] = iColumn;
105045 for(;;){
105046 for(pWC=pWCOrig; pWC; pWC=pWC->pOuter){
105047 for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
105048 if( pTerm->leftCursor==iCur
105049 && pTerm->u.leftColumn==iColumn
105050 ){
105051 if( (pTerm->prereqRight & notReady)==0
105052 && (pTerm->eOperator & op & WO_ALL)!=0
105053 ){
105054 if( iOrigCol>=0 && pIdx && (pTerm->eOperator & WO_ISNULL)==0 ){
105055 CollSeq *pColl;
105056 char idxaff;
105057
105058 pX = pTerm->pExpr;
105059 pParse = pWC->pParse;
105060 idxaff = pIdx->pTable->aCol[iOrigCol].affinity;
105061 if( !sqlite3IndexAffinityOk(pX, idxaff) ){
105062 continue;
105063 }
105064
105065 /* Figure out the collation sequence required from an index for
105066 ** it to be useful for optimising expression pX. Store this
105067 ** value in variable pColl.
105068 */
105069 assert(pX->pLeft);
105070 pColl = sqlite3BinaryCompareCollSeq(pParse,pX->pLeft,pX->pRight);
105071 if( pColl==0 ) pColl = pParse->db->pDfltColl;
105072
105073 for(j=0; pIdx->aiColumn[j]!=iOrigCol; j++){
105074 if( NEVER(j>=pIdx->nColumn) ) return 0;
105075 }
105076 if( sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ){
105077 continue;
105078 }
105079 }
105080 if( pTerm->prereqRight==0 && (pTerm->eOperator&WO_EQ)!=0 ){
105081 pResult = pTerm;
105082 goto findTerm_success;
105083 }else if( pResult==0 ){
105084 pResult = pTerm;
105085 }
105086 }
105087 if( (pTerm->eOperator & WO_EQUIV)!=0
105088 && nEquiv<ArraySize(aEquiv)
105089 ){
105090 pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
105091 assert( pX->op==TK_COLUMN );
105092 for(j=0; j<nEquiv; j+=2){
105093 if( aEquiv[j]==pX->iTable && aEquiv[j+1]==pX->iColumn ) break;
105094 }
105095 if( j==nEquiv ){
105096 aEquiv[j] = pX->iTable;
105097 aEquiv[j+1] = pX->iColumn;
105098 nEquiv += 2;
105099 }
105100 }
105101 }
105102 }
105103 }
105104 if( iEquiv>=nEquiv ) break;
105105 iCur = aEquiv[iEquiv++];
105106 iColumn = aEquiv[iEquiv++];
105107 }
105108 findTerm_success:
105109 return pResult;
105110 }
105111
105112 /* Forward reference */
105113 static void exprAnalyze(SrcList*, WhereClause*, int);
105114
105115 /*
105116 ** Call exprAnalyze on all terms in a WHERE clause.
105117 **
105118 **
105119 */
105120 static void exprAnalyzeAll(
105121 SrcList *pTabList, /* the FROM clause */
105122 WhereClause *pWC /* the WHERE clause to be analyzed */
105123 ){
@@ -105345,15 +105512,15 @@
105345 static void exprAnalyzeOrTerm(
105346 SrcList *pSrc, /* the FROM clause */
105347 WhereClause *pWC, /* the complete WHERE clause */
105348 int idxTerm /* Index of the OR-term to be analyzed */
105349 ){
105350 Parse *pParse = pWC->pParse; /* Parser context */
 
105351 sqlite3 *db = pParse->db; /* Database connection */
105352 WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
105353 Expr *pExpr = pTerm->pExpr; /* The expression of the term */
105354 WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
105355 int i; /* Loop counters */
105356 WhereClause *pOrWc; /* Breakup of pTerm into subterms */
105357 WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
105358 WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
105359 Bitmask chngToIN; /* Tables that might satisfy case 1 */
@@ -105368,11 +105535,11 @@
105368 assert( pExpr->op==TK_OR );
105369 pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
105370 if( pOrInfo==0 ) return;
105371 pTerm->wtFlags |= TERM_ORINFO;
105372 pOrWc = &pOrInfo->wc;
105373 whereClauseInit(pOrWc, pWC->pParse, pMaskSet, pWC->wctrlFlags);
105374 whereSplit(pOrWc, pExpr, TK_OR);
105375 exprAnalyzeAll(pSrc, pOrWc);
105376 if( db->mallocFailed ) return;
105377 assert( pOrWc->nTerm>=2 );
105378
@@ -105394,20 +105561,20 @@
105394 Bitmask b = 0;
105395 pOrTerm->u.pAndInfo = pAndInfo;
105396 pOrTerm->wtFlags |= TERM_ANDINFO;
105397 pOrTerm->eOperator = WO_AND;
105398 pAndWC = &pAndInfo->wc;
105399 whereClauseInit(pAndWC, pWC->pParse, pMaskSet, pWC->wctrlFlags);
105400 whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
105401 exprAnalyzeAll(pSrc, pAndWC);
105402 pAndWC->pOuter = pWC;
105403 testcase( db->mallocFailed );
105404 if( !db->mallocFailed ){
105405 for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
105406 assert( pAndTerm->pExpr );
105407 if( allowedOp(pAndTerm->pExpr->op) ){
105408 b |= getMask(pMaskSet, pAndTerm->leftCursor);
105409 }
105410 }
105411 }
105412 indexable &= b;
105413 }
@@ -105414,14 +105581,14 @@
105414 }else if( pOrTerm->wtFlags & TERM_COPIED ){
105415 /* Skip this term for now. We revisit it when we process the
105416 ** corresponding TERM_VIRTUAL term */
105417 }else{
105418 Bitmask b;
105419 b = getMask(pMaskSet, pOrTerm->leftCursor);
105420 if( pOrTerm->wtFlags & TERM_VIRTUAL ){
105421 WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
105422 b |= getMask(pMaskSet, pOther->leftCursor);
105423 }
105424 indexable &= b;
105425 if( (pOrTerm->eOperator & WO_EQ)==0 ){
105426 chngToIN = 0;
105427 }else{
@@ -105479,11 +105646,11 @@
105479 /* This is the 2-bit case and we are on the second iteration and
105480 ** current term is from the first iteration. So skip this term. */
105481 assert( j==1 );
105482 continue;
105483 }
105484 if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
105485 /* This term must be of the form t1.a==t2.b where t2 is in the
105486 ** chngToIN set but t1 is not. This term will be either preceeded
105487 ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
105488 ** and use its inversion. */
105489 testcase( pOrTerm->wtFlags & TERM_COPIED );
@@ -105498,11 +105665,11 @@
105498 if( i<0 ){
105499 /* No candidate table+column was found. This can only occur
105500 ** on the second iteration */
105501 assert( j==1 );
105502 assert( IsPowerOfTwo(chngToIN) );
105503 assert( chngToIN==getMask(pMaskSet, iCursor) );
105504 break;
105505 }
105506 testcase( j==1 );
105507
105508 /* We have found a candidate table and column. Check to see if that
@@ -105547,11 +105714,11 @@
105547 if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
105548 assert( pOrTerm->eOperator & WO_EQ );
105549 assert( pOrTerm->leftCursor==iCursor );
105550 assert( pOrTerm->u.leftColumn==iColumn );
105551 pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
105552 pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
105553 pLeft = pOrTerm->pExpr->pLeft;
105554 }
105555 assert( pLeft!=0 );
105556 pDup = sqlite3ExprDup(db, pLeft, 0);
105557 pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
@@ -105596,10 +105763,11 @@
105596 static void exprAnalyze(
105597 SrcList *pSrc, /* the FROM clause */
105598 WhereClause *pWC, /* the WHERE clause */
105599 int idxTerm /* Index of the term to be analyzed */
105600 ){
 
105601 WhereTerm *pTerm; /* The term to be analyzed */
105602 WhereMaskSet *pMaskSet; /* Set of table index masks */
105603 Expr *pExpr; /* The expression to be analyzed */
105604 Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
105605 Bitmask prereqAll; /* Prerequesites of pExpr */
@@ -105606,18 +105774,18 @@
105606 Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
105607 Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
105608 int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
105609 int noCase = 0; /* LIKE/GLOB distinguishes case */
105610 int op; /* Top-level operator. pExpr->op */
105611 Parse *pParse = pWC->pParse; /* Parsing context */
105612 sqlite3 *db = pParse->db; /* Database connection */
105613
105614 if( db->mallocFailed ){
105615 return;
105616 }
105617 pTerm = &pWC->a[idxTerm];
105618 pMaskSet = pWC->pMaskSet;
105619 pExpr = pTerm->pExpr;
105620 assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
105621 prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
105622 op = pExpr->op;
105623 if( op==TK_IN ){
@@ -105891,15 +106059,12 @@
105891 */
105892 pTerm->prereqRight |= extraRight;
105893 }
105894
105895 /*
105896 ** This function searches the expression list passed as the second argument
105897 ** for an expression of type TK_COLUMN that refers to the same column and
105898 ** uses the same collation sequence as the iCol'th column of index pIdx.
105899 ** Argument iBase is the cursor number used for the table that pIdx refers
105900 ** to.
105901 **
105902 ** If such an expression is found, its index in pList->a[] is returned. If
105903 ** no expression is found, -1 is returned.
105904 */
105905 static int findIndexCol(
@@ -105925,82 +106090,23 @@
105925 }
105926 }
105927
105928 return -1;
105929 }
105930
105931 /*
105932 ** This routine determines if pIdx can be used to assist in processing a
105933 ** DISTINCT qualifier. In other words, it tests whether or not using this
105934 ** index for the outer loop guarantees that rows with equal values for
105935 ** all expressions in the pDistinct list are delivered grouped together.
105936 **
105937 ** For example, the query
105938 **
105939 ** SELECT DISTINCT a, b, c FROM tbl WHERE a = ?
105940 **
105941 ** can benefit from any index on columns "b" and "c".
105942 */
105943 static int isDistinctIndex(
105944 Parse *pParse, /* Parsing context */
105945 WhereClause *pWC, /* The WHERE clause */
105946 Index *pIdx, /* The index being considered */
105947 int base, /* Cursor number for the table pIdx is on */
105948 ExprList *pDistinct, /* The DISTINCT expressions */
105949 int nEqCol /* Number of index columns with == */
105950 ){
105951 Bitmask mask = 0; /* Mask of unaccounted for pDistinct exprs */
105952 int i; /* Iterator variable */
105953
105954 assert( pDistinct!=0 );
105955 if( pIdx->zName==0 || pDistinct->nExpr>=BMS ) return 0;
105956 testcase( pDistinct->nExpr==BMS-1 );
105957
105958 /* Loop through all the expressions in the distinct list. If any of them
105959 ** are not simple column references, return early. Otherwise, test if the
105960 ** WHERE clause contains a "col=X" clause. If it does, the expression
105961 ** can be ignored. If it does not, and the column does not belong to the
105962 ** same table as index pIdx, return early. Finally, if there is no
105963 ** matching "col=X" expression and the column is on the same table as pIdx,
105964 ** set the corresponding bit in variable mask.
105965 */
105966 for(i=0; i<pDistinct->nExpr; i++){
105967 WhereTerm *pTerm;
105968 Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
105969 if( p->op!=TK_COLUMN ) return 0;
105970 pTerm = findTerm(pWC, p->iTable, p->iColumn, ~(Bitmask)0, WO_EQ, 0);
105971 if( pTerm ){
105972 Expr *pX = pTerm->pExpr;
105973 CollSeq *p1 = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
105974 CollSeq *p2 = sqlite3ExprCollSeq(pParse, p);
105975 if( p1==p2 ) continue;
105976 }
105977 if( p->iTable!=base ) return 0;
105978 mask |= (((Bitmask)1) << i);
105979 }
105980
105981 for(i=nEqCol; mask && i<pIdx->nColumn; i++){
105982 int iExpr = findIndexCol(pParse, pDistinct, base, pIdx, i);
105983 if( iExpr<0 ) break;
105984 mask &= ~(((Bitmask)1) << iExpr);
105985 }
105986
105987 return (mask==0);
105988 }
105989
105990
105991 /*
105992 ** Return true if the DISTINCT expression-list passed as the third argument
105993 ** is redundant. A DISTINCT list is redundant if the database contains a
105994 ** UNIQUE index that guarantees that the result of the query will be distinct
105995 ** anyway.
 
105996 */
105997 static int isDistinctRedundant(
105998 Parse *pParse,
105999 SrcList *pTabList,
106000 WhereClause *pWC,
106001 ExprList *pDistinct
106002 ){
106003 Table *pTab;
106004 Index *pIdx;
106005 int i;
106006 int iBase;
@@ -106051,35 +106157,90 @@
106051 }
106052 }
106053
106054 return 0;
106055 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106056
106057 /*
106058 ** Prepare a crude estimate of the logarithm of the input value.
106059 ** The results need not be exact. This is only used for estimating
106060 ** the total cost of performing operations with O(logN) or O(NlogN)
106061 ** complexity. Because N is just a guess, it is no great tragedy if
106062 ** logN is a little off.
106063 */
106064 static double estLog(double N){
106065 double logN = 1;
106066 double x = 10;
106067 while( N>x ){
106068 logN += 1;
106069 x *= 10;
106070 }
106071 return logN;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106072 }
106073
106074 /*
106075 ** Two routines for printing the content of an sqlite3_index_info
106076 ** structure. Used for testing and debugging only. If neither
106077 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
106078 ** are no-ops.
106079 */
106080 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
106081 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
106082 int i;
106083 if( !sqlite3WhereTrace ) return;
106084 for(i=0; i<p->nConstraint; i++){
106085 sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
@@ -106113,111 +106274,10 @@
106113 #else
106114 #define TRACE_IDX_INPUTS(A)
106115 #define TRACE_IDX_OUTPUTS(A)
106116 #endif
106117
106118 /*
106119 ** Required because bestIndex() is called by bestOrClauseIndex()
106120 */
106121 static void bestIndex(WhereBestIdx*);
106122
106123 /*
106124 ** This routine attempts to find an scanning strategy that can be used
106125 ** to optimize an 'OR' expression that is part of a WHERE clause.
106126 **
106127 ** The table associated with FROM clause term pSrc may be either a
106128 ** regular B-Tree table or a virtual table.
106129 */
106130 static void bestOrClauseIndex(WhereBestIdx *p){
106131 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
106132 WhereClause *pWC = p->pWC; /* The WHERE clause */
106133 struct SrcList_item *pSrc = p->pSrc; /* The FROM clause term to search */
106134 const int iCur = pSrc->iCursor; /* The cursor of the table */
106135 const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur); /* Bitmask for pSrc */
106136 WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm]; /* End of pWC->a[] */
106137 WhereTerm *pTerm; /* A single term of the WHERE clause */
106138
106139 /* The OR-clause optimization is disallowed if the INDEXED BY or
106140 ** NOT INDEXED clauses are used or if the WHERE_AND_ONLY bit is set. */
106141 if( pSrc->notIndexed || pSrc->pIndex!=0 ){
106142 return;
106143 }
106144 if( pWC->wctrlFlags & WHERE_AND_ONLY ){
106145 return;
106146 }
106147
106148 /* Search the WHERE clause terms for a usable WO_OR term. */
106149 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
106150 if( (pTerm->eOperator & WO_OR)!=0
106151 && ((pTerm->prereqAll & ~maskSrc) & p->notReady)==0
106152 && (pTerm->u.pOrInfo->indexable & maskSrc)!=0
106153 ){
106154 WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
106155 WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
106156 WhereTerm *pOrTerm;
106157 int flags = WHERE_MULTI_OR;
106158 double rTotal = 0;
106159 double nRow = 0;
106160 Bitmask used = 0;
106161 WhereBestIdx sBOI;
106162
106163 sBOI = *p;
106164 sBOI.pOrderBy = 0;
106165 sBOI.pDistinct = 0;
106166 sBOI.ppIdxInfo = 0;
106167 for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
106168 WHERETRACE(("... Multi-index OR testing for term %d of %d....\n",
106169 (pOrTerm - pOrWC->a), (pTerm - pWC->a)
106170 ));
106171 if( (pOrTerm->eOperator& WO_AND)!=0 ){
106172 sBOI.pWC = &pOrTerm->u.pAndInfo->wc;
106173 bestIndex(&sBOI);
106174 }else if( pOrTerm->leftCursor==iCur ){
106175 WhereClause tempWC;
106176 tempWC.pParse = pWC->pParse;
106177 tempWC.pMaskSet = pWC->pMaskSet;
106178 tempWC.pOuter = pWC;
106179 tempWC.op = TK_AND;
106180 tempWC.a = pOrTerm;
106181 tempWC.wctrlFlags = 0;
106182 tempWC.nTerm = 1;
106183 sBOI.pWC = &tempWC;
106184 bestIndex(&sBOI);
106185 }else{
106186 continue;
106187 }
106188 rTotal += sBOI.cost.rCost;
106189 nRow += sBOI.cost.plan.nRow;
106190 used |= sBOI.cost.used;
106191 if( rTotal>=p->cost.rCost ) break;
106192 }
106193
106194 /* If there is an ORDER BY clause, increase the scan cost to account
106195 ** for the cost of the sort. */
106196 if( p->pOrderBy!=0 ){
106197 WHERETRACE(("... sorting increases OR cost %.9g to %.9g\n",
106198 rTotal, rTotal+nRow*estLog(nRow)));
106199 rTotal += nRow*estLog(nRow);
106200 }
106201
106202 /* If the cost of scanning using this OR term for optimization is
106203 ** less than the current cost stored in pCost, replace the contents
106204 ** of pCost. */
106205 WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
106206 if( rTotal<p->cost.rCost ){
106207 p->cost.rCost = rTotal;
106208 p->cost.used = used;
106209 p->cost.plan.nRow = nRow;
106210 p->cost.plan.nOBSat = p->i ? p->aLevel[p->i-1].plan.nOBSat : 0;
106211 p->cost.plan.wsFlags = flags;
106212 p->cost.plan.u.pTerm = pTerm;
106213 }
106214 }
106215 }
106216 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
106217 }
106218
106219 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
106220 /*
106221 ** Return TRUE if the WHERE clause term pTerm is of a form where it
106222 ** could be used with an index to access pSrc, assuming an appropriate
106223 ** index existed.
@@ -106229,92 +106289,17 @@
106229 ){
106230 char aff;
106231 if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
106232 if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
106233 if( (pTerm->prereqRight & notReady)!=0 ) return 0;
 
106234 aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
106235 if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
106236 return 1;
106237 }
106238 #endif
106239
106240 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
106241 /*
106242 ** If the query plan for pSrc specified in pCost is a full table scan
106243 ** and indexing is allows (if there is no NOT INDEXED clause) and it
106244 ** possible to construct a transient index that would perform better
106245 ** than a full table scan even when the cost of constructing the index
106246 ** is taken into account, then alter the query plan to use the
106247 ** transient index.
106248 */
106249 static void bestAutomaticIndex(WhereBestIdx *p){
106250 Parse *pParse = p->pParse; /* The parsing context */
106251 WhereClause *pWC = p->pWC; /* The WHERE clause */
106252 struct SrcList_item *pSrc = p->pSrc; /* The FROM clause term to search */
106253 double nTableRow; /* Rows in the input table */
106254 double logN; /* log(nTableRow) */
106255 double costTempIdx; /* per-query cost of the transient index */
106256 WhereTerm *pTerm; /* A single term of the WHERE clause */
106257 WhereTerm *pWCEnd; /* End of pWC->a[] */
106258 Table *pTable; /* Table tht might be indexed */
106259
106260 if( pParse->nQueryLoop<=(double)1 ){
106261 /* There is no point in building an automatic index for a single scan */
106262 return;
106263 }
106264 if( (pParse->db->flags & SQLITE_AutoIndex)==0 ){
106265 /* Automatic indices are disabled at run-time */
106266 return;
106267 }
106268 if( (p->cost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0
106269 && (p->cost.plan.wsFlags & WHERE_COVER_SCAN)==0
106270 ){
106271 /* We already have some kind of index in use for this query. */
106272 return;
106273 }
106274 if( pSrc->viaCoroutine ){
106275 /* Cannot index a co-routine */
106276 return;
106277 }
106278 if( pSrc->notIndexed ){
106279 /* The NOT INDEXED clause appears in the SQL. */
106280 return;
106281 }
106282 if( pSrc->isCorrelated ){
106283 /* The source is a correlated sub-query. No point in indexing it. */
106284 return;
106285 }
106286
106287 assert( pParse->nQueryLoop >= (double)1 );
106288 pTable = pSrc->pTab;
106289 nTableRow = pTable->nRowEst;
106290 logN = estLog(nTableRow);
106291 costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
106292 if( costTempIdx>=p->cost.rCost ){
106293 /* The cost of creating the transient table would be greater than
106294 ** doing the full table scan */
106295 return;
106296 }
106297
106298 /* Search for any equality comparison term */
106299 pWCEnd = &pWC->a[pWC->nTerm];
106300 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
106301 if( termCanDriveIndex(pTerm, pSrc, p->notReady) ){
106302 WHERETRACE(("auto-index reduces cost from %.1f to %.1f\n",
106303 p->cost.rCost, costTempIdx));
106304 p->cost.rCost = costTempIdx;
106305 p->cost.plan.nRow = logN + 1;
106306 p->cost.plan.wsFlags = WHERE_TEMP_INDEX;
106307 p->cost.used = pTerm->prereqRight;
106308 break;
106309 }
106310 }
106311 }
106312 #else
106313 # define bestAutomaticIndex(A) /* no-op */
106314 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
106315
106316
106317 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
106318 /*
106319 ** Generate code to construct the Index object for an automatic index
106320 ** and to set up the WhereLevel object pLevel so that the code generator
@@ -106340,10 +106325,11 @@
106340 int regRecord; /* Register holding an index record */
106341 int n; /* Column counter */
106342 int i; /* Loop counter */
106343 int mxBitCol; /* Maximum column in pSrc->colUsed */
106344 CollSeq *pColl; /* Collating sequence to on a column */
 
106345 Bitmask idxCols; /* Bitmap of columns used for indexing */
106346 Bitmask extraCols; /* Bitmap of additional columns */
106347
106348 /* Generate code to skip over the creation and initialization of the
106349 ** transient index on 2nd and subsequent iterations of the loop. */
@@ -106354,54 +106340,58 @@
106354 /* Count the number of columns that will be added to the index
106355 ** and used to match WHERE clause constraints */
106356 nColumn = 0;
106357 pTable = pSrc->pTab;
106358 pWCEnd = &pWC->a[pWC->nTerm];
 
106359 idxCols = 0;
106360 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
106361 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
106362 int iCol = pTerm->u.leftColumn;
106363 Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
106364 testcase( iCol==BMS );
106365 testcase( iCol==BMS-1 );
106366 if( (idxCols & cMask)==0 ){
106367 nColumn++;
 
106368 idxCols |= cMask;
106369 }
106370 }
106371 }
106372 assert( nColumn>0 );
106373 pLevel->plan.nEq = nColumn;
 
 
106374
106375 /* Count the number of additional columns needed to create a
106376 ** covering index. A "covering index" is an index that contains all
106377 ** columns that are needed by the query. With a covering index, the
106378 ** original table never needs to be accessed. Automatic indices must
106379 ** be a covering index because the index will not be updated if the
106380 ** original table changes and the index and table cannot both be used
106381 ** if they go out of sync.
106382 */
106383 extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1)));
106384 mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
106385 testcase( pTable->nCol==BMS-1 );
106386 testcase( pTable->nCol==BMS-2 );
106387 for(i=0; i<mxBitCol; i++){
106388 if( extraCols & (((Bitmask)1)<<i) ) nColumn++;
106389 }
106390 if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
106391 nColumn += pTable->nCol - BMS + 1;
106392 }
106393 pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;
106394
106395 /* Construct the Index object to describe this index */
106396 nByte = sizeof(Index);
106397 nByte += nColumn*sizeof(int); /* Index.aiColumn */
106398 nByte += nColumn*sizeof(char*); /* Index.azColl */
106399 nByte += nColumn; /* Index.aSortOrder */
106400 pIdx = sqlite3DbMallocZero(pParse->db, nByte);
106401 if( pIdx==0 ) return;
106402 pLevel->plan.u.pIdx = pIdx;
106403 pIdx->azColl = (char**)&pIdx[1];
106404 pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
106405 pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
106406 pIdx->zName = "auto-index";
106407 pIdx->nColumn = nColumn;
@@ -106409,11 +106399,13 @@
106409 n = 0;
106410 idxCols = 0;
106411 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
106412 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
106413 int iCol = pTerm->u.leftColumn;
106414 Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
 
 
106415 if( (idxCols & cMask)==0 ){
106416 Expr *pX = pTerm->pExpr;
106417 idxCols |= cMask;
106418 pIdx->aiColumn[n] = pTerm->u.leftColumn;
106419 pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
@@ -106420,22 +106412,22 @@
106420 pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
106421 n++;
106422 }
106423 }
106424 }
106425 assert( (u32)n==pLevel->plan.nEq );
106426
106427 /* Add additional columns needed to make the automatic index into
106428 ** a covering index */
106429 for(i=0; i<mxBitCol; i++){
106430 if( extraCols & (((Bitmask)1)<<i) ){
106431 pIdx->aiColumn[n] = i;
106432 pIdx->azColl[n] = "BINARY";
106433 n++;
106434 }
106435 }
106436 if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
106437 for(i=BMS-1; i<pTable->nCol; i++){
106438 pIdx->aiColumn[n] = i;
106439 pIdx->azColl[n] = "BINARY";
106440 n++;
106441 }
@@ -106443,10 +106435,11 @@
106443 assert( n==nColumn );
106444
106445 /* Create the automatic index */
106446 pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
106447 assert( pLevel->iIdxCur>=0 );
 
106448 sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
106449 (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
106450 VdbeComment((v, "for %s", pTable->zName));
106451
106452 /* Fill the automatic index with content */
@@ -106469,26 +106462,25 @@
106469 /*
106470 ** Allocate and populate an sqlite3_index_info structure. It is the
106471 ** responsibility of the caller to eventually release the structure
106472 ** by passing the pointer returned by this function to sqlite3_free().
106473 */
106474 static sqlite3_index_info *allocateIndexInfo(WhereBestIdx *p){
106475 Parse *pParse = p->pParse;
106476 WhereClause *pWC = p->pWC;
106477 struct SrcList_item *pSrc = p->pSrc;
106478 ExprList *pOrderBy = p->pOrderBy;
 
106479 int i, j;
106480 int nTerm;
106481 struct sqlite3_index_constraint *pIdxCons;
106482 struct sqlite3_index_orderby *pIdxOrderBy;
106483 struct sqlite3_index_constraint_usage *pUsage;
106484 WhereTerm *pTerm;
106485 int nOrderBy;
106486 sqlite3_index_info *pIdxInfo;
106487
106488 WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
106489
106490 /* Count the number of possible WHERE clause constraints referring
106491 ** to this virtual table */
106492 for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
106493 if( pTerm->leftCursor != pSrc->iCursor ) continue;
106494 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
@@ -106520,11 +106512,10 @@
106520 pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
106521 + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
106522 + sizeof(*pIdxOrderBy)*nOrderBy );
106523 if( pIdxInfo==0 ){
106524 sqlite3ErrorMsg(pParse, "out of memory");
106525 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
106526 return 0;
106527 }
106528
106529 /* Initialize the structure. The sqlite3_index_info structure contains
106530 ** many fields that are declared "const" to prevent xBestIndex from
@@ -106576,12 +106567,12 @@
106576 }
106577
106578 /*
106579 ** The table object reference passed as the second argument to this function
106580 ** must represent a virtual table. This function invokes the xBestIndex()
106581 ** method of the virtual table with the sqlite3_index_info pointer passed
106582 ** as the argument.
106583 **
106584 ** If an error occurs, pParse is populated with an error message and a
106585 ** non-zero value is returned. Otherwise, 0 is returned and the output
106586 ** part of the sqlite3_index_info structure is left populated.
106587 **
@@ -106592,11 +106583,10 @@
106592 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
106593 sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
106594 int i;
106595 int rc;
106596
106597 WHERETRACE(("xBestIndex for %s\n", pTab->zName));
106598 TRACE_IDX_INPUTS(p);
106599 rc = pVtab->pModule->xBestIndex(pVtab, p);
106600 TRACE_IDX_OUTPUTS(p);
106601
106602 if( rc!=SQLITE_OK ){
@@ -106618,211 +106608,12 @@
106618 }
106619 }
106620
106621 return pParse->nErr;
106622 }
106623
106624
106625 /*
106626 ** Compute the best index for a virtual table.
106627 **
106628 ** The best index is computed by the xBestIndex method of the virtual
106629 ** table module. This routine is really just a wrapper that sets up
106630 ** the sqlite3_index_info structure that is used to communicate with
106631 ** xBestIndex.
106632 **
106633 ** In a join, this routine might be called multiple times for the
106634 ** same virtual table. The sqlite3_index_info structure is created
106635 ** and initialized on the first invocation and reused on all subsequent
106636 ** invocations. The sqlite3_index_info structure is also used when
106637 ** code is generated to access the virtual table. The whereInfoDelete()
106638 ** routine takes care of freeing the sqlite3_index_info structure after
106639 ** everybody has finished with it.
106640 */
106641 static void bestVirtualIndex(WhereBestIdx *p){
106642 Parse *pParse = p->pParse; /* The parsing context */
106643 WhereClause *pWC = p->pWC; /* The WHERE clause */
106644 struct SrcList_item *pSrc = p->pSrc; /* The FROM clause term to search */
106645 Table *pTab = pSrc->pTab;
106646 sqlite3_index_info *pIdxInfo;
106647 struct sqlite3_index_constraint *pIdxCons;
106648 struct sqlite3_index_constraint_usage *pUsage;
106649 WhereTerm *pTerm;
106650 int i, j;
106651 int nOrderBy;
106652 int bAllowIN; /* Allow IN optimizations */
106653 double rCost;
106654
106655 /* Make sure wsFlags is initialized to some sane value. Otherwise, if the
106656 ** malloc in allocateIndexInfo() fails and this function returns leaving
106657 ** wsFlags in an uninitialized state, the caller may behave unpredictably.
106658 */
106659 memset(&p->cost, 0, sizeof(p->cost));
106660 p->cost.plan.wsFlags = WHERE_VIRTUALTABLE;
106661
106662 /* If the sqlite3_index_info structure has not been previously
106663 ** allocated and initialized, then allocate and initialize it now.
106664 */
106665 pIdxInfo = *p->ppIdxInfo;
106666 if( pIdxInfo==0 ){
106667 *p->ppIdxInfo = pIdxInfo = allocateIndexInfo(p);
106668 }
106669 if( pIdxInfo==0 ){
106670 return;
106671 }
106672
106673 /* At this point, the sqlite3_index_info structure that pIdxInfo points
106674 ** to will have been initialized, either during the current invocation or
106675 ** during some prior invocation. Now we just have to customize the
106676 ** details of pIdxInfo for the current invocation and pass it to
106677 ** xBestIndex.
106678 */
106679
106680 /* The module name must be defined. Also, by this point there must
106681 ** be a pointer to an sqlite3_vtab structure. Otherwise
106682 ** sqlite3ViewGetColumnNames() would have picked up the error.
106683 */
106684 assert( pTab->azModuleArg && pTab->azModuleArg[0] );
106685 assert( sqlite3GetVTable(pParse->db, pTab) );
106686
106687 /* Try once or twice. On the first attempt, allow IN optimizations.
106688 ** If an IN optimization is accepted by the virtual table xBestIndex
106689 ** method, but the pInfo->aConstrainUsage.omit flag is not set, then
106690 ** the query will not work because it might allow duplicate rows in
106691 ** output. In that case, run the xBestIndex method a second time
106692 ** without the IN constraints. Usually this loop only runs once.
106693 ** The loop will exit using a "break" statement.
106694 */
106695 for(bAllowIN=1; 1; bAllowIN--){
106696 assert( bAllowIN==0 || bAllowIN==1 );
106697
106698 /* Set the aConstraint[].usable fields and initialize all
106699 ** output variables to zero.
106700 **
106701 ** aConstraint[].usable is true for constraints where the right-hand
106702 ** side contains only references to tables to the left of the current
106703 ** table. In other words, if the constraint is of the form:
106704 **
106705 ** column = expr
106706 **
106707 ** and we are evaluating a join, then the constraint on column is
106708 ** only valid if all tables referenced in expr occur to the left
106709 ** of the table containing column.
106710 **
106711 ** The aConstraints[] array contains entries for all constraints
106712 ** on the current table. That way we only have to compute it once
106713 ** even though we might try to pick the best index multiple times.
106714 ** For each attempt at picking an index, the order of tables in the
106715 ** join might be different so we have to recompute the usable flag
106716 ** each time.
106717 */
106718 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
106719 pUsage = pIdxInfo->aConstraintUsage;
106720 for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
106721 j = pIdxCons->iTermOffset;
106722 pTerm = &pWC->a[j];
106723 if( (pTerm->prereqRight&p->notReady)==0
106724 && (bAllowIN || (pTerm->eOperator & WO_IN)==0)
106725 ){
106726 pIdxCons->usable = 1;
106727 }else{
106728 pIdxCons->usable = 0;
106729 }
106730 }
106731 memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
106732 if( pIdxInfo->needToFreeIdxStr ){
106733 sqlite3_free(pIdxInfo->idxStr);
106734 }
106735 pIdxInfo->idxStr = 0;
106736 pIdxInfo->idxNum = 0;
106737 pIdxInfo->needToFreeIdxStr = 0;
106738 pIdxInfo->orderByConsumed = 0;
106739 /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
106740 pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
106741 nOrderBy = pIdxInfo->nOrderBy;
106742 if( !p->pOrderBy ){
106743 pIdxInfo->nOrderBy = 0;
106744 }
106745
106746 if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
106747 return;
106748 }
106749
106750 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
106751 for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
106752 if( pUsage[i].argvIndex>0 ){
106753 j = pIdxCons->iTermOffset;
106754 pTerm = &pWC->a[j];
106755 p->cost.used |= pTerm->prereqRight;
106756 if( (pTerm->eOperator & WO_IN)!=0 ){
106757 if( pUsage[i].omit==0 ){
106758 /* Do not attempt to use an IN constraint if the virtual table
106759 ** says that the equivalent EQ constraint cannot be safely omitted.
106760 ** If we do attempt to use such a constraint, some rows might be
106761 ** repeated in the output. */
106762 break;
106763 }
106764 /* A virtual table that is constrained by an IN clause may not
106765 ** consume the ORDER BY clause because (1) the order of IN terms
106766 ** is not necessarily related to the order of output terms and
106767 ** (2) Multiple outputs from a single IN value will not merge
106768 ** together. */
106769 pIdxInfo->orderByConsumed = 0;
106770 }
106771 }
106772 }
106773 if( i>=pIdxInfo->nConstraint ) break;
106774 }
106775
106776 /* The orderByConsumed signal is only valid if all outer loops collectively
106777 ** generate just a single row of output.
106778 */
106779 if( pIdxInfo->orderByConsumed ){
106780 for(i=0; i<p->i; i++){
106781 if( (p->aLevel[i].plan.wsFlags & WHERE_UNIQUE)==0 ){
106782 pIdxInfo->orderByConsumed = 0;
106783 }
106784 }
106785 }
106786
106787 /* If there is an ORDER BY clause, and the selected virtual table index
106788 ** does not satisfy it, increase the cost of the scan accordingly. This
106789 ** matches the processing for non-virtual tables in bestBtreeIndex().
106790 */
106791 rCost = pIdxInfo->estimatedCost;
106792 if( p->pOrderBy && pIdxInfo->orderByConsumed==0 ){
106793 rCost += estLog(rCost)*rCost;
106794 }
106795
106796 /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
106797 ** inital value of lowestCost in this loop. If it is, then the
106798 ** (cost<lowestCost) test below will never be true.
106799 **
106800 ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT
106801 ** is defined.
106802 */
106803 if( (SQLITE_BIG_DBL/((double)2))<rCost ){
106804 p->cost.rCost = (SQLITE_BIG_DBL/((double)2));
106805 }else{
106806 p->cost.rCost = rCost;
106807 }
106808 p->cost.plan.u.pVtabIdx = pIdxInfo;
106809 if( pIdxInfo->orderByConsumed ){
106810 p->cost.plan.wsFlags |= WHERE_ORDERED;
106811 p->cost.plan.nOBSat = nOrderBy;
106812 }else{
106813 p->cost.plan.nOBSat = p->i ? p->aLevel[p->i-1].plan.nOBSat : 0;
106814 }
106815 p->cost.plan.nEq = 0;
106816 pIdxInfo->nOrderBy = nOrderBy;
106817
106818 /* Try to find a more efficient access pattern by using multiple indexes
106819 ** to optimize an OR expression within the WHERE clause.
106820 */
106821 bestOrClauseIndex(p);
106822 }
106823 #endif /* SQLITE_OMIT_VIRTUALTABLE */
106824
106825 #ifdef SQLITE_ENABLE_STAT3
106826 /*
106827 ** Estimate the location of a particular key among all keys in an
106828 ** index. Store the results in aStat as follows:
@@ -107060,11 +106851,11 @@
107060 Parse *pParse, /* Parsing & code generating context */
107061 Index *p, /* The index containing the range-compared column; "x" */
107062 int nEq, /* index into p->aCol[] of the range-compared column */
107063 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
107064 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
107065 double *pRangeDiv /* OUT: Reduce search space by this divisor */
107066 ){
107067 int rc = SQLITE_OK;
107068
107069 #ifdef SQLITE_ENABLE_STAT3
107070
@@ -107098,29 +106889,35 @@
107098 if( (pUpper->eOperator & WO_LE)!=0 ) iUpper += a[1];
107099 }
107100 sqlite3ValueFree(pRangeVal);
107101 }
107102 if( rc==SQLITE_OK ){
107103 if( iUpper<=iLower ){
107104 *pRangeDiv = (double)p->aiRowEst[0];
107105 }else{
107106 *pRangeDiv = (double)p->aiRowEst[0]/(double)(iUpper - iLower);
107107 }
107108 WHERETRACE(("range scan regions: %u..%u div=%g\n",
107109 (u32)iLower, (u32)iUpper, *pRangeDiv));
 
107110 return SQLITE_OK;
107111 }
107112 }
107113 #else
107114 UNUSED_PARAMETER(pParse);
107115 UNUSED_PARAMETER(p);
107116 UNUSED_PARAMETER(nEq);
107117 #endif
107118 assert( pLower || pUpper );
107119 *pRangeDiv = (double)1;
107120 if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ) *pRangeDiv *= (double)4;
107121 if( pUpper ) *pRangeDiv *= (double)4;
 
 
 
 
 
 
107122 return rc;
107123 }
107124
107125 #ifdef SQLITE_ENABLE_STAT3
107126 /*
@@ -107142,11 +106939,11 @@
107142 */
107143 static int whereEqualScanEst(
107144 Parse *pParse, /* Parsing & code generating context */
107145 Index *p, /* The index whose left-most column is pTerm */
107146 Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
107147 double *pnRow /* Write the revised row estimate here */
107148 ){
107149 sqlite3_value *pRhs = 0; /* VALUE on right-hand side of pTerm */
107150 u8 aff; /* Column affinity */
107151 int rc; /* Subfunction return code */
107152 tRowcnt a[2]; /* Statistics */
@@ -107161,11 +106958,11 @@
107161 pRhs = sqlite3ValueNew(pParse->db);
107162 }
107163 if( pRhs==0 ) return SQLITE_NOTFOUND;
107164 rc = whereKeyStats(pParse, p, pRhs, 0, a);
107165 if( rc==SQLITE_OK ){
107166 WHERETRACE(("equality scan regions: %d\n", (int)a[1]));
107167 *pnRow = a[1];
107168 }
107169 whereEqualScanEst_cancel:
107170 sqlite3ValueFree(pRhs);
107171 return rc;
@@ -107191,16 +106988,16 @@
107191 */
107192 static int whereInScanEst(
107193 Parse *pParse, /* Parsing & code generating context */
107194 Index *p, /* The index whose left-most column is pTerm */
107195 ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
107196 double *pnRow /* Write the revised row estimate here */
107197 ){
107198 int rc = SQLITE_OK; /* Subfunction return code */
107199 double nEst; /* Number of rows for a single term */
107200 double nRowEst = (double)0; /* New estimate of the number of rows */
107201 int i; /* Loop counter */
107202
107203 assert( p->aSample!=0 );
107204 for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
107205 nEst = p->aiRowEst[0];
107206 rc = whereEqualScanEst(pParse, p, pList->a[i].pExpr, &nEst);
@@ -107207,888 +107004,15 @@
107207 nRowEst += nEst;
107208 }
107209 if( rc==SQLITE_OK ){
107210 if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
107211 *pnRow = nRowEst;
107212 WHERETRACE(("IN row estimate: est=%g\n", nRowEst));
107213 }
107214 return rc;
107215 }
107216 #endif /* defined(SQLITE_ENABLE_STAT3) */
107217
107218 /*
107219 ** Check to see if column iCol of the table with cursor iTab will appear
107220 ** in sorted order according to the current query plan.
107221 **
107222 ** Return values:
107223 **
107224 ** 0 iCol is not ordered
107225 ** 1 iCol has only a single value
107226 ** 2 iCol is in ASC order
107227 ** 3 iCol is in DESC order
107228 */
107229 static int isOrderedColumn(
107230 WhereBestIdx *p,
107231 int iTab,
107232 int iCol
107233 ){
107234 int i, j;
107235 WhereLevel *pLevel = &p->aLevel[p->i-1];
107236 Index *pIdx;
107237 u8 sortOrder;
107238 for(i=p->i-1; i>=0; i--, pLevel--){
107239 if( pLevel->iTabCur!=iTab ) continue;
107240 if( (pLevel->plan.wsFlags & WHERE_ALL_UNIQUE)!=0 ){
107241 return 1;
107242 }
107243 assert( (pLevel->plan.wsFlags & WHERE_ORDERED)!=0 );
107244 if( (pIdx = pLevel->plan.u.pIdx)!=0 ){
107245 if( iCol<0 ){
107246 sortOrder = 0;
107247 testcase( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 );
107248 }else{
107249 int n = pIdx->nColumn;
107250 for(j=0; j<n; j++){
107251 if( iCol==pIdx->aiColumn[j] ) break;
107252 }
107253 if( j>=n ) return 0;
107254 sortOrder = pIdx->aSortOrder[j];
107255 testcase( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 );
107256 }
107257 }else{
107258 if( iCol!=(-1) ) return 0;
107259 sortOrder = 0;
107260 testcase( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 );
107261 }
107262 if( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 ){
107263 assert( sortOrder==0 || sortOrder==1 );
107264 testcase( sortOrder==1 );
107265 sortOrder = 1 - sortOrder;
107266 }
107267 return sortOrder+2;
107268 }
107269 return 0;
107270 }
107271
107272 /*
107273 ** This routine decides if pIdx can be used to satisfy the ORDER BY
107274 ** clause, either in whole or in part. The return value is the
107275 ** cumulative number of terms in the ORDER BY clause that are satisfied
107276 ** by the index pIdx and other indices in outer loops.
107277 **
107278 ** The table being queried has a cursor number of "base". pIdx is the
107279 ** index that is postulated for use to access the table.
107280 **
107281 ** The *pbRev value is set to 0 order 1 depending on whether or not
107282 ** pIdx should be run in the forward order or in reverse order.
107283 */
107284 static int isSortingIndex(
107285 WhereBestIdx *p, /* Best index search context */
107286 Index *pIdx, /* The index we are testing */
107287 int base, /* Cursor number for the table to be sorted */
107288 int *pbRev, /* Set to 1 for reverse-order scan of pIdx */
107289 int *pbObUnique /* ORDER BY column values will different in every row */
107290 ){
107291 int i; /* Number of pIdx terms used */
107292 int j; /* Number of ORDER BY terms satisfied */
107293 int sortOrder = 2; /* 0: forward. 1: backward. 2: unknown */
107294 int nTerm; /* Number of ORDER BY terms */
107295 struct ExprList_item *pOBItem;/* A term of the ORDER BY clause */
107296 Table *pTab = pIdx->pTable; /* Table that owns index pIdx */
107297 ExprList *pOrderBy; /* The ORDER BY clause */
107298 Parse *pParse = p->pParse; /* Parser context */
107299 sqlite3 *db = pParse->db; /* Database connection */
107300 int nPriorSat; /* ORDER BY terms satisfied by outer loops */
107301 int seenRowid = 0; /* True if an ORDER BY rowid term is seen */
107302 int uniqueNotNull; /* pIdx is UNIQUE with all terms are NOT NULL */
107303 int outerObUnique; /* Outer loops generate different values in
107304 ** every row for the ORDER BY columns */
107305
107306 if( p->i==0 ){
107307 nPriorSat = 0;
107308 outerObUnique = 1;
107309 }else{
107310 u32 wsFlags = p->aLevel[p->i-1].plan.wsFlags;
107311 nPriorSat = p->aLevel[p->i-1].plan.nOBSat;
107312 if( (wsFlags & WHERE_ORDERED)==0 ){
107313 /* This loop cannot be ordered unless the next outer loop is
107314 ** also ordered */
107315 return nPriorSat;
107316 }
107317 if( OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ){
107318 /* Only look at the outer-most loop if the OrderByIdxJoin
107319 ** optimization is disabled */
107320 return nPriorSat;
107321 }
107322 testcase( wsFlags & WHERE_OB_UNIQUE );
107323 testcase( wsFlags & WHERE_ALL_UNIQUE );
107324 outerObUnique = (wsFlags & (WHERE_OB_UNIQUE|WHERE_ALL_UNIQUE))!=0;
107325 }
107326 pOrderBy = p->pOrderBy;
107327 assert( pOrderBy!=0 );
107328 if( pIdx->bUnordered ){
107329 /* Hash indices (indicated by the "unordered" tag on sqlite_stat1) cannot
107330 ** be used for sorting */
107331 return nPriorSat;
107332 }
107333 nTerm = pOrderBy->nExpr;
107334 uniqueNotNull = pIdx->onError!=OE_None;
107335 assert( nTerm>0 );
107336
107337 /* Argument pIdx must either point to a 'real' named index structure,
107338 ** or an index structure allocated on the stack by bestBtreeIndex() to
107339 ** represent the rowid index that is part of every table. */
107340 assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
107341
107342 /* Match terms of the ORDER BY clause against columns of
107343 ** the index.
107344 **
107345 ** Note that indices have pIdx->nColumn regular columns plus
107346 ** one additional column containing the rowid. The rowid column
107347 ** of the index is also allowed to match against the ORDER BY
107348 ** clause.
107349 */
107350 j = nPriorSat;
107351 for(i=0,pOBItem=&pOrderBy->a[j]; j<nTerm && i<=pIdx->nColumn; i++){
107352 Expr *pOBExpr; /* The expression of the ORDER BY pOBItem */
107353 CollSeq *pColl; /* The collating sequence of pOBExpr */
107354 int termSortOrder; /* Sort order for this term */
107355 int iColumn; /* The i-th column of the index. -1 for rowid */
107356 int iSortOrder; /* 1 for DESC, 0 for ASC on the i-th index term */
107357 int isEq; /* Subject to an == or IS NULL constraint */
107358 int isMatch; /* ORDER BY term matches the index term */
107359 const char *zColl; /* Name of collating sequence for i-th index term */
107360 WhereTerm *pConstraint; /* A constraint in the WHERE clause */
107361
107362 /* If the next term of the ORDER BY clause refers to anything other than
107363 ** a column in the "base" table, then this index will not be of any
107364 ** further use in handling the ORDER BY. */
107365 pOBExpr = sqlite3ExprSkipCollate(pOBItem->pExpr);
107366 if( pOBExpr->op!=TK_COLUMN || pOBExpr->iTable!=base ){
107367 break;
107368 }
107369
107370 /* Find column number and collating sequence for the next entry
107371 ** in the index */
107372 if( pIdx->zName && i<pIdx->nColumn ){
107373 iColumn = pIdx->aiColumn[i];
107374 if( iColumn==pIdx->pTable->iPKey ){
107375 iColumn = -1;
107376 }
107377 iSortOrder = pIdx->aSortOrder[i];
107378 zColl = pIdx->azColl[i];
107379 assert( zColl!=0 );
107380 }else{
107381 iColumn = -1;
107382 iSortOrder = 0;
107383 zColl = 0;
107384 }
107385
107386 /* Check to see if the column number and collating sequence of the
107387 ** index match the column number and collating sequence of the ORDER BY
107388 ** clause entry. Set isMatch to 1 if they both match. */
107389 if( pOBExpr->iColumn==iColumn ){
107390 if( zColl ){
107391 pColl = sqlite3ExprCollSeq(pParse, pOBItem->pExpr);
107392 if( !pColl ) pColl = db->pDfltColl;
107393 isMatch = sqlite3StrICmp(pColl->zName, zColl)==0;
107394 }else{
107395 isMatch = 1;
107396 }
107397 }else{
107398 isMatch = 0;
107399 }
107400
107401 /* termSortOrder is 0 or 1 for whether or not the access loop should
107402 ** run forward or backwards (respectively) in order to satisfy this
107403 ** term of the ORDER BY clause. */
107404 assert( pOBItem->sortOrder==0 || pOBItem->sortOrder==1 );
107405 assert( iSortOrder==0 || iSortOrder==1 );
107406 termSortOrder = iSortOrder ^ pOBItem->sortOrder;
107407
107408 /* If X is the column in the index and ORDER BY clause, check to see
107409 ** if there are any X= or X IS NULL constraints in the WHERE clause. */
107410 pConstraint = findTerm(p->pWC, base, iColumn, p->notReady,
107411 WO_EQ|WO_ISNULL|WO_IN, pIdx);
107412 if( pConstraint==0 ){
107413 isEq = 0;
107414 }else if( (pConstraint->eOperator & WO_IN)!=0 ){
107415 isEq = 0;
107416 }else if( (pConstraint->eOperator & WO_ISNULL)!=0 ){
107417 uniqueNotNull = 0;
107418 isEq = 1; /* "X IS NULL" means X has only a single value */
107419 }else if( pConstraint->prereqRight==0 ){
107420 isEq = 1; /* Constraint "X=constant" means X has only a single value */
107421 }else{
107422 Expr *pRight = pConstraint->pExpr->pRight;
107423 if( pRight->op==TK_COLUMN ){
107424 WHERETRACE((" .. isOrderedColumn(tab=%d,col=%d)",
107425 pRight->iTable, pRight->iColumn));
107426 isEq = isOrderedColumn(p, pRight->iTable, pRight->iColumn);
107427 WHERETRACE((" -> isEq=%d\n", isEq));
107428
107429 /* If the constraint is of the form X=Y where Y is an ordered value
107430 ** in an outer loop, then make sure the sort order of Y matches the
107431 ** sort order required for X. */
107432 if( isMatch && isEq>=2 && isEq!=pOBItem->sortOrder+2 ){
107433 testcase( isEq==2 );
107434 testcase( isEq==3 );
107435 break;
107436 }
107437 }else{
107438 isEq = 0; /* "X=expr" places no ordering constraints on X */
107439 }
107440 }
107441 if( !isMatch ){
107442 if( isEq==0 ){
107443 break;
107444 }else{
107445 continue;
107446 }
107447 }else if( isEq!=1 ){
107448 if( sortOrder==2 ){
107449 sortOrder = termSortOrder;
107450 }else if( termSortOrder!=sortOrder ){
107451 break;
107452 }
107453 }
107454 j++;
107455 pOBItem++;
107456 if( iColumn<0 ){
107457 seenRowid = 1;
107458 break;
107459 }else if( pTab->aCol[iColumn].notNull==0 && isEq!=1 ){
107460 testcase( isEq==0 );
107461 testcase( isEq==2 );
107462 testcase( isEq==3 );
107463 uniqueNotNull = 0;
107464 }
107465 }
107466 if( seenRowid ){
107467 uniqueNotNull = 1;
107468 }else if( uniqueNotNull==0 || i<pIdx->nColumn ){
107469 uniqueNotNull = 0;
107470 }
107471
107472 /* If we have not found at least one ORDER BY term that matches the
107473 ** index, then show no progress. */
107474 if( pOBItem==&pOrderBy->a[nPriorSat] ) return nPriorSat;
107475
107476 /* Either the outer queries must generate rows where there are no two
107477 ** rows with the same values in all ORDER BY columns, or else this
107478 ** loop must generate just a single row of output. Example: Suppose
107479 ** the outer loops generate A=1 and A=1, and this loop generates B=3
107480 ** and B=4. Then without the following test, ORDER BY A,B would
107481 ** generate the wrong order output: 1,3 1,4 1,3 1,4
107482 */
107483 if( outerObUnique==0 && uniqueNotNull==0 ) return nPriorSat;
107484 *pbObUnique = uniqueNotNull;
107485
107486 /* Return the necessary scan order back to the caller */
107487 *pbRev = sortOrder & 1;
107488
107489 /* If there was an "ORDER BY rowid" term that matched, or it is only
107490 ** possible for a single row from this table to match, then skip over
107491 ** any additional ORDER BY terms dealing with this table.
107492 */
107493 if( uniqueNotNull ){
107494 /* Advance j over additional ORDER BY terms associated with base */
107495 WhereMaskSet *pMS = p->pWC->pMaskSet;
107496 Bitmask m = ~getMask(pMS, base);
107497 while( j<nTerm && (exprTableUsage(pMS, pOrderBy->a[j].pExpr)&m)==0 ){
107498 j++;
107499 }
107500 }
107501 return j;
107502 }
107503
107504 /*
107505 ** Find the best query plan for accessing a particular table. Write the
107506 ** best query plan and its cost into the p->cost.
107507 **
107508 ** The lowest cost plan wins. The cost is an estimate of the amount of
107509 ** CPU and disk I/O needed to process the requested result.
107510 ** Factors that influence cost include:
107511 **
107512 ** * The estimated number of rows that will be retrieved. (The
107513 ** fewer the better.)
107514 **
107515 ** * Whether or not sorting must occur.
107516 **
107517 ** * Whether or not there must be separate lookups in the
107518 ** index and in the main table.
107519 **
107520 ** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
107521 ** the SQL statement, then this function only considers plans using the
107522 ** named index. If no such plan is found, then the returned cost is
107523 ** SQLITE_BIG_DBL. If a plan is found that uses the named index,
107524 ** then the cost is calculated in the usual way.
107525 **
107526 ** If a NOT INDEXED clause was attached to the table
107527 ** in the SELECT statement, then no indexes are considered. However, the
107528 ** selected plan may still take advantage of the built-in rowid primary key
107529 ** index.
107530 */
107531 static void bestBtreeIndex(WhereBestIdx *p){
107532 Parse *pParse = p->pParse; /* The parsing context */
107533 WhereClause *pWC = p->pWC; /* The WHERE clause */
107534 struct SrcList_item *pSrc = p->pSrc; /* The FROM clause term to search */
107535 int iCur = pSrc->iCursor; /* The cursor of the table to be accessed */
107536 Index *pProbe; /* An index we are evaluating */
107537 Index *pIdx; /* Copy of pProbe, or zero for IPK index */
107538 int eqTermMask; /* Current mask of valid equality operators */
107539 int idxEqTermMask; /* Index mask of valid equality operators */
107540 Index sPk; /* A fake index object for the primary key */
107541 tRowcnt aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
107542 int aiColumnPk = -1; /* The aColumn[] value for the sPk index */
107543 int wsFlagMask; /* Allowed flags in p->cost.plan.wsFlag */
107544 int nPriorSat; /* ORDER BY terms satisfied by outer loops */
107545 int nOrderBy; /* Number of ORDER BY terms */
107546 char bSortInit; /* Initializer for bSort in inner loop */
107547 char bDistInit; /* Initializer for bDist in inner loop */
107548
107549
107550 /* Initialize the cost to a worst-case value */
107551 memset(&p->cost, 0, sizeof(p->cost));
107552 p->cost.rCost = SQLITE_BIG_DBL;
107553
107554 /* If the pSrc table is the right table of a LEFT JOIN then we may not
107555 ** use an index to satisfy IS NULL constraints on that table. This is
107556 ** because columns might end up being NULL if the table does not match -
107557 ** a circumstance which the index cannot help us discover. Ticket #2177.
107558 */
107559 if( pSrc->jointype & JT_LEFT ){
107560 idxEqTermMask = WO_EQ|WO_IN;
107561 }else{
107562 idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
107563 }
107564
107565 if( pSrc->pIndex ){
107566 /* An INDEXED BY clause specifies a particular index to use */
107567 pIdx = pProbe = pSrc->pIndex;
107568 wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
107569 eqTermMask = idxEqTermMask;
107570 }else{
107571 /* There is no INDEXED BY clause. Create a fake Index object in local
107572 ** variable sPk to represent the rowid primary key index. Make this
107573 ** fake index the first in a chain of Index objects with all of the real
107574 ** indices to follow */
107575 Index *pFirst; /* First of real indices on the table */
107576 memset(&sPk, 0, sizeof(Index));
107577 sPk.nColumn = 1;
107578 sPk.aiColumn = &aiColumnPk;
107579 sPk.aiRowEst = aiRowEstPk;
107580 sPk.onError = OE_Replace;
107581 sPk.pTable = pSrc->pTab;
107582 aiRowEstPk[0] = pSrc->pTab->nRowEst;
107583 aiRowEstPk[1] = 1;
107584 pFirst = pSrc->pTab->pIndex;
107585 if( pSrc->notIndexed==0 ){
107586 /* The real indices of the table are only considered if the
107587 ** NOT INDEXED qualifier is omitted from the FROM clause */
107588 sPk.pNext = pFirst;
107589 }
107590 pProbe = &sPk;
107591 wsFlagMask = ~(
107592 WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
107593 );
107594 eqTermMask = WO_EQ|WO_IN;
107595 pIdx = 0;
107596 }
107597
107598 nOrderBy = p->pOrderBy ? p->pOrderBy->nExpr : 0;
107599 if( p->i ){
107600 nPriorSat = p->aLevel[p->i-1].plan.nOBSat;
107601 bSortInit = nPriorSat<nOrderBy;
107602 bDistInit = 0;
107603 }else{
107604 nPriorSat = 0;
107605 bSortInit = nOrderBy>0;
107606 bDistInit = p->pDistinct!=0;
107607 }
107608
107609 /* Loop over all indices looking for the best one to use
107610 */
107611 for(; pProbe; pIdx=pProbe=pProbe->pNext){
107612 const tRowcnt * const aiRowEst = pProbe->aiRowEst;
107613 WhereCost pc; /* Cost of using pProbe */
107614 double log10N = (double)1; /* base-10 logarithm of nRow (inexact) */
107615
107616 /* The following variables are populated based on the properties of
107617 ** index being evaluated. They are then used to determine the expected
107618 ** cost and number of rows returned.
107619 **
107620 ** pc.plan.nEq:
107621 ** Number of equality terms that can be implemented using the index.
107622 ** In other words, the number of initial fields in the index that
107623 ** are used in == or IN or NOT NULL constraints of the WHERE clause.
107624 **
107625 ** nInMul:
107626 ** The "in-multiplier". This is an estimate of how many seek operations
107627 ** SQLite must perform on the index in question. For example, if the
107628 ** WHERE clause is:
107629 **
107630 ** WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
107631 **
107632 ** SQLite must perform 9 lookups on an index on (a, b), so nInMul is
107633 ** set to 9. Given the same schema and either of the following WHERE
107634 ** clauses:
107635 **
107636 ** WHERE a = 1
107637 ** WHERE a >= 2
107638 **
107639 ** nInMul is set to 1.
107640 **
107641 ** If there exists a WHERE term of the form "x IN (SELECT ...)", then
107642 ** the sub-select is assumed to return 25 rows for the purposes of
107643 ** determining nInMul.
107644 **
107645 ** bInEst:
107646 ** Set to true if there was at least one "x IN (SELECT ...)" term used
107647 ** in determining the value of nInMul. Note that the RHS of the
107648 ** IN operator must be a SELECT, not a value list, for this variable
107649 ** to be true.
107650 **
107651 ** rangeDiv:
107652 ** An estimate of a divisor by which to reduce the search space due
107653 ** to inequality constraints. In the absence of sqlite_stat3 ANALYZE
107654 ** data, a single inequality reduces the search space to 1/4rd its
107655 ** original size (rangeDiv==4). Two inequalities reduce the search
107656 ** space to 1/16th of its original size (rangeDiv==16).
107657 **
107658 ** bSort:
107659 ** Boolean. True if there is an ORDER BY clause that will require an
107660 ** external sort (i.e. scanning the index being evaluated will not
107661 ** correctly order records).
107662 **
107663 ** bDist:
107664 ** Boolean. True if there is a DISTINCT clause that will require an
107665 ** external btree.
107666 **
107667 ** bLookup:
107668 ** Boolean. True if a table lookup is required for each index entry
107669 ** visited. In other words, true if this is not a covering index.
107670 ** This is always false for the rowid primary key index of a table.
107671 ** For other indexes, it is true unless all the columns of the table
107672 ** used by the SELECT statement are present in the index (such an
107673 ** index is sometimes described as a covering index).
107674 ** For example, given the index on (a, b), the second of the following
107675 ** two queries requires table b-tree lookups in order to find the value
107676 ** of column c, but the first does not because columns a and b are
107677 ** both available in the index.
107678 **
107679 ** SELECT a, b FROM tbl WHERE a = 1;
107680 ** SELECT a, b, c FROM tbl WHERE a = 1;
107681 */
107682 int bInEst = 0; /* True if "x IN (SELECT...)" seen */
107683 int nInMul = 1; /* Number of distinct equalities to lookup */
107684 double rangeDiv = (double)1; /* Estimated reduction in search space */
107685 int nBound = 0; /* Number of range constraints seen */
107686 char bSort = bSortInit; /* True if external sort required */
107687 char bDist = bDistInit; /* True if index cannot help with DISTINCT */
107688 char bLookup = 0; /* True if not a covering index */
107689 WhereTerm *pTerm; /* A single term of the WHERE clause */
107690 #ifdef SQLITE_ENABLE_STAT3
107691 WhereTerm *pFirstTerm = 0; /* First term matching the index */
107692 #endif
107693
107694 WHERETRACE((
107695 " %s(%s):\n",
107696 pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk")
107697 ));
107698 memset(&pc, 0, sizeof(pc));
107699 pc.plan.nOBSat = nPriorSat;
107700
107701 /* Determine the values of pc.plan.nEq and nInMul */
107702 for(pc.plan.nEq=0; pc.plan.nEq<pProbe->nColumn; pc.plan.nEq++){
107703 int j = pProbe->aiColumn[pc.plan.nEq];
107704 pTerm = findTerm(pWC, iCur, j, p->notReady, eqTermMask, pIdx);
107705 if( pTerm==0 ) break;
107706 pc.plan.wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
107707 testcase( pTerm->pWC!=pWC );
107708 if( pTerm->eOperator & WO_IN ){
107709 Expr *pExpr = pTerm->pExpr;
107710 pc.plan.wsFlags |= WHERE_COLUMN_IN;
107711 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
107712 /* "x IN (SELECT ...)": Assume the SELECT returns 25 rows */
107713 nInMul *= 25;
107714 bInEst = 1;
107715 }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
107716 /* "x IN (value, value, ...)" */
107717 nInMul *= pExpr->x.pList->nExpr;
107718 }
107719 }else if( pTerm->eOperator & WO_ISNULL ){
107720 pc.plan.wsFlags |= WHERE_COLUMN_NULL;
107721 }
107722 #ifdef SQLITE_ENABLE_STAT3
107723 if( pc.plan.nEq==0 && pProbe->aSample ) pFirstTerm = pTerm;
107724 #endif
107725 pc.used |= pTerm->prereqRight;
107726 }
107727
107728 /* If the index being considered is UNIQUE, and there is an equality
107729 ** constraint for all columns in the index, then this search will find
107730 ** at most a single row. In this case set the WHERE_UNIQUE flag to
107731 ** indicate this to the caller.
107732 **
107733 ** Otherwise, if the search may find more than one row, test to see if
107734 ** there is a range constraint on indexed column (pc.plan.nEq+1) that
107735 ** can be optimized using the index.
107736 */
107737 if( pc.plan.nEq==pProbe->nColumn && pProbe->onError!=OE_None ){
107738 testcase( pc.plan.wsFlags & WHERE_COLUMN_IN );
107739 testcase( pc.plan.wsFlags & WHERE_COLUMN_NULL );
107740 if( (pc.plan.wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
107741 pc.plan.wsFlags |= WHERE_UNIQUE;
107742 if( p->i==0 || (p->aLevel[p->i-1].plan.wsFlags & WHERE_ALL_UNIQUE)!=0 ){
107743 pc.plan.wsFlags |= WHERE_ALL_UNIQUE;
107744 }
107745 }
107746 }else if( pProbe->bUnordered==0 ){
107747 int j;
107748 j = (pc.plan.nEq==pProbe->nColumn ? -1 : pProbe->aiColumn[pc.plan.nEq]);
107749 if( findTerm(pWC, iCur, j, p->notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
107750 WhereTerm *pTop, *pBtm;
107751 pTop = findTerm(pWC, iCur, j, p->notReady, WO_LT|WO_LE, pIdx);
107752 pBtm = findTerm(pWC, iCur, j, p->notReady, WO_GT|WO_GE, pIdx);
107753 whereRangeScanEst(pParse, pProbe, pc.plan.nEq, pBtm, pTop, &rangeDiv);
107754 if( pTop ){
107755 nBound = 1;
107756 pc.plan.wsFlags |= WHERE_TOP_LIMIT;
107757 pc.used |= pTop->prereqRight;
107758 testcase( pTop->pWC!=pWC );
107759 }
107760 if( pBtm ){
107761 nBound++;
107762 pc.plan.wsFlags |= WHERE_BTM_LIMIT;
107763 pc.used |= pBtm->prereqRight;
107764 testcase( pBtm->pWC!=pWC );
107765 }
107766 pc.plan.wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
107767 }
107768 }
107769
107770 /* If there is an ORDER BY clause and the index being considered will
107771 ** naturally scan rows in the required order, set the appropriate flags
107772 ** in pc.plan.wsFlags. Otherwise, if there is an ORDER BY clause but
107773 ** the index will scan rows in a different order, set the bSort
107774 ** variable. */
107775 if( bSort && (pSrc->jointype & JT_LEFT)==0 ){
107776 int bRev = 2;
107777 int bObUnique = 0;
107778 WHERETRACE((" --> before isSortIndex: nPriorSat=%d\n",nPriorSat));
107779 pc.plan.nOBSat = isSortingIndex(p, pProbe, iCur, &bRev, &bObUnique);
107780 WHERETRACE((" --> after isSortIndex: bRev=%d bObU=%d nOBSat=%d\n",
107781 bRev, bObUnique, pc.plan.nOBSat));
107782 if( nPriorSat<pc.plan.nOBSat || (pc.plan.wsFlags & WHERE_ALL_UNIQUE)!=0 ){
107783 pc.plan.wsFlags |= WHERE_ORDERED;
107784 if( bObUnique ) pc.plan.wsFlags |= WHERE_OB_UNIQUE;
107785 }
107786 if( nOrderBy==pc.plan.nOBSat ){
107787 bSort = 0;
107788 pc.plan.wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE;
107789 }
107790 if( bRev & 1 ) pc.plan.wsFlags |= WHERE_REVERSE;
107791 }
107792
107793 /* If there is a DISTINCT qualifier and this index will scan rows in
107794 ** order of the DISTINCT expressions, clear bDist and set the appropriate
107795 ** flags in pc.plan.wsFlags. */
107796 if( bDist
107797 && isDistinctIndex(pParse, pWC, pProbe, iCur, p->pDistinct, pc.plan.nEq)
107798 && (pc.plan.wsFlags & WHERE_COLUMN_IN)==0
107799 ){
107800 bDist = 0;
107801 pc.plan.wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_DISTINCT;
107802 }
107803
107804 /* If currently calculating the cost of using an index (not the IPK
107805 ** index), determine if all required column data may be obtained without
107806 ** using the main table (i.e. if the index is a covering
107807 ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
107808 ** pc.plan.wsFlags. Otherwise, set the bLookup variable to true. */
107809 if( pIdx ){
107810 Bitmask m = pSrc->colUsed;
107811 int j;
107812 for(j=0; j<pIdx->nColumn; j++){
107813 int x = pIdx->aiColumn[j];
107814 if( x<BMS-1 ){
107815 m &= ~(((Bitmask)1)<<x);
107816 }
107817 }
107818 if( m==0 ){
107819 pc.plan.wsFlags |= WHERE_IDX_ONLY;
107820 }else{
107821 bLookup = 1;
107822 }
107823 }
107824
107825 /*
107826 ** Estimate the number of rows of output. For an "x IN (SELECT...)"
107827 ** constraint, do not let the estimate exceed half the rows in the table.
107828 */
107829 pc.plan.nRow = (double)(aiRowEst[pc.plan.nEq] * nInMul);
107830 if( bInEst && pc.plan.nRow*2>aiRowEst[0] ){
107831 pc.plan.nRow = aiRowEst[0]/2;
107832 nInMul = (int)(pc.plan.nRow / aiRowEst[pc.plan.nEq]);
107833 }
107834
107835 #ifdef SQLITE_ENABLE_STAT3
107836 /* If the constraint is of the form x=VALUE or x IN (E1,E2,...)
107837 ** and we do not think that values of x are unique and if histogram
107838 ** data is available for column x, then it might be possible
107839 ** to get a better estimate on the number of rows based on
107840 ** VALUE and how common that value is according to the histogram.
107841 */
107842 if( pc.plan.nRow>(double)1 && pc.plan.nEq==1
107843 && pFirstTerm!=0 && aiRowEst[1]>1 ){
107844 assert( (pFirstTerm->eOperator & (WO_EQ|WO_ISNULL|WO_IN))!=0 );
107845 if( pFirstTerm->eOperator & (WO_EQ|WO_ISNULL) ){
107846 testcase( pFirstTerm->eOperator & WO_EQ );
107847 testcase( pFirstTerm->eOperator & WO_EQUIV );
107848 testcase( pFirstTerm->eOperator & WO_ISNULL );
107849 whereEqualScanEst(pParse, pProbe, pFirstTerm->pExpr->pRight,
107850 &pc.plan.nRow);
107851 }else if( bInEst==0 ){
107852 assert( pFirstTerm->eOperator & WO_IN );
107853 whereInScanEst(pParse, pProbe, pFirstTerm->pExpr->x.pList,
107854 &pc.plan.nRow);
107855 }
107856 }
107857 #endif /* SQLITE_ENABLE_STAT3 */
107858
107859 /* Adjust the number of output rows and downward to reflect rows
107860 ** that are excluded by range constraints.
107861 */
107862 pc.plan.nRow = pc.plan.nRow/rangeDiv;
107863 if( pc.plan.nRow<1 ) pc.plan.nRow = 1;
107864
107865 /* Experiments run on real SQLite databases show that the time needed
107866 ** to do a binary search to locate a row in a table or index is roughly
107867 ** log10(N) times the time to move from one row to the next row within
107868 ** a table or index. The actual times can vary, with the size of
107869 ** records being an important factor. Both moves and searches are
107870 ** slower with larger records, presumably because fewer records fit
107871 ** on one page and hence more pages have to be fetched.
107872 **
107873 ** The ANALYZE command and the sqlite_stat1 and sqlite_stat3 tables do
107874 ** not give us data on the relative sizes of table and index records.
107875 ** So this computation assumes table records are about twice as big
107876 ** as index records
107877 */
107878 if( (pc.plan.wsFlags&~(WHERE_REVERSE|WHERE_ORDERED|WHERE_OB_UNIQUE))
107879 ==WHERE_IDX_ONLY
107880 && (pWC->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
107881 && sqlite3GlobalConfig.bUseCis
107882 && OptimizationEnabled(pParse->db, SQLITE_CoverIdxScan)
107883 ){
107884 /* This index is not useful for indexing, but it is a covering index.
107885 ** A full-scan of the index might be a little faster than a full-scan
107886 ** of the table, so give this case a cost slightly less than a table
107887 ** scan. */
107888 pc.rCost = aiRowEst[0]*3 + pProbe->nColumn;
107889 pc.plan.wsFlags |= WHERE_COVER_SCAN|WHERE_COLUMN_RANGE;
107890 }else if( (pc.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
107891 /* The cost of a full table scan is a number of move operations equal
107892 ** to the number of rows in the table.
107893 **
107894 ** We add an additional 4x penalty to full table scans. This causes
107895 ** the cost function to err on the side of choosing an index over
107896 ** choosing a full scan. This 4x full-scan penalty is an arguable
107897 ** decision and one which we expect to revisit in the future. But
107898 ** it seems to be working well enough at the moment.
107899 */
107900 pc.rCost = aiRowEst[0]*4;
107901 pc.plan.wsFlags &= ~WHERE_IDX_ONLY;
107902 if( pIdx ){
107903 pc.plan.wsFlags &= ~WHERE_ORDERED;
107904 pc.plan.nOBSat = nPriorSat;
107905 }
107906 }else{
107907 log10N = estLog(aiRowEst[0]);
107908 pc.rCost = pc.plan.nRow;
107909 if( pIdx ){
107910 if( bLookup ){
107911 /* For an index lookup followed by a table lookup:
107912 ** nInMul index searches to find the start of each index range
107913 ** + nRow steps through the index
107914 ** + nRow table searches to lookup the table entry using the rowid
107915 */
107916 pc.rCost += (nInMul + pc.plan.nRow)*log10N;
107917 }else{
107918 /* For a covering index:
107919 ** nInMul index searches to find the initial entry
107920 ** + nRow steps through the index
107921 */
107922 pc.rCost += nInMul*log10N;
107923 }
107924 }else{
107925 /* For a rowid primary key lookup:
107926 ** nInMult table searches to find the initial entry for each range
107927 ** + nRow steps through the table
107928 */
107929 pc.rCost += nInMul*log10N;
107930 }
107931 }
107932
107933 /* Add in the estimated cost of sorting the result. Actual experimental
107934 ** measurements of sorting performance in SQLite show that sorting time
107935 ** adds C*N*log10(N) to the cost, where N is the number of rows to be
107936 ** sorted and C is a factor between 1.95 and 4.3. We will split the
107937 ** difference and select C of 3.0.
107938 */
107939 if( bSort ){
107940 double m = estLog(pc.plan.nRow*(nOrderBy - pc.plan.nOBSat)/nOrderBy);
107941 m *= (double)(pc.plan.nOBSat ? 2 : 3);
107942 pc.rCost += pc.plan.nRow*m;
107943 }
107944 if( bDist ){
107945 pc.rCost += pc.plan.nRow*estLog(pc.plan.nRow)*3;
107946 }
107947
107948 /**** Cost of using this index has now been computed ****/
107949
107950 /* If there are additional constraints on this table that cannot
107951 ** be used with the current index, but which might lower the number
107952 ** of output rows, adjust the nRow value accordingly. This only
107953 ** matters if the current index is the least costly, so do not bother
107954 ** with this step if we already know this index will not be chosen.
107955 ** Also, never reduce the output row count below 2 using this step.
107956 **
107957 ** It is critical that the notValid mask be used here instead of
107958 ** the notReady mask. When computing an "optimal" index, the notReady
107959 ** mask will only have one bit set - the bit for the current table.
107960 ** The notValid mask, on the other hand, always has all bits set for
107961 ** tables that are not in outer loops. If notReady is used here instead
107962 ** of notValid, then a optimal index that depends on inner joins loops
107963 ** might be selected even when there exists an optimal index that has
107964 ** no such dependency.
107965 */
107966 if( pc.plan.nRow>2 && pc.rCost<=p->cost.rCost ){
107967 int k; /* Loop counter */
107968 int nSkipEq = pc.plan.nEq; /* Number of == constraints to skip */
107969 int nSkipRange = nBound; /* Number of < constraints to skip */
107970 Bitmask thisTab; /* Bitmap for pSrc */
107971
107972 thisTab = getMask(pWC->pMaskSet, iCur);
107973 for(pTerm=pWC->a, k=pWC->nTerm; pc.plan.nRow>2 && k; k--, pTerm++){
107974 if( pTerm->wtFlags & TERM_VIRTUAL ) continue;
107975 if( (pTerm->prereqAll & p->notValid)!=thisTab ) continue;
107976 if( pTerm->eOperator & (WO_EQ|WO_IN|WO_ISNULL) ){
107977 if( nSkipEq ){
107978 /* Ignore the first pc.plan.nEq equality matches since the index
107979 ** has already accounted for these */
107980 nSkipEq--;
107981 }else{
107982 /* Assume each additional equality match reduces the result
107983 ** set size by a factor of 10 */
107984 pc.plan.nRow /= 10;
107985 }
107986 }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GT|WO_GE) ){
107987 if( nSkipRange ){
107988 /* Ignore the first nSkipRange range constraints since the index
107989 ** has already accounted for these */
107990 nSkipRange--;
107991 }else{
107992 /* Assume each additional range constraint reduces the result
107993 ** set size by a factor of 3. Indexed range constraints reduce
107994 ** the search space by a larger factor: 4. We make indexed range
107995 ** more selective intentionally because of the subjective
107996 ** observation that indexed range constraints really are more
107997 ** selective in practice, on average. */
107998 pc.plan.nRow /= 3;
107999 }
108000 }else if( (pTerm->eOperator & WO_NOOP)==0 ){
108001 /* Any other expression lowers the output row count by half */
108002 pc.plan.nRow /= 2;
108003 }
108004 }
108005 if( pc.plan.nRow<2 ) pc.plan.nRow = 2;
108006 }
108007
108008
108009 WHERETRACE((
108010 " nEq=%d nInMul=%d rangeDiv=%d bSort=%d bLookup=%d wsFlags=0x%08x\n"
108011 " notReady=0x%llx log10N=%.1f nRow=%.1f cost=%.1f\n"
108012 " used=0x%llx nOBSat=%d\n",
108013 pc.plan.nEq, nInMul, (int)rangeDiv, bSort, bLookup, pc.plan.wsFlags,
108014 p->notReady, log10N, pc.plan.nRow, pc.rCost, pc.used,
108015 pc.plan.nOBSat
108016 ));
108017
108018 /* If this index is the best we have seen so far, then record this
108019 ** index and its cost in the p->cost structure.
108020 */
108021 if( (!pIdx || pc.plan.wsFlags) && compareCost(&pc, &p->cost) ){
108022 p->cost = pc;
108023 p->cost.plan.wsFlags &= wsFlagMask;
108024 p->cost.plan.u.pIdx = pIdx;
108025 }
108026
108027 /* If there was an INDEXED BY clause, then only that one index is
108028 ** considered. */
108029 if( pSrc->pIndex ) break;
108030
108031 /* Reset masks for the next index in the loop */
108032 wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
108033 eqTermMask = idxEqTermMask;
108034 }
108035
108036 /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
108037 ** is set, then reverse the order that the index will be scanned
108038 ** in. This is used for application testing, to help find cases
108039 ** where application behavior depends on the (undefined) order that
108040 ** SQLite outputs rows in in the absence of an ORDER BY clause. */
108041 if( !p->pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
108042 p->cost.plan.wsFlags |= WHERE_REVERSE;
108043 }
108044
108045 assert( p->pOrderBy || (p->cost.plan.wsFlags&WHERE_ORDERED)==0 );
108046 assert( p->cost.plan.u.pIdx==0 || (p->cost.plan.wsFlags&WHERE_ROWID_EQ)==0 );
108047 assert( pSrc->pIndex==0
108048 || p->cost.plan.u.pIdx==0
108049 || p->cost.plan.u.pIdx==pSrc->pIndex
108050 );
108051
108052 WHERETRACE((" best index is %s cost=%.1f\n",
108053 p->cost.plan.u.pIdx ? p->cost.plan.u.pIdx->zName : "ipk",
108054 p->cost.rCost));
108055
108056 bestOrClauseIndex(p);
108057 bestAutomaticIndex(p);
108058 p->cost.plan.wsFlags |= eqTermMask;
108059 }
108060
108061 /*
108062 ** Find the query plan for accessing table pSrc->pTab. Write the
108063 ** best query plan and its cost into the WhereCost object supplied
108064 ** as the last parameter. This function may calculate the cost of
108065 ** both real and virtual table scans.
108066 **
108067 ** This function does not take ORDER BY or DISTINCT into account. Nor
108068 ** does it remember the virtual table query plan. All it does is compute
108069 ** the cost while determining if an OR optimization is applicable. The
108070 ** details will be reconsidered later if the optimization is found to be
108071 ** applicable.
108072 */
108073 static void bestIndex(WhereBestIdx *p){
108074 #ifndef SQLITE_OMIT_VIRTUALTABLE
108075 if( IsVirtual(p->pSrc->pTab) ){
108076 sqlite3_index_info *pIdxInfo = 0;
108077 p->ppIdxInfo = &pIdxInfo;
108078 bestVirtualIndex(p);
108079 assert( pIdxInfo!=0 || p->pParse->db->mallocFailed );
108080 if( pIdxInfo && pIdxInfo->needToFreeIdxStr ){
108081 sqlite3_free(pIdxInfo->idxStr);
108082 }
108083 sqlite3DbFree(p->pParse->db, pIdxInfo);
108084 }else
108085 #endif
108086 {
108087 bestBtreeIndex(p);
108088 }
108089 }
108090
108091 /*
108092 ** Disable a term in the WHERE clause. Except, do not disable the term
108093 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
108094 ** or USING clause of that join.
@@ -108183,10 +107107,11 @@
108183 static int codeEqualityTerm(
108184 Parse *pParse, /* The parsing context */
108185 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
108186 WhereLevel *pLevel, /* The level of the FROM clause we are working on */
108187 int iEq, /* Index of the equality term within this level */
 
108188 int iTarget /* Attempt to leave results in this register */
108189 ){
108190 Expr *pX = pTerm->pExpr;
108191 Vdbe *v = pParse->pVdbe;
108192 int iReg; /* Register holding results */
@@ -108200,18 +107125,17 @@
108200 #ifndef SQLITE_OMIT_SUBQUERY
108201 }else{
108202 int eType;
108203 int iTab;
108204 struct InLoop *pIn;
108205 u8 bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
108206
108207 if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0
108208 && pLevel->plan.u.pIdx->aSortOrder[iEq]
 
108209 ){
108210 testcase( iEq==0 );
108211 testcase( iEq==pLevel->plan.u.pIdx->nColumn-1 );
108212 testcase( iEq>0 && iEq+1<pLevel->plan.u.pIdx->nColumn );
108213 testcase( bRev );
108214 bRev = !bRev;
108215 }
108216 assert( pX->op==TK_IN );
108217 iReg = iTarget;
@@ -108220,11 +107144,12 @@
108220 testcase( bRev );
108221 bRev = !bRev;
108222 }
108223 iTab = pX->iTable;
108224 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
108225 assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
 
108226 if( pLevel->u.in.nIn==0 ){
108227 pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
108228 }
108229 pLevel->u.in.nIn++;
108230 pLevel->u.in.aInLoop =
@@ -108290,33 +107215,35 @@
108290 ** string in this example would be set to SQLITE_AFF_NONE.
108291 */
108292 static int codeAllEqualityTerms(
108293 Parse *pParse, /* Parsing context */
108294 WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
108295 WhereClause *pWC, /* The WHERE clause */
108296 Bitmask notReady, /* Which parts of FROM have not yet been coded */
108297 int nExtraReg, /* Number of extra registers to allocate */
108298 char **pzAff /* OUT: Set to point to affinity string */
108299 ){
108300 int nEq = pLevel->plan.nEq; /* The number of == or IN constraints to code */
108301 Vdbe *v = pParse->pVdbe; /* The vm under construction */
108302 Index *pIdx; /* The index being used for this loop */
108303 int iCur = pLevel->iTabCur; /* The cursor of the table */
108304 WhereTerm *pTerm; /* A single constraint term */
 
108305 int j; /* Loop counter */
108306 int regBase; /* Base register */
108307 int nReg; /* Number of registers to allocate */
108308 char *zAff; /* Affinity string to return */
108309
108310 /* This module is only called on query plans that use an index. */
108311 assert( pLevel->plan.wsFlags & WHERE_INDEXED );
108312 pIdx = pLevel->plan.u.pIdx;
 
 
 
108313
108314 /* Figure out how many memory cells we will need then allocate them.
108315 */
108316 regBase = pParse->nMem + 1;
108317 nReg = pLevel->plan.nEq + nExtraReg;
108318 pParse->nMem += nReg;
108319
108320 zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
108321 if( !zAff ){
108322 pParse->db->mallocFailed = 1;
@@ -108325,18 +107252,17 @@
108325 /* Evaluate the equality constraints
108326 */
108327 assert( pIdx->nColumn>=nEq );
108328 for(j=0; j<nEq; j++){
108329 int r1;
108330 int k = pIdx->aiColumn[j];
108331 pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
108332 if( pTerm==0 ) break;
108333 /* The following true for indices with redundant columns.
108334 ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
108335 testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
108336 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
108337 r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, regBase+j);
108338 if( r1!=regBase+j ){
108339 if( nReg==1 ){
108340 sqlite3ReleaseTempReg(pParse, regBase);
108341 regBase = r1;
108342 }else{
@@ -108400,20 +107326,19 @@
108400 **
108401 ** The returned pointer points to memory obtained from sqlite3DbMalloc().
108402 ** It is the responsibility of the caller to free the buffer when it is
108403 ** no longer required.
108404 */
108405 static char *explainIndexRange(sqlite3 *db, WhereLevel *pLevel, Table *pTab){
108406 WherePlan *pPlan = &pLevel->plan;
108407 Index *pIndex = pPlan->u.pIdx;
108408 int nEq = pPlan->nEq;
108409 int i, j;
108410 Column *aCol = pTab->aCol;
108411 int *aiColumn = pIndex->aiColumn;
108412 StrAccum txt;
108413
108414 if( nEq==0 && (pPlan->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
108415 return 0;
108416 }
108417 sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
108418 txt.db = db;
108419 sqlite3StrAccumAppend(&txt, " (", 2);
@@ -108420,15 +107345,15 @@
108420 for(i=0; i<nEq; i++){
108421 explainAppendTerm(&txt, i, aCol[aiColumn[i]].zName, "=");
108422 }
108423
108424 j = i;
108425 if( pPlan->wsFlags&WHERE_BTM_LIMIT ){
108426 char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
108427 explainAppendTerm(&txt, i++, z, ">");
108428 }
108429 if( pPlan->wsFlags&WHERE_TOP_LIMIT ){
108430 char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
108431 explainAppendTerm(&txt, i, z, "<");
108432 }
108433 sqlite3StrAccumAppend(&txt, ")", 1);
108434 return sqlite3StrAccumFinish(&txt);
@@ -108447,24 +107372,26 @@
108447 int iLevel, /* Value for "level" column of output */
108448 int iFrom, /* Value for "from" column of output */
108449 u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
108450 ){
108451 if( pParse->explain==2 ){
108452 u32 flags = pLevel->plan.wsFlags;
108453 struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
108454 Vdbe *v = pParse->pVdbe; /* VM being constructed */
108455 sqlite3 *db = pParse->db; /* Database handle */
108456 char *zMsg; /* Text to add to EQP output */
108457 sqlite3_int64 nRow; /* Expected number of rows visited by scan */
108458 int iId = pParse->iSelectId; /* Select id (left-most output column) */
108459 int isSearch; /* True for a SEARCH. False for SCAN. */
 
 
108460
 
 
108461 if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
108462
108463 isSearch = (pLevel->plan.nEq>0)
108464 || (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
108465 || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
108466
108467 zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
108468 if( pItem->pSelect ){
108469 zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
108470 }else{
@@ -108472,47 +107399,42 @@
108472 }
108473
108474 if( pItem->zAlias ){
108475 zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
108476 }
108477 if( (flags & WHERE_INDEXED)!=0 ){
108478 char *zWhere = explainIndexRange(db, pLevel, pItem->pTab);
 
 
108479 zMsg = sqlite3MAppendf(db, zMsg, "%s USING %s%sINDEX%s%s%s", zMsg,
108480 ((flags & WHERE_TEMP_INDEX)?"AUTOMATIC ":""),
108481 ((flags & WHERE_IDX_ONLY)?"COVERING ":""),
108482 ((flags & WHERE_TEMP_INDEX)?"":" "),
108483 ((flags & WHERE_TEMP_INDEX)?"": pLevel->plan.u.pIdx->zName),
108484 zWhere
108485 );
108486 sqlite3DbFree(db, zWhere);
108487 }else if( flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
108488 zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
108489
108490 if( flags&WHERE_ROWID_EQ ){
108491 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
108492 }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
108493 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
108494 }else if( flags&WHERE_BTM_LIMIT ){
108495 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
108496 }else if( flags&WHERE_TOP_LIMIT ){
108497 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
108498 }
108499 }
108500 #ifndef SQLITE_OMIT_VIRTUALTABLE
108501 else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
108502 sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
108503 zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
108504 pVtabIdx->idxNum, pVtabIdx->idxStr);
108505 }
108506 #endif
108507 if( wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) ){
108508 testcase( wctrlFlags & WHERE_ORDERBY_MIN );
108509 nRow = 1;
108510 }else{
108511 nRow = (sqlite3_int64)pLevel->plan.nRow;
108512 }
108513 zMsg = sqlite3MAppendf(db, zMsg, "%s (~%lld rows)", zMsg, nRow);
108514 sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
108515 }
108516 }
108517 #else
108518 # define explainOneScan(u,v,w,x,y,z)
@@ -108524,19 +107446,19 @@
108524 ** implementation described by pWInfo.
108525 */
108526 static Bitmask codeOneLoopStart(
108527 WhereInfo *pWInfo, /* Complete information about the WHERE clause */
108528 int iLevel, /* Which level of pWInfo->a[] should be coded */
108529 u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
108530 Bitmask notReady /* Which tables are currently available */
108531 ){
108532 int j, k; /* Loop counters */
108533 int iCur; /* The VDBE cursor for the table */
108534 int addrNxt; /* Where to jump to continue with the next IN case */
108535 int omitTable; /* True if we use the index only */
108536 int bRev; /* True if we need to scan in reverse order */
108537 WhereLevel *pLevel; /* The where level to be coded */
 
108538 WhereClause *pWC; /* Decomposition of the entire WHERE clause */
108539 WhereTerm *pTerm; /* A WHERE clause term */
108540 Parse *pParse; /* Parsing context */
108541 Vdbe *v; /* The prepared stmt under constructions */
108542 struct SrcList_item *pTabItem; /* FROM clause term being coded */
@@ -108546,17 +107468,18 @@
108546 int iReleaseReg = 0; /* Temp register to free before returning */
108547 Bitmask newNotReady; /* Return value */
108548
108549 pParse = pWInfo->pParse;
108550 v = pParse->pVdbe;
108551 pWC = pWInfo->pWC;
108552 pLevel = &pWInfo->a[iLevel];
 
108553 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
108554 iCur = pTabItem->iCursor;
108555 bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
108556 omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0
108557 && (wctrlFlags & WHERE_FORCE_TABLE)==0;
108558 VdbeNoopComment((v, "Begin Join Loop %d", iLevel));
108559
108560 /* Create labels for the "break" and "continue" instructions
108561 ** for the current loop. Jump to addrBrk to break out of a loop.
108562 ** Jump to cont to go immediately to the next iteration of the
@@ -108589,51 +107512,41 @@
108589 sqlite3VdbeAddOp2(v, OP_If, regYield+1, addrBrk);
108590 pLevel->op = OP_Goto;
108591 }else
108592
108593 #ifndef SQLITE_OMIT_VIRTUALTABLE
108594 if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
108595 /* Case 0: The table is a virtual-table. Use the VFilter and VNext
108596 ** to access the data.
108597 */
108598 int iReg; /* P3 Value for OP_VFilter */
108599 int addrNotFound;
108600 sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
108601 int nConstraint = pVtabIdx->nConstraint;
108602 struct sqlite3_index_constraint_usage *aUsage =
108603 pVtabIdx->aConstraintUsage;
108604 const struct sqlite3_index_constraint *aConstraint =
108605 pVtabIdx->aConstraint;
108606
108607 sqlite3ExprCachePush(pParse);
108608 iReg = sqlite3GetTempRange(pParse, nConstraint+2);
108609 addrNotFound = pLevel->addrBrk;
108610 for(j=1; j<=nConstraint; j++){
108611 for(k=0; k<nConstraint; k++){
108612 if( aUsage[k].argvIndex==j ){
108613 int iTarget = iReg+j+1;
108614 pTerm = &pWC->a[aConstraint[k].iTermOffset];
108615 if( pTerm->eOperator & WO_IN ){
108616 codeEqualityTerm(pParse, pTerm, pLevel, k, iTarget);
108617 addrNotFound = pLevel->addrNxt;
108618 }else{
108619 sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
108620 }
108621 break;
108622 }
108623 }
108624 if( k==nConstraint ) break;
108625 }
108626 sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
108627 sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
108628 sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg, pVtabIdx->idxStr,
108629 pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
108630 pVtabIdx->needToFreeIdxStr = 0;
108631 for(j=0; j<nConstraint; j++){
108632 if( aUsage[j].omit ){
108633 int iTerm = aConstraint[j].iTermOffset;
108634 disableTerm(pLevel, &pWC->a[iTerm]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108635 }
108636 }
108637 pLevel->op = OP_VNext;
108638 pLevel->p1 = iCur;
108639 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
@@ -108640,41 +107553,49 @@
108640 sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
108641 sqlite3ExprCachePop(pParse, 1);
108642 }else
108643 #endif /* SQLITE_OMIT_VIRTUALTABLE */
108644
108645 if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
108646 /* Case 1: We can directly reference a single row using an
 
 
108647 ** equality comparison against the ROWID field. Or
108648 ** we reference multiple rows using a "rowid IN (...)"
108649 ** construct.
108650 */
 
108651 iReleaseReg = sqlite3GetTempReg(pParse);
108652 pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
108653 assert( pTerm!=0 );
108654 assert( pTerm->pExpr!=0 );
108655 assert( omitTable==0 );
108656 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
108657 iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, iReleaseReg);
108658 addrNxt = pLevel->addrNxt;
108659 sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
108660 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
108661 sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
108662 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
108663 VdbeComment((v, "pk"));
108664 pLevel->op = OP_Noop;
108665 }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
108666 /* Case 2: We have an inequality comparison against the ROWID field.
 
 
108667 */
108668 int testOp = OP_Noop;
108669 int start;
108670 int memEndValue = 0;
108671 WhereTerm *pStart, *pEnd;
108672
108673 assert( omitTable==0 );
108674 pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
108675 pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
 
 
 
108676 if( bRev ){
108677 pTerm = pStart;
108678 pStart = pEnd;
108679 pEnd = pTerm;
108680 }
@@ -108725,24 +107646,20 @@
108725 }
108726 start = sqlite3VdbeCurrentAddr(v);
108727 pLevel->op = bRev ? OP_Prev : OP_Next;
108728 pLevel->p1 = iCur;
108729 pLevel->p2 = start;
108730 if( pStart==0 && pEnd==0 ){
108731 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
108732 }else{
108733 assert( pLevel->p5==0 );
108734 }
108735 if( testOp!=OP_Noop ){
108736 iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
108737 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
108738 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
108739 sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
108740 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
108741 }
108742 }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
108743 /* Case 3: A scan using an index.
108744 **
108745 ** The WHERE clause may contain zero or more equality
108746 ** terms ("==" or "IN" operators) that refer to the N
108747 ** left-most columns of the index. It may also contain
108748 ** inequality constraints (>, <, >= or <=) on the indexed
@@ -108784,12 +107701,12 @@
108784 static const u8 aEndOp[] = {
108785 OP_Noop, /* 0: (!end_constraints) */
108786 OP_IdxGE, /* 1: (end_constraints && !bRev) */
108787 OP_IdxLT /* 2: (end_constraints && bRev) */
108788 };
108789 int nEq = pLevel->plan.nEq; /* Number of == or IN terms */
108790 int isMinQuery = 0; /* If this is an optimized SELECT min(x).. */
108791 int regBase; /* Base register holding constraint values */
108792 int r1; /* Temp register */
108793 WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
108794 WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
108795 int startEq; /* True if range start uses ==, >= or <= */
@@ -108801,24 +107718,23 @@
108801 int nExtraReg = 0; /* Number of extra registers needed */
108802 int op; /* Instruction opcode */
108803 char *zStartAff; /* Affinity for start of range constraint */
108804 char *zEndAff; /* Affinity for end of range constraint */
108805
108806 pIdx = pLevel->plan.u.pIdx;
108807 iIdxCur = pLevel->iIdxCur;
108808 k = (nEq==pIdx->nColumn ? -1 : pIdx->aiColumn[nEq]);
108809
108810 /* If this loop satisfies a sort order (pOrderBy) request that
108811 ** was passed to this function to implement a "SELECT min(x) ..."
108812 ** query, then the caller will only allow the loop to run for
108813 ** a single iteration. This means that the first row returned
108814 ** should not have a NULL value stored in 'x'. If column 'x' is
108815 ** the first one after the nEq equality constraints in the index,
108816 ** this requires some special handling.
108817 */
108818 if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
108819 && (pLevel->plan.wsFlags&WHERE_ORDERED)
108820 && (pIdx->nColumn>nEq)
108821 ){
108822 /* assert( pOrderBy->nExpr==1 ); */
108823 /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
108824 isMinQuery = 1;
@@ -108826,26 +107742,25 @@
108826 }
108827
108828 /* Find any inequality constraint terms for the start and end
108829 ** of the range.
108830 */
108831 if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
108832 pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
 
108833 nExtraReg = 1;
108834 }
108835 if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
108836 pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
108837 nExtraReg = 1;
108838 }
108839
108840 /* Generate code to evaluate all constraint terms using == or IN
108841 ** and store the values of those terms in an array of registers
108842 ** starting at regBase.
108843 */
108844 regBase = codeAllEqualityTerms(
108845 pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff
108846 );
108847 zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
108848 addrNxt = pLevel->addrNxt;
108849
108850 /* If we are doing a reverse order scan on an ascending index, or
108851 ** a forward order scan on a descending index, interchange the
@@ -108855,14 +107770,14 @@
108855 || (bRev && pIdx->nColumn==nEq)
108856 ){
108857 SWAP(WhereTerm *, pRangeEnd, pRangeStart);
108858 }
108859
108860 testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
108861 testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
108862 testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
108863 testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
108864 startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
108865 endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
108866 start_constraints = pRangeStart || nEq>0;
108867
108868 /* Seek the index cursor to the start of the range. */
@@ -108948,13 +107863,13 @@
108948 /* If there are inequality constraints, check that the value
108949 ** of the table column that the inequality contrains is not NULL.
108950 ** If it is, jump to the next iteration of the loop.
108951 */
108952 r1 = sqlite3GetTempReg(pParse);
108953 testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
108954 testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
108955 if( (pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
108956 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
108957 sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
108958 }
108959 sqlite3ReleaseTempReg(pParse, r1);
108960
@@ -108969,28 +107884,28 @@
108969 }
108970
108971 /* Record the instruction used to terminate the loop. Disable
108972 ** WHERE clause terms made redundant by the index range scan.
108973 */
108974 if( pLevel->plan.wsFlags & WHERE_UNIQUE ){
108975 pLevel->op = OP_Noop;
108976 }else if( bRev ){
108977 pLevel->op = OP_Prev;
108978 }else{
108979 pLevel->op = OP_Next;
108980 }
108981 pLevel->p1 = iIdxCur;
108982 if( pLevel->plan.wsFlags & WHERE_COVER_SCAN ){
108983 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
108984 }else{
108985 assert( pLevel->p5==0 );
108986 }
108987 }else
108988
108989 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
108990 if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
108991 /* Case 4: Two or more separately indexed terms connected by OR
108992 **
108993 ** Example:
108994 **
108995 ** CREATE TABLE t1(a,b,c,d);
108996 ** CREATE INDEX i1 ON t1(a);
@@ -109039,11 +107954,11 @@
109039 int iRetInit; /* Address of regReturn init */
109040 int untestedTerms = 0; /* Some terms not completely tested */
109041 int ii; /* Loop counter */
109042 Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
109043
109044 pTerm = pLevel->plan.u.pTerm;
109045 assert( pTerm!=0 );
109046 assert( pTerm->eOperator & WO_OR );
109047 assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
109048 pOrWc = &pTerm->u.pOrInfo->wc;
109049 pLevel->op = OP_Return;
@@ -109058,11 +107973,11 @@
109058 struct SrcList_item *origSrc; /* Original list of tables */
109059 nNotReady = pWInfo->nLevel - iLevel - 1;
109060 pOrTab = sqlite3StackAllocRaw(pParse->db,
109061 sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
109062 if( pOrTab==0 ) return notReady;
109063 pOrTab->nAlloc = (i16)(nNotReady + 1);
109064 pOrTab->nSrc = pOrTab->nAlloc;
109065 memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
109066 origSrc = pWInfo->pTabList->a;
109067 for(k=1; k<=nNotReady; k++){
109068 memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
@@ -109080,11 +107995,11 @@
109080 ** over the top of the loop into the body of it. In this case the
109081 ** correct response for the end-of-loop code (the OP_Return) is to
109082 ** fall through to the next instruction, just as an OP_Next does if
109083 ** called on an uninitialized cursor.
109084 */
109085 if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
109086 regRowset = ++pParse->nMem;
109087 regRowid = ++pParse->nMem;
109088 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
109089 }
109090 iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
@@ -109131,15 +108046,15 @@
109131 pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
109132 WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
109133 WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY, iCovCur);
109134 assert( pSubWInfo || pParse->nErr || pParse->db->mallocFailed );
109135 if( pSubWInfo ){
109136 WhereLevel *pLvl;
109137 explainOneScan(
109138 pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
109139 );
109140 if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
109141 int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
109142 int r;
109143 r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
109144 regRowid, 0);
109145 sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
@@ -109164,17 +108079,17 @@
109164 ** processed or the index is the same as that used by all previous
109165 ** terms, set pCov to the candidate covering index. Otherwise, set
109166 ** pCov to NULL to indicate that no candidate covering index will
109167 ** be available.
109168 */
109169 pLvl = &pSubWInfo->a[0];
109170 if( (pLvl->plan.wsFlags & WHERE_INDEXED)!=0
109171 && (pLvl->plan.wsFlags & WHERE_TEMP_INDEX)==0
109172 && (ii==0 || pLvl->plan.u.pIdx==pCov)
109173 ){
109174 assert( pLvl->iIdxCur==iCovCur );
109175 pCov = pLvl->plan.u.pIdx;
109176 }else{
109177 pCov = 0;
109178 }
109179
109180 /* Finish the loop through table entries that match term pOrTerm. */
@@ -109196,23 +108111,22 @@
109196 if( !untestedTerms ) disableTerm(pLevel, pTerm);
109197 }else
109198 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
109199
109200 {
109201 /* Case 5: There is no usable index. We must do a complete
109202 ** scan of the entire table.
109203 */
109204 static const u8 aStep[] = { OP_Next, OP_Prev };
109205 static const u8 aStart[] = { OP_Rewind, OP_Last };
109206 assert( bRev==0 || bRev==1 );
109207 assert( omitTable==0 );
109208 pLevel->op = aStep[bRev];
109209 pLevel->p1 = iCur;
109210 pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
109211 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
109212 }
109213 newNotReady = notReady & ~getMask(pWC->pMaskSet, iCur);
109214
109215 /* Insert code to test every subexpression that can be completely
109216 ** computed using the current set of tables.
109217 **
109218 ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
@@ -109258,10 +108172,12 @@
109258 assert( !ExprHasProperty(pE, EP_FromJoin) );
109259 assert( (pTerm->prereqRight & newNotReady)!=0 );
109260 pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
109261 if( pAlt==0 ) continue;
109262 if( pAlt->wtFlags & (TERM_CODED) ) continue;
 
 
109263 VdbeNoopComment((v, "begin transitive constraint"));
109264 sEq = *pAlt->pExpr;
109265 sEq.pLeft = pE->pLeft;
109266 sqlite3ExprIfFalse(pParse, &sEq, addrCont, SQLITE_JUMPIFNULL);
109267 }
@@ -109290,51 +108206,1562 @@
109290 sqlite3ReleaseTempReg(pParse, iReleaseReg);
109291
109292 return newNotReady;
109293 }
109294
109295 #if defined(SQLITE_TEST)
109296 /*
109297 ** The following variable holds a text description of query plan generated
109298 ** by the most recent call to sqlite3WhereBegin(). Each call to WhereBegin
109299 ** overwrites the previous. This information is used for testing and
109300 ** analysis only.
109301 */
109302 SQLITE_API char sqlite3_query_plan[BMS*2*40]; /* Text of the join */
109303 static int nQPlan = 0; /* Next free slow in _query_plan[] */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109304
109305 #endif /* SQLITE_TEST */
 
 
 
 
 
 
 
 
 
109306
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109307
109308 /*
109309 ** Free a WhereInfo structure
109310 */
109311 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
109312 if( ALWAYS(pWInfo) ){
109313 int i;
109314 for(i=0; i<pWInfo->nLevel; i++){
109315 sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
109316 if( pInfo ){
109317 /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
109318 if( pInfo->needToFreeIdxStr ){
109319 sqlite3_free(pInfo->idxStr);
109320 }
109321 sqlite3DbFree(db, pInfo);
109322 }
109323 if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){
109324 Index *pIdx = pWInfo->a[i].plan.u.pIdx;
109325 if( pIdx ){
109326 sqlite3DbFree(db, pIdx->zColAff);
109327 sqlite3DbFree(db, pIdx);
109328 }
109329 }
109330 }
109331 whereClauseClear(pWInfo->pWC);
109332 sqlite3DbFree(db, pWInfo);
109333 }
109334 }
109335
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109336
109337 /*
109338 ** Generate the beginning of the loop used for WHERE clause processing.
109339 ** The return value is a pointer to an opaque structure that contains
109340 ** information needed to terminate the loop. Later, the calling routine
@@ -109410,19 +109837,10 @@
109410 ** ORDER BY CLAUSE PROCESSING
109411 **
109412 ** pOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
109413 ** if there is one. If there is no ORDER BY clause or if this routine
109414 ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
109415 **
109416 ** If an index can be used so that the natural output order of the table
109417 ** scan is correct for the ORDER BY clause, then that index is used and
109418 ** the returned WhereInfo.nOBSat field is set to pOrderBy->nExpr. This
109419 ** is an optimization that prevents an unnecessary sort of the result set
109420 ** if an index appropriate for the ORDER BY clause already exists.
109421 **
109422 ** If the where clause loops cannot be arranged to provide the correct
109423 ** output order, then WhereInfo.nOBSat is 0.
109424 */
109425 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
109426 Parse *pParse, /* The parser context */
109427 SrcList *pTabList, /* A list of all tables to be scanned */
109428 Expr *pWhere, /* The WHERE clause */
@@ -109434,22 +109852,21 @@
109434 int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
109435 int nTabList; /* Number of elements in pTabList */
109436 WhereInfo *pWInfo; /* Will become the return value of this function */
109437 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
109438 Bitmask notReady; /* Cursors that are not yet positioned */
109439 WhereBestIdx sWBI; /* Best index search context */
109440 WhereMaskSet *pMaskSet; /* The expression mask set */
109441 WhereLevel *pLevel; /* A single level in pWInfo->a[] */
109442 int iFrom; /* First unused FROM clause element */
109443 int andFlags; /* AND-ed combination of all pWC->a[].wtFlags */
109444 int ii; /* Loop counter */
109445 sqlite3 *db; /* Database connection */
 
109446
109447
109448 /* Variable initialization */
109449 memset(&sWBI, 0, sizeof(sWBI));
109450 sWBI.pParse = pParse;
109451
109452 /* The number of tables in the FROM clause is limited by the number of
109453 ** bits in a Bitmask
109454 */
109455 testcase( pTabList->nSrc==BMS );
@@ -109472,49 +109889,59 @@
109472 ** field (type Bitmask) it must be aligned on an 8-byte boundary on
109473 ** some architectures. Hence the ROUND8() below.
109474 */
109475 db = pParse->db;
109476 nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
109477 pWInfo = sqlite3DbMallocZero(db,
109478 nByteWInfo +
109479 sizeof(WhereClause) +
109480 sizeof(WhereMaskSet)
109481 );
109482 if( db->mallocFailed ){
109483 sqlite3DbFree(db, pWInfo);
109484 pWInfo = 0;
109485 goto whereBeginError;
109486 }
109487 pWInfo->nLevel = nTabList;
109488 pWInfo->pParse = pParse;
109489 pWInfo->pTabList = pTabList;
 
 
109490 pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
109491 pWInfo->pWC = sWBI.pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
109492 pWInfo->wctrlFlags = wctrlFlags;
109493 pWInfo->savedNQueryLoop = pParse->nQueryLoop;
109494 pMaskSet = (WhereMaskSet*)&sWBI.pWC[1];
109495 sWBI.aLevel = pWInfo->a;
 
 
 
 
 
 
109496
109497 /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
109498 ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
109499 if( OptimizationDisabled(db, SQLITE_DistinctOpt) ) pDistinct = 0;
109500
109501 /* Split the WHERE clause into separate subexpressions where each
109502 ** subexpression is separated by an AND operator.
109503 */
109504 initMaskSet(pMaskSet);
109505 whereClauseInit(sWBI.pWC, pParse, pMaskSet, wctrlFlags);
109506 sqlite3ExprCodeConstants(pParse, pWhere);
109507 whereSplit(sWBI.pWC, pWhere, TK_AND); /* IMP: R-15842-53296 */
109508
109509 /* Special case: a WHERE clause that is constant. Evaluate the
109510 ** expression and either jump over all of the code or fall thru.
109511 */
109512 if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
109513 sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
109514 pWhere = 0;
109515 }
 
 
 
 
 
 
 
109516
109517 /* Assign a bit from the bitmask to every term in the FROM clause.
109518 **
109519 ** When assigning bitmask values to FROM clause cursors, it must be
109520 ** the case that if X is the bitmask for the N-th FROM clause term then
@@ -109547,337 +109974,153 @@
109547 /* Analyze all of the subexpressions. Note that exprAnalyze() might
109548 ** add new virtual terms onto the end of the WHERE clause. We do not
109549 ** want to analyze these virtual terms, so start analyzing at the end
109550 ** and work forward so that the added virtual terms are never processed.
109551 */
109552 exprAnalyzeAll(pTabList, sWBI.pWC);
109553 if( db->mallocFailed ){
109554 goto whereBeginError;
109555 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109556
109557 /* Check if the DISTINCT qualifier, if there is one, is redundant.
109558 ** If it is, then set pDistinct to NULL and WhereInfo.eDistinct to
109559 ** WHERE_DISTINCT_UNIQUE to tell the caller to ignore the DISTINCT.
109560 */
109561 if( pDistinct && isDistinctRedundant(pParse, pTabList, sWBI.pWC, pDistinct) ){
109562 pDistinct = 0;
109563 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
109564 }
109565
109566 /* Chose the best index to use for each table in the FROM clause.
109567 **
109568 ** This loop fills in the following fields:
109569 **
109570 ** pWInfo->a[].pIdx The index to use for this level of the loop.
109571 ** pWInfo->a[].wsFlags WHERE_xxx flags associated with pIdx
109572 ** pWInfo->a[].nEq The number of == and IN constraints
109573 ** pWInfo->a[].iFrom Which term of the FROM clause is being coded
109574 ** pWInfo->a[].iTabCur The VDBE cursor for the database table
109575 ** pWInfo->a[].iIdxCur The VDBE cursor for the index
109576 ** pWInfo->a[].pTerm When wsFlags==WO_OR, the OR-clause term
109577 **
109578 ** This loop also figures out the nesting order of tables in the FROM
109579 ** clause.
109580 */
109581 sWBI.notValid = ~(Bitmask)0;
109582 sWBI.pOrderBy = pOrderBy;
109583 sWBI.n = nTabList;
109584 sWBI.pDistinct = pDistinct;
109585 andFlags = ~0;
109586 WHERETRACE(("*** Optimizer Start ***\n"));
109587 for(sWBI.i=iFrom=0, pLevel=pWInfo->a; sWBI.i<nTabList; sWBI.i++, pLevel++){
109588 WhereCost bestPlan; /* Most efficient plan seen so far */
109589 Index *pIdx; /* Index for FROM table at pTabItem */
109590 int j; /* For looping over FROM tables */
109591 int bestJ = -1; /* The value of j */
109592 Bitmask m; /* Bitmask value for j or bestJ */
109593 int isOptimal; /* Iterator for optimal/non-optimal search */
109594 int ckOptimal; /* Do the optimal scan check */
109595 int nUnconstrained; /* Number tables without INDEXED BY */
109596 Bitmask notIndexed; /* Mask of tables that cannot use an index */
109597
109598 memset(&bestPlan, 0, sizeof(bestPlan));
109599 bestPlan.rCost = SQLITE_BIG_DBL;
109600 WHERETRACE(("*** Begin search for loop %d ***\n", sWBI.i));
109601
109602 /* Loop through the remaining entries in the FROM clause to find the
109603 ** next nested loop. The loop tests all FROM clause entries
109604 ** either once or twice.
109605 **
109606 ** The first test is always performed if there are two or more entries
109607 ** remaining and never performed if there is only one FROM clause entry
109608 ** to choose from. The first test looks for an "optimal" scan. In
109609 ** this context an optimal scan is one that uses the same strategy
109610 ** for the given FROM clause entry as would be selected if the entry
109611 ** were used as the innermost nested loop. In other words, a table
109612 ** is chosen such that the cost of running that table cannot be reduced
109613 ** by waiting for other tables to run first. This "optimal" test works
109614 ** by first assuming that the FROM clause is on the inner loop and finding
109615 ** its query plan, then checking to see if that query plan uses any
109616 ** other FROM clause terms that are sWBI.notValid. If no notValid terms
109617 ** are used then the "optimal" query plan works.
109618 **
109619 ** Note that the WhereCost.nRow parameter for an optimal scan might
109620 ** not be as small as it would be if the table really were the innermost
109621 ** join. The nRow value can be reduced by WHERE clause constraints
109622 ** that do not use indices. But this nRow reduction only happens if the
109623 ** table really is the innermost join.
109624 **
109625 ** The second loop iteration is only performed if no optimal scan
109626 ** strategies were found by the first iteration. This second iteration
109627 ** is used to search for the lowest cost scan overall.
109628 **
109629 ** Without the optimal scan step (the first iteration) a suboptimal
109630 ** plan might be chosen for queries like this:
109631 **
109632 ** CREATE TABLE t1(a, b);
109633 ** CREATE TABLE t2(c, d);
109634 ** SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
109635 **
109636 ** The best strategy is to iterate through table t1 first. However it
109637 ** is not possible to determine this with a simple greedy algorithm.
109638 ** Since the cost of a linear scan through table t2 is the same
109639 ** as the cost of a linear scan through table t1, a simple greedy
109640 ** algorithm may choose to use t2 for the outer loop, which is a much
109641 ** costlier approach.
109642 */
109643 nUnconstrained = 0;
109644 notIndexed = 0;
109645
109646 /* The optimal scan check only occurs if there are two or more tables
109647 ** available to be reordered */
109648 if( iFrom==nTabList-1 ){
109649 ckOptimal = 0; /* Common case of just one table in the FROM clause */
109650 }else{
109651 ckOptimal = -1;
109652 for(j=iFrom, sWBI.pSrc=&pTabList->a[j]; j<nTabList; j++, sWBI.pSrc++){
109653 m = getMask(pMaskSet, sWBI.pSrc->iCursor);
109654 if( (m & sWBI.notValid)==0 ){
109655 if( j==iFrom ) iFrom++;
109656 continue;
109657 }
109658 if( j>iFrom && (sWBI.pSrc->jointype & (JT_LEFT|JT_CROSS))!=0 ) break;
109659 if( ++ckOptimal ) break;
109660 if( (sWBI.pSrc->jointype & JT_LEFT)!=0 ) break;
109661 }
109662 }
109663 assert( ckOptimal==0 || ckOptimal==1 );
109664
109665 for(isOptimal=ckOptimal; isOptimal>=0 && bestJ<0; isOptimal--){
109666 for(j=iFrom, sWBI.pSrc=&pTabList->a[j]; j<nTabList; j++, sWBI.pSrc++){
109667 if( j>iFrom && (sWBI.pSrc->jointype & (JT_LEFT|JT_CROSS))!=0 ){
109668 /* This break and one like it in the ckOptimal computation loop
109669 ** above prevent table reordering across LEFT and CROSS JOINs.
109670 ** The LEFT JOIN case is necessary for correctness. The prohibition
109671 ** against reordering across a CROSS JOIN is an SQLite feature that
109672 ** allows the developer to control table reordering */
109673 break;
109674 }
109675 m = getMask(pMaskSet, sWBI.pSrc->iCursor);
109676 if( (m & sWBI.notValid)==0 ){
109677 assert( j>iFrom );
109678 continue;
109679 }
109680 sWBI.notReady = (isOptimal ? m : sWBI.notValid);
109681 if( sWBI.pSrc->pIndex==0 ) nUnconstrained++;
109682
109683 WHERETRACE((" === trying table %d (%s) with isOptimal=%d ===\n",
109684 j, sWBI.pSrc->pTab->zName, isOptimal));
109685 assert( sWBI.pSrc->pTab );
109686 #ifndef SQLITE_OMIT_VIRTUALTABLE
109687 if( IsVirtual(sWBI.pSrc->pTab) ){
109688 sWBI.ppIdxInfo = &pWInfo->a[j].pIdxInfo;
109689 bestVirtualIndex(&sWBI);
109690 }else
109691 #endif
109692 {
109693 bestBtreeIndex(&sWBI);
109694 }
109695 assert( isOptimal || (sWBI.cost.used&sWBI.notValid)==0 );
109696
109697 /* If an INDEXED BY clause is present, then the plan must use that
109698 ** index if it uses any index at all */
109699 assert( sWBI.pSrc->pIndex==0
109700 || (sWBI.cost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
109701 || sWBI.cost.plan.u.pIdx==sWBI.pSrc->pIndex );
109702
109703 if( isOptimal && (sWBI.cost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
109704 notIndexed |= m;
109705 }
109706 if( isOptimal ){
109707 pWInfo->a[j].rOptCost = sWBI.cost.rCost;
109708 }else if( ckOptimal ){
109709 /* If two or more tables have nearly the same outer loop cost, but
109710 ** very different inner loop (optimal) cost, we want to choose
109711 ** for the outer loop that table which benefits the least from
109712 ** being in the inner loop. The following code scales the
109713 ** outer loop cost estimate to accomplish that. */
109714 WHERETRACE((" scaling cost from %.1f to %.1f\n",
109715 sWBI.cost.rCost,
109716 sWBI.cost.rCost/pWInfo->a[j].rOptCost));
109717 sWBI.cost.rCost /= pWInfo->a[j].rOptCost;
109718 }
109719
109720 /* Conditions under which this table becomes the best so far:
109721 **
109722 ** (1) The table must not depend on other tables that have not
109723 ** yet run. (In other words, it must not depend on tables
109724 ** in inner loops.)
109725 **
109726 ** (2) (This rule was removed on 2012-11-09. The scaling of the
109727 ** cost using the optimal scan cost made this rule obsolete.)
109728 **
109729 ** (3) All tables have an INDEXED BY clause or this table lacks an
109730 ** INDEXED BY clause or this table uses the specific
109731 ** index specified by its INDEXED BY clause. This rule ensures
109732 ** that a best-so-far is always selected even if an impossible
109733 ** combination of INDEXED BY clauses are given. The error
109734 ** will be detected and relayed back to the application later.
109735 ** The NEVER() comes about because rule (2) above prevents
109736 ** An indexable full-table-scan from reaching rule (3).
109737 **
109738 ** (4) The plan cost must be lower than prior plans, where "cost"
109739 ** is defined by the compareCost() function above.
109740 */
109741 if( (sWBI.cost.used&sWBI.notValid)==0 /* (1) */
109742 && (nUnconstrained==0 || sWBI.pSrc->pIndex==0 /* (3) */
109743 || NEVER((sWBI.cost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0))
109744 && (bestJ<0 || compareCost(&sWBI.cost, &bestPlan)) /* (4) */
109745 ){
109746 WHERETRACE((" === table %d (%s) is best so far\n"
109747 " cost=%.1f, nRow=%.1f, nOBSat=%d, wsFlags=%08x\n",
109748 j, sWBI.pSrc->pTab->zName,
109749 sWBI.cost.rCost, sWBI.cost.plan.nRow,
109750 sWBI.cost.plan.nOBSat, sWBI.cost.plan.wsFlags));
109751 bestPlan = sWBI.cost;
109752 bestJ = j;
109753 }
109754
109755 /* In a join like "w JOIN x LEFT JOIN y JOIN z" make sure that
109756 ** table y (and not table z) is always the next inner loop inside
109757 ** of table x. */
109758 if( (sWBI.pSrc->jointype & JT_LEFT)!=0 ) break;
109759 }
109760 }
109761 assert( bestJ>=0 );
109762 assert( sWBI.notValid & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
109763 assert( bestJ==iFrom || (pTabList->a[iFrom].jointype & JT_LEFT)==0 );
109764 testcase( bestJ>iFrom && (pTabList->a[iFrom].jointype & JT_CROSS)!=0 );
109765 testcase( bestJ>iFrom && bestJ<nTabList-1
109766 && (pTabList->a[bestJ+1].jointype & JT_LEFT)!=0 );
109767 WHERETRACE(("*** Optimizer selects table %d (%s) for loop %d with:\n"
109768 " cost=%.1f, nRow=%.1f, nOBSat=%d, wsFlags=0x%08x\n",
109769 bestJ, pTabList->a[bestJ].pTab->zName,
109770 pLevel-pWInfo->a, bestPlan.rCost, bestPlan.plan.nRow,
109771 bestPlan.plan.nOBSat, bestPlan.plan.wsFlags));
109772 if( (bestPlan.plan.wsFlags & WHERE_DISTINCT)!=0 ){
109773 assert( pWInfo->eDistinct==0 );
109774 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
109775 }
109776 andFlags &= bestPlan.plan.wsFlags;
109777 pLevel->plan = bestPlan.plan;
109778 pLevel->iTabCur = pTabList->a[bestJ].iCursor;
109779 testcase( bestPlan.plan.wsFlags & WHERE_INDEXED );
109780 testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX );
109781 if( bestPlan.plan.wsFlags & (WHERE_INDEXED|WHERE_TEMP_INDEX) ){
109782 if( (wctrlFlags & WHERE_ONETABLE_ONLY)
109783 && (bestPlan.plan.wsFlags & WHERE_TEMP_INDEX)==0
109784 ){
109785 pLevel->iIdxCur = iIdxCur;
109786 }else{
109787 pLevel->iIdxCur = pParse->nTab++;
109788 }
109789 }else{
109790 pLevel->iIdxCur = -1;
109791 }
109792 sWBI.notValid &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
109793 pLevel->iFrom = (u8)bestJ;
109794 if( bestPlan.plan.nRow>=(double)1 ){
109795 pParse->nQueryLoop *= bestPlan.plan.nRow;
109796 }
109797
109798 /* Check that if the table scanned by this loop iteration had an
109799 ** INDEXED BY clause attached to it, that the named index is being
109800 ** used for the scan. If not, then query compilation has failed.
109801 ** Return an error.
109802 */
109803 pIdx = pTabList->a[bestJ].pIndex;
109804 if( pIdx ){
109805 if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
109806 sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
109807 goto whereBeginError;
109808 }else{
109809 /* If an INDEXED BY clause is used, the bestIndex() function is
109810 ** guaranteed to find the index specified in the INDEXED BY clause
109811 ** if it find an index at all. */
109812 assert( bestPlan.plan.u.pIdx==pIdx );
109813 }
109814 }
109815 }
109816 WHERETRACE(("*** Optimizer Finished ***\n"));
109817 if( pParse->nErr || db->mallocFailed ){
109818 goto whereBeginError;
109819 }
109820 if( nTabList ){
109821 pLevel--;
109822 pWInfo->nOBSat = pLevel->plan.nOBSat;
109823 }else{
109824 pWInfo->nOBSat = 0;
109825 }
109826
109827 /* If the total query only selects a single row, then the ORDER BY
109828 ** clause is irrelevant.
109829 */
109830 if( (andFlags & WHERE_UNIQUE)!=0 && pOrderBy ){
109831 assert( nTabList==0 || (pLevel->plan.wsFlags & WHERE_ALL_UNIQUE)!=0 );
109832 pWInfo->nOBSat = pOrderBy->nExpr;
109833 }
109834
109835 /* If the caller is an UPDATE or DELETE statement that is requesting
109836 ** to use a one-pass algorithm, determine if this is appropriate.
109837 ** The one-pass algorithm only works if the WHERE clause constraints
109838 ** the statement to update a single row.
109839 */
109840 assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
109841 if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
 
109842 pWInfo->okOnePass = 1;
109843 pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
109844 }
109845
109846 /* Open all tables in the pTabList and any indices selected for
109847 ** searching those tables.
109848 */
109849 sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
109850 notReady = ~(Bitmask)0;
109851 pWInfo->nRowOut = (double)1;
109852 for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
109853 Table *pTab; /* Table to open */
109854 int iDb; /* Index of database containing table/index */
109855 struct SrcList_item *pTabItem;
 
109856
109857 pTabItem = &pTabList->a[pLevel->iFrom];
109858 pTab = pTabItem->pTab;
109859 pWInfo->nRowOut *= pLevel->plan.nRow;
109860 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
 
109861 if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
109862 /* Do nothing */
109863 }else
109864 #ifndef SQLITE_OMIT_VIRTUALTABLE
109865 if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
109866 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
109867 int iCur = pTabItem->iCursor;
109868 sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
109869 }else if( IsVirtual(pTab) ){
109870 /* noop */
109871 }else
109872 #endif
109873 if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
109874 && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
109875 int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
109876 sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
109877 testcase( pTab->nCol==BMS-1 );
109878 testcase( pTab->nCol==BMS );
109879 if( !pWInfo->okOnePass && pTab->nCol<BMS ){
109880 Bitmask b = pTabItem->colUsed;
109881 int n = 0;
109882 for(; b; b=b>>1, n++){}
109883 sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
@@ -109886,26 +110129,27 @@
109886 }
109887 }else{
109888 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
109889 }
109890 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
109891 if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
109892 constructAutomaticIndex(pParse, sWBI.pWC, pTabItem, notReady, pLevel);
109893 }else
109894 #endif
109895 if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
109896 Index *pIx = pLevel->plan.u.pIdx;
109897 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
109898 int iIndexCur = pLevel->iIdxCur;
 
109899 assert( pIx->pSchema==pTab->pSchema );
109900 assert( iIndexCur>=0 );
109901 sqlite3VdbeAddOp4(v, OP_OpenRead, iIndexCur, pIx->tnum, iDb,
109902 (char*)pKey, P4_KEYINFO_HANDOFF);
109903 VdbeComment((v, "%s", pIx->zName));
109904 }
109905 sqlite3CodeVerifySchema(pParse, iDb);
109906 notReady &= ~getMask(sWBI.pWC->pMaskSet, pTabItem->iCursor);
109907 }
109908 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
109909 if( db->mallocFailed ) goto whereBeginError;
109910
109911 /* Generate the code to do the search. Each iteration of the for
@@ -109914,70 +110158,15 @@
109914 */
109915 notReady = ~(Bitmask)0;
109916 for(ii=0; ii<nTabList; ii++){
109917 pLevel = &pWInfo->a[ii];
109918 explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
109919 notReady = codeOneLoopStart(pWInfo, ii, wctrlFlags, notReady);
109920 pWInfo->iContinue = pLevel->addrCont;
109921 }
109922
109923 #ifdef SQLITE_TEST /* For testing and debugging use only */
109924 /* Record in the query plan information about the current table
109925 ** and the index used to access it (if any). If the table itself
109926 ** is not used, its name is just '{}'. If no index is used
109927 ** the index is listed as "{}". If the primary key is used the
109928 ** index name is '*'.
109929 */
109930 for(ii=0; ii<nTabList; ii++){
109931 char *z;
109932 int n;
109933 int w;
109934 struct SrcList_item *pTabItem;
109935
109936 pLevel = &pWInfo->a[ii];
109937 w = pLevel->plan.wsFlags;
109938 pTabItem = &pTabList->a[pLevel->iFrom];
109939 z = pTabItem->zAlias;
109940 if( z==0 ) z = pTabItem->pTab->zName;
109941 n = sqlite3Strlen30(z);
109942 if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
109943 if( (w & WHERE_IDX_ONLY)!=0 && (w & WHERE_COVER_SCAN)==0 ){
109944 memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
109945 nQPlan += 2;
109946 }else{
109947 memcpy(&sqlite3_query_plan[nQPlan], z, n);
109948 nQPlan += n;
109949 }
109950 sqlite3_query_plan[nQPlan++] = ' ';
109951 }
109952 testcase( w & WHERE_ROWID_EQ );
109953 testcase( w & WHERE_ROWID_RANGE );
109954 if( w & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
109955 memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
109956 nQPlan += 2;
109957 }else if( (w & WHERE_INDEXED)!=0 && (w & WHERE_COVER_SCAN)==0 ){
109958 n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
109959 if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
109960 memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
109961 nQPlan += n;
109962 sqlite3_query_plan[nQPlan++] = ' ';
109963 }
109964 }else{
109965 memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
109966 nQPlan += 3;
109967 }
109968 }
109969 while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
109970 sqlite3_query_plan[--nQPlan] = 0;
109971 }
109972 sqlite3_query_plan[nQPlan] = 0;
109973 nQPlan = 0;
109974 #endif /* SQLITE_TEST // Testing and debugging use only */
109975
109976 /* Record the continuation address in the WhereInfo structure. Then
109977 ** clean up and return.
109978 */
109979 return pWInfo;
109980
109981 /* Jump here if malloc fails */
109982 whereBeginError:
109983 if( pWInfo ){
@@ -109994,24 +110183,26 @@
109994 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
109995 Parse *pParse = pWInfo->pParse;
109996 Vdbe *v = pParse->pVdbe;
109997 int i;
109998 WhereLevel *pLevel;
 
109999 SrcList *pTabList = pWInfo->pTabList;
110000 sqlite3 *db = pParse->db;
110001
110002 /* Generate loop termination code.
110003 */
110004 sqlite3ExprCacheClear(pParse);
110005 for(i=pWInfo->nLevel-1; i>=0; i--){
110006 pLevel = &pWInfo->a[i];
 
110007 sqlite3VdbeResolveLabel(v, pLevel->addrCont);
110008 if( pLevel->op!=OP_Noop ){
110009 sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
110010 sqlite3VdbeChangeP5(v, pLevel->p5);
110011 }
110012 if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
110013 struct InLoop *pIn;
110014 int j;
110015 sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
110016 for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
110017 sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
@@ -110022,16 +110213,16 @@
110022 }
110023 sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
110024 if( pLevel->iLeftJoin ){
110025 int addr;
110026 addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
110027 assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
110028 || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
110029 if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
110030 sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
110031 }
110032 if( pLevel->iIdxCur>=0 ){
110033 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
110034 }
110035 if( pLevel->op==OP_Return ){
110036 sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
110037 }else{
@@ -110052,42 +110243,41 @@
110052 for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
110053 Index *pIdx = 0;
110054 struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
110055 Table *pTab = pTabItem->pTab;
110056 assert( pTab!=0 );
 
110057 if( (pTab->tabFlags & TF_Ephemeral)==0
110058 && pTab->pSelect==0
110059 && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
110060 ){
110061 int ws = pLevel->plan.wsFlags;
110062 if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
110063 sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
110064 }
110065 if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){
110066 sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
110067 }
110068 }
110069
110070 /* If this scan uses an index, make code substitutions to read data
110071 ** from the index in preference to the table. Sometimes, this means
110072 ** the table need never be read from. This is a performance boost,
110073 ** as the vdbe level waits until the table is read before actually
110074 ** seeking the table cursor to the record corresponding to the current
110075 ** position in the index.
110076 **
110077 ** Calls to the code generator in between sqlite3WhereBegin and
110078 ** sqlite3WhereEnd will have created code that references the table
110079 ** directly. This loop scans all that code looking for opcodes
110080 ** that reference the table and converts them into opcodes that
110081 ** reference the index.
110082 */
110083 if( pLevel->plan.wsFlags & WHERE_INDEXED ){
110084 pIdx = pLevel->plan.u.pIdx;
110085 }else if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
110086 pIdx = pLevel->u.pCovidx;
110087 }
110088 if( pIdx && !db->mallocFailed){
110089 int k, j, last;
110090 VdbeOp *pOp;
110091
110092 pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
110093 last = sqlite3VdbeCurrentAddr(v);
@@ -110099,12 +110289,11 @@
110099 pOp->p2 = j;
110100 pOp->p1 = pLevel->iIdxCur;
110101 break;
110102 }
110103 }
110104 assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
110105 || j<pIdx->nColumn );
110106 }else if( pOp->opcode==OP_Rowid ){
110107 pOp->p1 = pLevel->iIdxCur;
110108 pOp->opcode = OP_IdxRowid;
110109 }
110110 }
@@ -115480,11 +115669,11 @@
115480 }
115481
115482 /*
115483 ** Another built-in collating sequence: NOCASE.
115484 **
115485 ** This collating sequence is intended to be used for "case independant
115486 ** comparison". SQLite's knowledge of upper and lower case equivalents
115487 ** extends only to the 26 characters used in the English language.
115488 **
115489 ** At the moment there is only a UTF-8 implementation.
115490 */
@@ -115627,16 +115816,10 @@
115627 "statements or unfinished backups");
115628 sqlite3_mutex_leave(db->mutex);
115629 return SQLITE_BUSY;
115630 }
115631
115632 /* If a transaction is open, roll it back. This also ensures that if
115633 ** any database schemas have been modified by the current transaction
115634 ** they are reset. And that the required b-tree mutex is held to make
115635 ** the the pager rollback and schema reset an atomic operation. */
115636 sqlite3RollbackAll(db, SQLITE_OK);
115637
115638 #ifdef SQLITE_ENABLE_SQLLOG
115639 if( sqlite3GlobalConfig.xSqllog ){
115640 /* Closing the handle. Fourth parameter is passed the value 2. */
115641 sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
115642 }
@@ -115686,10 +115869,16 @@
115686 /* If we reach this point, it means that the database connection has
115687 ** closed all sqlite3_stmt and sqlite3_backup objects and has been
115688 ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
115689 ** go ahead and free all resources.
115690 */
 
 
 
 
 
 
115691
115692 /* Free any outstanding Savepoint structures. */
115693 sqlite3CloseSavepoints(db);
115694
115695 /* Close all database connections */
@@ -115787,19 +115976,26 @@
115787 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
115788 int i;
115789 int inTrans = 0;
115790 assert( sqlite3_mutex_held(db->mutex) );
115791 sqlite3BeginBenignMalloc();
 
 
 
 
 
 
 
115792 sqlite3BtreeEnterAll(db);
 
115793 for(i=0; i<db->nDb; i++){
115794 Btree *p = db->aDb[i].pBt;
115795 if( p ){
115796 if( sqlite3BtreeIsInTrans(p) ){
115797 inTrans = 1;
115798 }
115799 sqlite3BtreeRollback(p, tripCode);
115800 db->aDb[i].inTrans = 0;
115801 }
115802 }
115803 sqlite3VtabRollback(db);
115804 sqlite3EndBenignMalloc();
115805
@@ -117562,12 +117758,10 @@
117562 /*
117563 ** Test to see whether or not the database connection is in autocommit
117564 ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
117565 ** by default. Autocommit is disabled by a BEGIN statement and reenabled
117566 ** by the next COMMIT or ROLLBACK.
117567 **
117568 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
117569 */
117570 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
117571 return db->autoCommit;
117572 }
117573
@@ -119051,10 +119245,22 @@
119051
119052 #endif /* _FTS3_HASH_H_ */
119053
119054 /************** End of fts3_hash.h *******************************************/
119055 /************** Continuing where we left off in fts3Int.h ********************/
 
 
 
 
 
 
 
 
 
 
 
 
119056
119057 /*
119058 ** This constant controls how often segments are merged. Once there are
119059 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
119060 ** segment of level N+1.
@@ -120709,11 +120915,11 @@
120709 /* By default use a full table scan. This is an expensive option,
120710 ** so search through the constraints to see if a more efficient
120711 ** strategy is possible.
120712 */
120713 pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
120714 pInfo->estimatedCost = 500000;
120715 for(i=0; i<pInfo->nConstraint; i++){
120716 struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
120717 if( pCons->usable==0 ) continue;
120718
120719 /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
@@ -122270,15 +122476,11 @@
122270 );
122271 if( rc!=SQLITE_OK ){
122272 return rc;
122273 }
122274
122275 rc = sqlite3Fts3ReadLock(p);
122276 if( rc!=SQLITE_OK ) return rc;
122277
122278 rc = fts3EvalStart(pCsr);
122279
122280 sqlite3Fts3SegmentsClose(p);
122281 if( rc!=SQLITE_OK ) return rc;
122282 pCsr->pNextId = pCsr->aDoclist;
122283 pCsr->iPrevId = 0;
122284 }
@@ -126129,30 +126331,30 @@
126129 int iDefaultCol, /* Default column to query */
126130 const char *z, int n, /* Text of MATCH query */
126131 Fts3Expr **ppExpr, /* OUT: Parsed query structure */
126132 char **pzErr /* OUT: Error message (sqlite3_malloc) */
126133 ){
126134 static const int MAX_EXPR_DEPTH = 12;
126135 int rc = fts3ExprParseUnbalanced(
126136 pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
126137 );
126138
126139 /* Rebalance the expression. And check that its depth does not exceed
126140 ** MAX_EXPR_DEPTH. */
126141 if( rc==SQLITE_OK && *ppExpr ){
126142 rc = fts3ExprBalance(ppExpr, MAX_EXPR_DEPTH);
126143 if( rc==SQLITE_OK ){
126144 rc = fts3ExprCheckDepth(*ppExpr, MAX_EXPR_DEPTH);
126145 }
126146 }
126147
126148 if( rc!=SQLITE_OK ){
126149 sqlite3Fts3ExprFree(*ppExpr);
126150 *ppExpr = 0;
126151 if( rc==SQLITE_TOOBIG ){
126152 *pzErr = sqlite3_mprintf(
126153 "FTS expression tree is too large (maximum depth %d)", MAX_EXPR_DEPTH
 
126154 );
126155 rc = SQLITE_ERROR;
126156 }else if( rc==SQLITE_ERROR ){
126157 *pzErr = sqlite3_mprintf("malformed MATCH expression: [%s]", z);
126158 }
@@ -129110,41 +129312,34 @@
129110 *pRC = rc;
129111 }
129112
129113
129114 /*
129115 ** This function ensures that the caller has obtained a shared-cache
129116 ** table-lock on the %_content table. This is required before reading
129117 ** data from the fts3 table. If this lock is not acquired first, then
129118 ** the caller may end up holding read-locks on the %_segments and %_segdir
129119 ** tables, but no read-lock on the %_content table. If this happens
129120 ** a second connection will be able to write to the fts3 table, but
129121 ** attempting to commit those writes might return SQLITE_LOCKED or
129122 ** SQLITE_LOCKED_SHAREDCACHE (because the commit attempts to obtain
129123 ** write-locks on the %_segments and %_segdir ** tables).
129124 **
129125 ** We try to avoid this because if FTS3 returns any error when committing
129126 ** a transaction, the whole transaction will be rolled back. And this is
129127 ** not what users expect when they get SQLITE_LOCKED_SHAREDCACHE. It can
129128 ** still happen if the user reads data directly from the %_segments or
129129 ** %_segdir tables instead of going through FTS3 though.
129130 **
129131 ** This reasoning does not apply to a content=xxx table.
129132 */
129133 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *p){
129134 int rc; /* Return code */
129135 sqlite3_stmt *pStmt; /* Statement used to obtain lock */
129136
129137 if( p->zContentTbl==0 ){
129138 rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pStmt, 0);
129139 if( rc==SQLITE_OK ){
129140 sqlite3_bind_null(pStmt, 1);
129141 sqlite3_step(pStmt);
129142 rc = sqlite3_reset(pStmt);
129143 }
129144 }else{
129145 rc = SQLITE_OK;
129146 }
129147
129148 return rc;
129149 }
129150
@@ -133918,10 +134113,13 @@
133918 goto update_out;
133919 }
133920 aSzIns = &aSzDel[p->nColumn+1];
133921 memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
133922
 
 
 
133923 /* If this is an INSERT operation, or an UPDATE that modifies the rowid
133924 ** value, then this operation requires constraint handling.
133925 **
133926 ** If the on-conflict mode is REPLACE, this means that the existing row
133927 ** should be deleted from the database before inserting the new row. Or,
@@ -136051,32 +136249,31 @@
136051 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
136052 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
136053 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
136054 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
136055 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
136056 0x037FFC02, 0x03E3FC01, 0x03EC7801, 0x03ECA401, 0x03EEC810,
136057 0x03F4F802, 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023,
136058 0x03F95013, 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807,
136059 0x03FCEC06, 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405,
136060 0x04040003, 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E,
136061 0x040E7C01, 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01,
136062 0x04280403, 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01,
136063 0x04294009, 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016,
136064 0x04420003, 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004,
136065 0x04460003, 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004,
136066 0x05BD442E, 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5,
136067 0x07480046, 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01,
136068 0x075C5401, 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401,
136069 0x075EA401, 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064,
136070 0x07C2800F, 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F,
136071 0x07C4C03C, 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009,
136072 0x07C94002, 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014,
136073 0x07CE8025, 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001,
136074 0x07D108B6, 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018,
136075 0x07D7EC46, 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401,
136076 0x38008060, 0x380400F0, 0x3C000001, 0x3FFFF401, 0x40000001,
136077 0x43FFF401,
136078 };
136079 static const unsigned int aAscii[4] = {
136080 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
136081 };
136082
@@ -139705,11 +139902,11 @@
139705 ** operator) using the ICU uregex_XX() APIs.
139706 **
139707 ** * Implementations of the SQL scalar upper() and lower() functions
139708 ** for case mapping.
139709 **
139710 ** * Integration of ICU and SQLite collation seqences.
139711 **
139712 ** * An implementation of the LIKE operator that uses ICU to
139713 ** provide case-independent matching.
139714 */
139715
139716
--- src/sqlite3.c
+++ src/sqlite3.c
@@ -352,11 +352,11 @@
352
353 /*
354 ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
355 ** 0 means mutexes are permanently disable and the library is never
356 ** threadsafe. 1 means the library is serialized which is the highest
357 ** level of threadsafety. 2 means the library is multithreaded - multiple
358 ** threads can use SQLite as long as no two threads try to use the same
359 ** database connection at the same time.
360 **
361 ** Older versions of SQLite used an optional THREADSAFE macro.
362 ** We support that for legacy.
@@ -431,24 +431,16 @@
431 # define SQLITE_MALLOC_SOFT_LIMIT 1024
432 #endif
433
434 /*
435 ** We need to define _XOPEN_SOURCE as follows in order to enable
436 ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
437 ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
438 ** it.
 
 
 
 
 
 
 
439 */
440 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
441 # define _XOPEN_SOURCE 600
 
442 #endif
443
444 /*
445 ** The TCL headers are only needed when compiling the TCL bindings.
446 */
@@ -678,11 +670,11 @@
670 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
671 ** [sqlite_version()] and [sqlite_source_id()].
672 */
673 #define SQLITE_VERSION "3.7.17"
674 #define SQLITE_VERSION_NUMBER 3007017
675 #define SQLITE_SOURCE_ID "2013-06-19 23:48:35 bf5764067ab848e19e5971cbdf892c633495e325"
676
677 /*
678 ** CAPI3REF: Run-Time Library Version Numbers
679 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
680 **
@@ -5087,10 +5079,15 @@
5079 */
5080 SQLITE_API int sqlite3_key(
5081 sqlite3 *db, /* Database to be rekeyed */
5082 const void *pKey, int nKey /* The key */
5083 );
5084 SQLITE_API int sqlite3_key_v2(
5085 sqlite3 *db, /* Database to be rekeyed */
5086 const char *zDbName, /* Name of the database */
5087 const void *pKey, int nKey /* The key */
5088 );
5089
5090 /*
5091 ** Change the key on an open database. If the current database is not
5092 ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
5093 ** database is decrypted.
@@ -5100,10 +5097,15 @@
5097 */
5098 SQLITE_API int sqlite3_rekey(
5099 sqlite3 *db, /* Database to be rekeyed */
5100 const void *pKey, int nKey /* The new key */
5101 );
5102 SQLITE_API int sqlite3_rekey_v2(
5103 sqlite3 *db, /* Database to be rekeyed */
5104 const char *zDbName, /* Name of the database */
5105 const void *pKey, int nKey /* The new key */
5106 );
5107
5108 /*
5109 ** Specify the activation key for a SEE database. Unless
5110 ** activated, none of the SEE routines will work.
5111 */
@@ -8151,10 +8153,16 @@
8153 */
8154 #ifndef offsetof
8155 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
8156 #endif
8157
8158 /*
8159 ** Macros to compute minimum and maximum of two numbers.
8160 */
8161 #define MIN(A,B) ((A)<(B)?(A):(B))
8162 #define MAX(A,B) ((A)>(B)?(A):(B))
8163
8164 /*
8165 ** Check to see if this machine uses EBCDIC. (Yes, believe it or
8166 ** not, there are still machines out there that use EBCDIC.)
8167 */
8168 #if 'A' == '\301'
@@ -8476,13 +8484,11 @@
8484 typedef struct TriggerStep TriggerStep;
8485 typedef struct UnpackedRecord UnpackedRecord;
8486 typedef struct VTable VTable;
8487 typedef struct VtabCtx VtabCtx;
8488 typedef struct Walker Walker;
 
8489 typedef struct WhereInfo WhereInfo;
 
8490
8491 /*
8492 ** Defer sourcing vdbe.h and btree.h until after the "u8" and
8493 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
8494 ** pointer types (i.e. FuncDef) defined above.
@@ -9915,11 +9921,10 @@
9921 ** databases may be attached.
9922 */
9923 struct Db {
9924 char *zName; /* Name of this database */
9925 Btree *pBt; /* The B*Tree structure for this database file */
 
9926 u8 safety_level; /* How aggressive at syncing data to disk */
9927 Schema *pSchema; /* Pointer to database schema (possibly shared) */
9928 };
9929
9930 /*
@@ -10713,10 +10718,11 @@
10718 int tnum; /* DB Page containing root of this index */
10719 u16 nColumn; /* Number of columns in table used by this index */
10720 u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
10721 unsigned autoIndex:2; /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
10722 unsigned bUnordered:1; /* Use this index for == or IN queries only */
10723 unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */
10724 #ifdef SQLITE_ENABLE_STAT3
10725 int nSample; /* Number of elements in aSample[] */
10726 tRowcnt avgEq; /* Average nEq value for key values not in aSample */
10727 IndexSample *aSample; /* Samples of the left-most key */
10728 #endif
@@ -11058,10 +11064,15 @@
11064 /*
11065 ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
11066 */
11067 #define BMS ((int)(sizeof(Bitmask)*8))
11068
11069 /*
11070 ** A bit in a Bitmask
11071 */
11072 #define MASKBIT(n) (((Bitmask)1)<<(n))
11073
11074 /*
11075 ** The following structure describes the FROM clause of a SELECT statement.
11076 ** Each table or subquery in the FROM clause is a separate element of
11077 ** the SrcList.a[] array.
11078 **
@@ -11078,12 +11089,12 @@
11089 **
11090 ** In the colUsed field, the high-order bit (bit 63) is set if the table
11091 ** contains more than 63 columns and the 64-th or later column is used.
11092 */
11093 struct SrcList {
11094 u8 nSrc; /* Number of tables or subqueries in the FROM clause */
11095 u8 nAlloc; /* Number of entries allocated in a[] below */
11096 struct SrcList_item {
11097 Schema *pSchema; /* Schema to which this item is fixed */
11098 char *zDatabase; /* Name of database holding this table */
11099 char *zName; /* Name of the table */
11100 char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
@@ -11117,83 +11128,10 @@
11128 #define JT_RIGHT 0x0010 /* Right outer join */
11129 #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
11130 #define JT_ERROR 0x0040 /* unknown or unsupported join type */
11131
11132
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11133 /*
11134 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
11135 ** and the WhereInfo.wctrlFlags member.
11136 */
11137 #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
@@ -11203,37 +11141,15 @@
11141 #define WHERE_DUPLICATES_OK 0x0008 /* Ok to return a row more than once */
11142 #define WHERE_OMIT_OPEN_CLOSE 0x0010 /* Table cursors are already open */
11143 #define WHERE_FORCE_TABLE 0x0020 /* Do not use an index-only search */
11144 #define WHERE_ONETABLE_ONLY 0x0040 /* Only code the 1st table in pTabList */
11145 #define WHERE_AND_ONLY 0x0080 /* Don't use indices for OR terms */
11146 #define WHERE_GROUPBY 0x0100 /* pOrderBy is really a GROUP BY */
11147 #define WHERE_DISTINCTBY 0x0200 /* pOrderby is really a DISTINCT clause */
11148
11149 /* Allowed return values from sqlite3WhereIsDistinct()
11150 */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11151 #define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
11152 #define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
11153 #define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */
11154 #define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */
11155
@@ -11303,11 +11219,11 @@
11219 ExprList *pEList; /* The fields of the result */
11220 u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
11221 u16 selFlags; /* Various SF_* values */
11222 int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
11223 int addrOpenEphm[3]; /* OP_OpenEphem opcodes related to this select */
11224 u64 nSelectRow; /* Estimated number of result rows */
11225 SrcList *pSrc; /* The FROM clause */
11226 Expr *pWhere; /* The WHERE clause */
11227 ExprList *pGroupBy; /* The GROUP BY clause */
11228 Expr *pHaving; /* The HAVING clause */
11229 ExprList *pOrderBy; /* The ORDER BY clause */
@@ -11487,11 +11403,11 @@
11403 AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
11404
11405 /* Information used while coding trigger programs. */
11406 Parse *pToplevel; /* Parse structure for main program (or NULL) */
11407 Table *pTriggerTab; /* Table triggers are being coded for */
11408 u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */
11409 u32 oldmask; /* Mask of old.* columns referenced */
11410 u32 newmask; /* Mask of new.* columns referenced */
11411 u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
11412 u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
11413 u8 disableTriggers; /* True to disable triggers */
@@ -12057,10 +11973,16 @@
11973 #endif
11974 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
11975 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
11976 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
11977 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
11978 SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo*);
11979 SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
11980 SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
11981 SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
11982 SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
11983 SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*);
11984 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
11985 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
11986 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
11987 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
11988 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
@@ -19960,17 +19882,11 @@
19882 if( flag_plussign ) prefix = '+';
19883 else if( flag_blanksign ) prefix = ' ';
19884 else prefix = 0;
19885 }
19886 if( xtype==etGENERIC && precision>0 ) precision--;
 
 
 
 
 
19887 for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
 
19888 if( xtype==etFLOAT ) realvalue += rounder;
19889 /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
19890 exp = 0;
19891 if( sqlite3IsNaN((double)realvalue) ){
19892 bufpt = "NaN";
@@ -22931,12 +22847,11 @@
22847 */
22848 #if SQLITE_OS_UNIX /* This file is used on unix only */
22849
22850 /* Use posix_fallocate() if it is available
22851 */
22852 #if !defined(HAVE_POSIX_FALLOCATE) && defined(__linux__)
 
22853 # define HAVE_POSIX_FALLOCATE 1
22854 #endif
22855
22856 /*
22857 ** There are various methods for file locking used for concurrency
@@ -26866,19 +26781,23 @@
26781 }
26782 return SQLITE_OK;
26783 }
26784 case SQLITE_FCNTL_MMAP_SIZE: {
26785 i64 newLimit = *(i64*)pArg;
26786 int rc = SQLITE_OK;
26787 if( newLimit>sqlite3GlobalConfig.mxMmap ){
26788 newLimit = sqlite3GlobalConfig.mxMmap;
26789 }
26790 *(i64*)pArg = pFile->mmapSizeMax;
26791 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
26792 pFile->mmapSizeMax = newLimit;
26793 if( pFile->mmapSize>0 ){
26794 unixUnmapfile(pFile);
26795 rc = unixMapfile(pFile, -1);
26796 }
26797 }
26798 return rc;
26799 }
26800 #ifdef SQLITE_DEBUG
26801 /* The pager calls this method to signal that it has done
26802 ** a rollback and that the database is therefore unchanged and
26803 ** it hence it is OK for the transaction change counter to be
@@ -28244,11 +28163,11 @@
28163 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
28164 pNew->h = h;
28165 pNew->pVfs = pVfs;
28166 pNew->zPath = zFilename;
28167 pNew->ctrlFlags = (u8)ctrlFlags;
28168 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
28169 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
28170 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
28171 pNew->ctrlFlags |= UNIXFILE_PSOW;
28172 }
28173 if( strcmp(pVfs->zName,"unix-excl")==0 ){
@@ -30799,17 +30718,10 @@
30718 ** This file mapping API is common to both Win32 and WinRT.
30719 */
30720 WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
30721 #endif /* SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL) */
30722
 
 
 
 
 
 
 
30723 /*
30724 ** Some Microsoft compilers lack this definition.
30725 */
30726 #ifndef INVALID_FILE_ATTRIBUTES
30727 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
@@ -33531,10 +33443,13 @@
33443 }
33444 }
33445
33446 /* Forward declaration */
33447 static int getTempname(int nBuf, char *zBuf);
33448 #if SQLITE_MAX_MMAP_SIZE>0
33449 static int winMapfile(winFile*, sqlite3_int64);
33450 #endif
33451
33452 /*
33453 ** Control and query of the open file handle.
33454 */
33455 static int winFileControl(sqlite3_file *id, int op, void *pArg){
@@ -33614,17 +33529,24 @@
33529 return SQLITE_OK;
33530 }
33531 #if SQLITE_MAX_MMAP_SIZE>0
33532 case SQLITE_FCNTL_MMAP_SIZE: {
33533 i64 newLimit = *(i64*)pArg;
33534 int rc = SQLITE_OK;
33535 if( newLimit>sqlite3GlobalConfig.mxMmap ){
33536 newLimit = sqlite3GlobalConfig.mxMmap;
33537 }
33538 *(i64*)pArg = pFile->mmapSizeMax;
33539 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
33540 pFile->mmapSizeMax = newLimit;
33541 if( pFile->mmapSize>0 ){
33542 (void)winUnmapfile(pFile);
33543 rc = winMapfile(pFile, -1);
33544 }
33545 }
33546 OSTRACE(("FCNTL file=%p, rc=%d\n", pFile->h, rc));
33547 return rc;
33548 }
33549 #endif
33550 }
33551 OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
33552 return SQLITE_NOTFOUND;
@@ -33652,19 +33574,19 @@
33574 winFile *p = (winFile*)id;
33575 return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
33576 ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
33577 }
33578
 
 
33579 /*
33580 ** Windows will only let you create file view mappings
33581 ** on allocation size granularity boundaries.
33582 ** During sqlite3_os_init() we do a GetSystemInfo()
33583 ** to get the granularity size.
33584 */
33585 SYSTEM_INFO winSysInfo;
33586
33587 #ifndef SQLITE_OMIT_WAL
33588
33589 /*
33590 ** Helper functions to obtain and relinquish the global mutex. The
33591 ** global mutex is used to protect the winLockInfo objects used by
33592 ** this file, all of which may be shared by multiple threads.
@@ -34961,11 +34883,11 @@
34883 #if SQLITE_MAX_MMAP_SIZE>0
34884 pFile->hMap = NULL;
34885 pFile->pMapRegion = 0;
34886 pFile->mmapSize = 0;
34887 pFile->mmapSizeActual = 0;
34888 pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
34889 #endif
34890
34891 OpenCounter(+1);
34892 return rc;
34893 }
@@ -37220,11 +37142,11 @@
37142 PCache1 *pCache; /* The newly created page cache */
37143 PGroup *pGroup; /* The group the new page cache will belong to */
37144 int sz; /* Bytes of memory required to allocate the new cache */
37145
37146 /*
37147 ** The separateCache variable is true if each PCache has its own private
37148 ** PGroup. In other words, separateCache is true for mode (1) where no
37149 ** mutexing is required.
37150 **
37151 ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
37152 **
@@ -42544,11 +42466,12 @@
42466 /* Before the first write, give the VFS a hint of what the final
42467 ** file size will be.
42468 */
42469 assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
42470 if( rc==SQLITE_OK
42471 && pPager->dbHintSize<pPager->dbSize
42472 && (pList->pDirty || pList->pgno>pPager->dbHintSize)
42473 ){
42474 sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
42475 sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
42476 pPager->dbHintSize = pPager->dbSize;
42477 }
@@ -43509,11 +43432,11 @@
43432 ** requested page is not already stored in the cache, then no
43433 ** actual disk read occurs. In this case the memory image of the
43434 ** page is initialized to all zeros.
43435 **
43436 ** If noContent is true, it means that we do not care about the contents
43437 ** of the page. This occurs in two scenarios:
43438 **
43439 ** a) When reading a free-list leaf page from the database, and
43440 **
43441 ** b) When a savepoint is being rolled back and we need to load
43442 ** a new page into the cache to be filled with the data read
@@ -44919,11 +44842,31 @@
44842 pagerReportSize(pPager);
44843 }
44844 SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
44845 return pPager->pCodec;
44846 }
44847
44848 /*
44849 ** This function is called by the wal module when writing page content
44850 ** into the log file.
44851 **
44852 ** This function returns a pointer to a buffer containing the encrypted
44853 ** page content. If a malloc fails, this function may return NULL.
44854 */
44855 SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
44856 void *aData = 0;
44857 CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
44858 return aData;
44859 }
44860
44861 /*
44862 ** Return the current pager state
44863 */
44864 SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
44865 return pPager->eState;
44866 }
44867 #endif /* SQLITE_HAS_CODEC */
44868
44869 #ifndef SQLITE_OMIT_AUTOVACUUM
44870 /*
44871 ** Move the page pPg to location pgno in the file.
44872 **
@@ -45474,25 +45417,10 @@
45417 assert( pPager->eState==PAGER_READER );
45418 return sqlite3WalFramesize(pPager->pWal);
45419 }
45420 #endif
45421
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45422 #endif /* SQLITE_OMIT_DISKIO */
45423
45424 /************** End of pager.c ***********************************************/
45425 /************** Begin file wal.c *********************************************/
45426 /*
@@ -50759,11 +50687,11 @@
50687 if( rc ) return rc;
50688 top = get2byteNotZero(&data[hdr+5]);
50689 }else if( gap+2<=top ){
50690 /* Search the freelist looking for a free slot big enough to satisfy
50691 ** the request. The allocation is made from the first free slot in
50692 ** the list that is large enough to accommodate it.
50693 */
50694 int pc, addr;
50695 for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
50696 int size; /* Size of the free slot */
50697 if( pc>usableSize-4 || pc<addr+4 ){
@@ -52702,11 +52630,11 @@
52630 return rc;
52631 }
52632
52633 /*
52634 ** This routine is called prior to sqlite3PagerCommit when a transaction
52635 ** is committed for an auto-vacuum database.
52636 **
52637 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
52638 ** the database file should be truncated to during the commit process.
52639 ** i.e. the database has been reorganized so that only the first *pnTrunc
52640 ** pages are in use.
@@ -58045,16 +57973,10 @@
57973 *************************************************************************
57974 ** This file contains the implementation of the sqlite3_backup_XXX()
57975 ** API functions and the related features.
57976 */
57977
 
 
 
 
 
 
57978 /*
57979 ** Structure allocated for each backup operation.
57980 */
57981 struct sqlite3_backup {
57982 sqlite3* pDestDb; /* Destination database handle */
@@ -61942,11 +61864,11 @@
61864 /*
61865 ** If the Vdbe passed as the first argument opened a statement-transaction,
61866 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
61867 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
61868 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
61869 ** statement transaction is committed.
61870 **
61871 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
61872 ** Otherwise SQLITE_OK.
61873 */
61874 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
@@ -64011,17 +63933,10 @@
63933 int iType = sqlite3_value_type( columnMem(pStmt,i) );
63934 columnMallocFailure(pStmt);
63935 return iType;
63936 }
63937
 
 
 
 
 
 
 
63938 /*
63939 ** Convert the N-th element of pStmt->pColName[] into a string using
63940 ** xFunc() then return that string. If N is out of range, return 0.
63941 **
63942 ** There are up to 5 names for each column. useType determines which
@@ -64643,18 +64558,18 @@
64558 pVar = &utf8;
64559 }
64560 #endif
64561 nOut = pVar->n;
64562 #ifdef SQLITE_TRACE_SIZE_LIMIT
64563 if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
64564 nOut = SQLITE_TRACE_SIZE_LIMIT;
64565 while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
64566 }
64567 #endif
64568 sqlite3XPrintf(&out, "'%.*q'", nOut, pVar->z);
64569 #ifdef SQLITE_TRACE_SIZE_LIMIT
64570 if( nOut<pVar->n ) sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
64571 #endif
64572 #ifndef SQLITE_OMIT_UTF16
64573 if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
64574 #endif
64575 }else if( pVar->flags & MEM_Zero ){
@@ -64670,11 +64585,11 @@
64585 for(i=0; i<nOut; i++){
64586 sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
64587 }
64588 sqlite3StrAccumAppend(&out, "'", 1);
64589 #ifdef SQLITE_TRACE_SIZE_LIMIT
64590 if( nOut<pVar->n ) sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
64591 #endif
64592 }
64593 }
64594 }
64595 return sqlite3StrAccumFinish(&out);
@@ -68269,12 +68184,12 @@
68184 ** If P2 is non-zero, then a write-transaction is started. A RESERVED lock is
68185 ** obtained on the database file when a write-transaction is started. No
68186 ** other process can start another write transaction while this transaction is
68187 ** underway. Starting a write transaction also creates a rollback journal. A
68188 ** write transaction must be started before any changes can be made to the
68189 ** database. If P2 is greater than or equal to 2 then an EXCLUSIVE lock is
68190 ** also obtained on the file.
68191 **
68192 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
68193 ** true (this flag is set if the Vdbe may modify more than one row and may
68194 ** throw an ABORT exception), a statement transaction may also be opened.
68195 ** More specifically, a statement transaction is opened iff the database
@@ -72224,11 +72139,11 @@
72139 **
72140 ** For the purposes of this comparison, EOF is considered greater than any
72141 ** other key value. If the keys are equal (only possible with two EOF
72142 ** values), it doesn't matter which index is stored.
72143 **
72144 ** The (N/4) elements of aTree[] that precede the final (N/2) described
72145 ** above contains the index of the smallest of each block of 4 iterators.
72146 ** And so on. So that aTree[1] contains the index of the iterator that
72147 ** currently points to the smallest key value. aTree[0] is unused.
72148 **
72149 ** Example:
@@ -73499,16 +73414,10 @@
73414 ** a power-of-two allocation. This mimimizes wasted space in power-of-two
73415 ** memory allocators.
73416 */
73417 #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
73418
 
 
 
 
 
 
73419 /*
73420 ** The rollback journal is composed of a linked list of these structures.
73421 */
73422 struct FileChunk {
73423 FileChunk *pNext; /* Next chunk in the journal */
@@ -75045,12 +74954,12 @@
74954 **
74955 ** Minor point: If this is the case, then the expression will be
74956 ** re-evaluated for each reference to it.
74957 */
74958 sNC.pEList = p->pEList;
 
74959 sNC.ncFlags |= NC_AsMaybe;
74960 if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
74961 if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
74962 sNC.ncFlags &= ~NC_AsMaybe;
74963
74964 /* The ORDER BY and GROUP BY clauses may not refer to terms in
74965 ** outer queries
@@ -76817,19 +76726,19 @@
76726
76727 if( eType==0 ){
76728 /* Could not found an existing table or index to use as the RHS b-tree.
76729 ** We will have to generate an ephemeral table to do the job.
76730 */
76731 u32 savedNQueryLoop = pParse->nQueryLoop;
76732 int rMayHaveNull = 0;
76733 eType = IN_INDEX_EPH;
76734 if( prNotFound ){
76735 *prNotFound = rMayHaveNull = ++pParse->nMem;
76736 sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
76737 }else{
76738 testcase( pParse->nQueryLoop>0 );
76739 pParse->nQueryLoop = 0;
76740 if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
76741 eType = IN_INDEX_ROWID;
76742 }
76743 }
76744 sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
@@ -76867,11 +76776,11 @@
76776 ** the register given by rMayHaveNull to NULL. Calling routines will take
76777 ** care of changing this register value to non-NULL if the RHS is NULL-free.
76778 **
76779 ** If rMayHaveNull is zero, that means that the subquery is being used
76780 ** for membership testing only. There is no need to initialize any
76781 ** registers to indicate the presence or absence of NULLs on the RHS.
76782 **
76783 ** For a SELECT or EXISTS operator, return the register that holds the
76784 ** result. For IN operators or if an error occurs, the return value is 0.
76785 */
76786 #ifndef SQLITE_OMIT_SUBQUERY
@@ -80267,11 +80176,11 @@
80176 **
80177 ** Additional tables might be added in future releases of SQLite.
80178 ** The sqlite_stat2 table is not created or used unless the SQLite version
80179 ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
80180 ** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated.
80181 ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
80182 ** created and used by SQLite versions 3.7.9 and later and with
80183 ** SQLITE_ENABLE_STAT3 defined. The fucntionality of sqlite_stat3
80184 ** is a superset of sqlite_stat2.
80185 **
80186 ** Format of sqlite_stat1:
@@ -83455,10 +83364,11 @@
83364 zColl = sqlite3NameFromToken(db, pToken);
83365 if( !zColl ) return;
83366
83367 if( sqlite3LocateCollSeq(pParse, zColl) ){
83368 Index *pIdx;
83369 sqlite3DbFree(db, p->aCol[i].zColl);
83370 p->aCol[i].zColl = zColl;
83371
83372 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
83373 ** then an index may have been created on this column before the
83374 ** collation type was added. Correct this if it is the case.
@@ -84874,10 +84784,11 @@
84784 zExtra = (char *)(&pIndex->zName[nName+1]);
84785 memcpy(pIndex->zName, zName, nName+1);
84786 pIndex->pTable = pTab;
84787 pIndex->nColumn = pList->nExpr;
84788 pIndex->onError = (u8)onError;
84789 pIndex->uniqNotNull = onError==OE_Abort;
84790 pIndex->autoIndex = (u8)(pName==0);
84791 pIndex->pSchema = db->aDb[iDb].pSchema;
84792 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
84793
84794 /* Check to see if we should honor DESC requests on index columns
@@ -84932,10 +84843,11 @@
84843 goto exit_create_index;
84844 }
84845 pIndex->azColl[i] = zColl;
84846 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
84847 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
84848 if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0;
84849 }
84850 sqlite3DefaultRowEst(pIndex);
84851
84852 if( pTab==pParse->pNewTable ){
84853 /* This routine has been called to create an automatic index as a
@@ -85363,19 +85275,19 @@
85275 assert( db->mallocFailed );
85276 return pSrc;
85277 }
85278 pSrc = pNew;
85279 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
85280 pSrc->nAlloc = (u8)nGot;
85281 }
85282
85283 /* Move existing slots that come after the newly inserted slots
85284 ** out of the way */
85285 for(i=pSrc->nSrc-1; i>=iStart; i--){
85286 pSrc->a[i+nExtra] = pSrc->a[i];
85287 }
85288 pSrc->nSrc += (i8)nExtra;
85289
85290 /* Zero the newly allocated slots */
85291 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
85292 for(i=iStart; i<iStart+nExtra; i++){
85293 pSrc->a[i].iCursor = -1;
@@ -87378,11 +87290,11 @@
87290 ** of x. If x is text, then we actually count UTF-8 characters.
87291 ** If x is a blob, then we count bytes.
87292 **
87293 ** If p1 is negative, then we begin abs(p1) from the end of x[].
87294 **
87295 ** If p2 is negative, return the p2 characters preceding p1.
87296 */
87297 static void substrFunc(
87298 sqlite3_context *context,
87299 int argc,
87300 sqlite3_value **argv
@@ -88037,14 +87949,10 @@
87949 '0', '1', '2', '3', '4', '5', '6', '7',
87950 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
87951 };
87952
87953 /*
 
 
 
 
87954 ** Implementation of the QUOTE() function. This function takes a single
87955 ** argument. If the argument is numeric, the return value is the same as
87956 ** the argument. If the argument is NULL, the return value is the string
87957 ** "NULL". Otherwise, the argument is enclosed in single quotes with
87958 ** single-quote escapes.
@@ -88229,11 +88137,11 @@
88137 }
88138
88139 /*
88140 ** The replace() function. Three arguments are all strings: call
88141 ** them A, B, and C. The result is also a string which is derived
88142 ** from A by replacing every occurrence of B with C. The match
88143 ** must be exact. Collating sequences are not used.
88144 */
88145 static void replaceFunc(
88146 sqlite3_context *context,
88147 int argc,
@@ -94147,15 +94055,19 @@
94055 sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
94056 }
94057 }
94058 }
94059 sz = -1;
94060 rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
94061 #if SQLITE_MAX_MMAP_SIZE==0
94062 sz = 0;
94063 #endif
94064 if( rc==SQLITE_OK ){
94065 returnSingleInt(pParse, "mmap_size", sz);
94066 }else if( rc!=SQLITE_NOTFOUND ){
94067 pParse->nErr++;
94068 pParse->rc = rc;
94069 }
94070 }else
94071
94072 /*
94073 ** PRAGMA temp_store
@@ -94682,11 +94594,11 @@
94594 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
94595 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
94596 #endif
94597
94598 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
94599 /* Pragma "quick_check" is reduced version of
94600 ** integrity_check designed to detect most database corruption
94601 ** without most of the overhead of a full integrity-check.
94602 */
94603 if( sqlite3StrICmp(zLeft, "integrity_check")==0
94604 || sqlite3StrICmp(zLeft, "quick_check")==0
@@ -95140,14 +95052,14 @@
95052 }else
95053 #endif
95054
95055 #ifdef SQLITE_HAS_CODEC
95056 if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
95057 sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
95058 }else
95059 if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
95060 sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
95061 }else
95062 if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
95063 sqlite3StrICmp(zLeft, "hexrekey")==0) ){
95064 int i, h1, h2;
95065 char zKey[40];
@@ -95155,13 +95067,13 @@
95067 h1 += 9*(1&(h1>>6));
95068 h2 += 9*(1&(h2>>6));
95069 zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
95070 }
95071 if( (zLeft[3] & 0xf)==0xb ){
95072 sqlite3_key_v2(db, zDb, zKey, i/2);
95073 }else{
95074 sqlite3_rekey_v2(db, zDb, zKey, i/2);
95075 }
95076 }else
95077 #endif
95078 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
95079 if( sqlite3StrICmp(zLeft, "activate_extensions")==0 && zRight ){
@@ -95792,11 +95704,11 @@
95704 }
95705
95706 sqlite3VtabUnlockList(db);
95707
95708 pParse->db = db;
95709 pParse->nQueryLoop = 0; /* Logarithmic, so 0 really means 1 */
95710 if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
95711 char *zSqlCopy;
95712 int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
95713 testcase( nBytes==mxLen );
95714 testcase( nBytes==mxLen+1 );
@@ -95814,11 +95726,11 @@
95726 pParse->zTail = &zSql[nBytes];
95727 }
95728 }else{
95729 sqlite3RunParser(pParse, zSql, &zErrMsg);
95730 }
95731 assert( 0==pParse->nQueryLoop );
95732
95733 if( db->mallocFailed ){
95734 pParse->rc = SQLITE_NOMEM;
95735 }
95736 if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
@@ -96178,11 +96090,11 @@
96090 sqlite3DbFree(db, p);
96091 }
96092 }
96093
96094 /*
96095 ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
96096 ** type of join. Return an integer constant that expresses that type
96097 ** in terms of the following bit values:
96098 **
96099 ** JT_INNER
96100 ** JT_CROSS
@@ -97592,11 +97504,11 @@
97504 int addr1, n;
97505 if( p->iLimit ) return;
97506
97507 /*
97508 ** "LIMIT -1" always shows all rows. There is some
97509 ** controversy about what the correct behavior should be.
97510 ** The current implementation interprets "LIMIT 0" to mean
97511 ** no rows.
97512 */
97513 sqlite3ExprCacheClear(pParse);
97514 assert( p->pOffset==0 || p->pLimit!=0 );
@@ -97607,12 +97519,12 @@
97519 if( sqlite3ExprIsInteger(p->pLimit, &n) ){
97520 sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
97521 VdbeComment((v, "LIMIT counter"));
97522 if( n==0 ){
97523 sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
97524 }else if( n>=0 && p->nSelectRow>(u64)n ){
97525 p->nSelectRow = n;
97526 }
97527 }else{
97528 sqlite3ExprCode(pParse, p->pLimit, iLimit);
97529 sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
97530 VdbeComment((v, "LIMIT counter"));
@@ -97802,13 +97714,13 @@
97714 pDelete = p->pPrior;
97715 p->pPrior = pPrior;
97716 p->nSelectRow += pPrior->nSelectRow;
97717 if( pPrior->pLimit
97718 && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
97719 && nLimit>0 && p->nSelectRow > (u64)nLimit
97720 ){
97721 p->nSelectRow = nLimit;
97722 }
97723 if( addr ){
97724 sqlite3VdbeJumpHere(v, addr);
97725 }
97726 break;
@@ -99953,15 +99865,14 @@
99865 Parse *pParse, /* Parse context */
99866 Table *pTab, /* Table being queried */
99867 Index *pIdx /* Index used to optimize scan, or NULL */
99868 ){
99869 if( pParse->explain==2 ){
99870 char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
99871 pTab->zName,
99872 pIdx ? " USING COVERING INDEX " : "",
99873 pIdx ? pIdx->zName : ""
 
99874 );
99875 sqlite3VdbeAddOp4(
99876 pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
99877 );
99878 }
@@ -100115,11 +100026,11 @@
100026 }
100027 continue;
100028 }
100029
100030 /* Increment Parse.nHeight by the height of the largest expression
100031 ** tree referred to by this, the parent select. The child select
100032 ** may contain expression trees of at most
100033 ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
100034 ** more conservative than necessary, but much easier than enforcing
100035 ** an exact limit.
100036 */
@@ -100308,11 +100219,11 @@
100219 }
100220
100221 /* Set the limiter.
100222 */
100223 iEnd = sqlite3VdbeMakeLabel(v);
100224 p->nSelectRow = LARGEST_INT64;
100225 computeLimitRegisters(pParse, p, iEnd);
100226 if( p->iLimit==0 && addrSortIndex>=0 ){
100227 sqlite3VdbeGetOp(v, addrSortIndex)->opcode = OP_SorterOpen;
100228 p->selFlags |= SF_UseSorter;
100229 }
@@ -100336,13 +100247,17 @@
100247 ExprList *pDist = (sDistinct.isTnct ? p->pEList : 0);
100248
100249 /* Begin the database scan. */
100250 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pOrderBy, pDist, 0,0);
100251 if( pWInfo==0 ) goto select_end;
100252 if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
100253 p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
100254 }
100255 if( sqlite3WhereIsDistinct(pWInfo) ){
100256 sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
100257 }
100258 if( pOrderBy && sqlite3WhereIsOrdered(pWInfo) ) pOrderBy = 0;
100259
100260 /* If sorting index that was created by a prior OP_OpenEphemeral
100261 ** instruction ended up not being needed, then change the OP_OpenEphemeral
100262 ** into an OP_Noop.
100263 */
@@ -100351,11 +100266,12 @@
100266 p->addrOpenEphm[2] = -1;
100267 }
100268
100269 /* Use the standard inner loop. */
100270 selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, &sDistinct, pDest,
100271 sqlite3WhereContinueLabel(pWInfo),
100272 sqlite3WhereBreakLabel(pWInfo));
100273
100274 /* End the database scan loop.
100275 */
100276 sqlite3WhereEnd(pWInfo);
100277 }else{
@@ -100384,13 +100300,13 @@
100300 pItem->iAlias = 0;
100301 }
100302 for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
100303 pItem->iAlias = 0;
100304 }
100305 if( p->nSelectRow>100 ) p->nSelectRow = 100;
100306 }else{
100307 p->nSelectRow = 1;
100308 }
100309
100310
100311 /* Create a label to jump to when we want to abort the query */
100312 addrEnd = sqlite3VdbeMakeLabel(v);
@@ -100466,13 +100382,14 @@
100382 ** This might involve two separate loops with an OP_Sort in between, or
100383 ** it might be a single loop that uses an index to extract information
100384 ** in the right order to begin with.
100385 */
100386 sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
100387 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
100388 WHERE_GROUPBY, 0);
100389 if( pWInfo==0 ) goto select_end;
100390 if( sqlite3WhereIsOrdered(pWInfo) ){
100391 /* The optimizer is able to deliver rows in group by order so
100392 ** we do not have to sort. The OP_OpenEphemeral table will be
100393 ** cancelled later because we still need to use the pKeyInfo
100394 */
100395 groupBySort = 0;
@@ -100749,12 +100666,12 @@
100666 sqlite3ExprListDelete(db, pDel);
100667 goto select_end;
100668 }
100669 updateAccumulator(pParse, &sAggInfo);
100670 assert( pMinMax==0 || pMinMax->nExpr==1 );
100671 if( sqlite3WhereIsOrdered(pWInfo) ){
100672 sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3WhereBreakLabel(pWInfo));
100673 VdbeComment((v, "%s() by index",
100674 (flag==WHERE_ORDERBY_MIN?"min":"max")));
100675 }
100676 sqlite3WhereEnd(pWInfo);
100677 finalizeAggFunctions(pParse, &sAggInfo);
@@ -102109,11 +102026,11 @@
102026 }
102027
102028 /*
102029 ** This is called to code the required FOR EACH ROW triggers for an operation
102030 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
102031 ** is given by the op parameter. The tr_tm parameter determines whether the
102032 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
102033 ** parameter pChanges is passed the list of columns being modified.
102034 **
102035 ** If there are no triggers that fire at the specified time for the specified
102036 ** operation on pTab, this function is a no-op.
@@ -102560,11 +102477,11 @@
102477 sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
102478 pWInfo = sqlite3WhereBegin(
102479 pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, 0
102480 );
102481 if( pWInfo==0 ) goto update_cleanup;
102482 okOnePass = sqlite3WhereOkOnePass(pWInfo);
102483
102484 /* Remember the rowid of every item to be updated.
102485 */
102486 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
102487 if( !okOnePass ){
@@ -104397,22 +104314,165 @@
104314 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
104315 /***/ int sqlite3WhereTrace = 0;
104316 #endif
104317 #if defined(SQLITE_DEBUG) \
104318 && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
104319 # define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
104320 # define WHERETRACE_ENABLED 1
104321 #else
104322 # define WHERETRACE(K,X)
104323 #endif
104324
104325 /* Forward reference
104326 */
104327 typedef struct WhereClause WhereClause;
104328 typedef struct WhereMaskSet WhereMaskSet;
104329 typedef struct WhereOrInfo WhereOrInfo;
104330 typedef struct WhereAndInfo WhereAndInfo;
104331 typedef struct WhereLevel WhereLevel;
104332 typedef struct WhereLoop WhereLoop;
104333 typedef struct WherePath WherePath;
104334 typedef struct WhereTerm WhereTerm;
104335 typedef struct WhereLoopBuilder WhereLoopBuilder;
104336 typedef struct WhereScan WhereScan;
104337
104338 /*
104339 ** Cost X is tracked as 10*log2(X) stored in a 16-bit integer. The
104340 ** maximum cost for ordinary tables is 64*(2**63) which becomes 6900.
104341 ** (Virtual tables can return a larger cost, but let's assume they do not.)
104342 ** So all costs can be stored in a 16-bit unsigned integer without risk
104343 ** of overflow.
104344 **
104345 ** Costs are estimates, so don't go to the computational trouble to compute
104346 ** 10*log2(X) exactly. Instead, a close estimate is used. Any value of
104347 ** X<=1 is stored as 0. X=2 is 10. X=3 is 16. X=1000 is 99. etc.
104348 **
104349 ** The tool/wherecosttest.c source file implements a command-line program
104350 ** that will convert between WhereCost to integers and do addition and
104351 ** multiplication on WhereCost values. That command-line program is a
104352 ** useful utility to have around when working with this module.
104353 */
104354 typedef unsigned short int WhereCost;
104355
104356 /*
104357 ** This object contains information needed to implement a single nested
104358 ** loop in WHERE clause.
104359 **
104360 ** Contrast this object with WhereLoop. This object describes the
104361 ** implementation of the loop. WhereLoop describes the algorithm.
104362 ** This object contains a pointer to the WhereLoop algorithm as one of
104363 ** its elements.
104364 **
104365 ** The WhereInfo object contains a single instance of this object for
104366 ** each term in the FROM clause (which is to say, for each of the
104367 ** nested loops as implemented). The order of WhereLevel objects determines
104368 ** the loop nested order, with WhereInfo.a[0] being the outer loop and
104369 ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
104370 */
104371 struct WhereLevel {
104372 int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
104373 int iTabCur; /* The VDBE cursor used to access the table */
104374 int iIdxCur; /* The VDBE cursor used to access pIdx */
104375 int addrBrk; /* Jump here to break out of the loop */
104376 int addrNxt; /* Jump here to start the next IN combination */
104377 int addrCont; /* Jump here to continue with the next loop cycle */
104378 int addrFirst; /* First instruction of interior of the loop */
104379 u8 iFrom; /* Which entry in the FROM clause */
104380 u8 op, p5; /* Opcode and P5 of the opcode that ends the loop */
104381 int p1, p2; /* Operands of the opcode used to ends the loop */
104382 union { /* Information that depends on pWLoop->wsFlags */
104383 struct {
104384 int nIn; /* Number of entries in aInLoop[] */
104385 struct InLoop {
104386 int iCur; /* The VDBE cursor used by this IN operator */
104387 int addrInTop; /* Top of the IN loop */
104388 u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
104389 } *aInLoop; /* Information about each nested IN operator */
104390 } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
104391 Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
104392 } u;
104393 struct WhereLoop *pWLoop; /* The selected WhereLoop object */
104394 };
104395
104396 /*
104397 ** Each instance of this object represents an algorithm for evaluating one
104398 ** term of a join. Every term of the FROM clause will have at least
104399 ** one corresponding WhereLoop object (unless INDEXED BY constraints
104400 ** prevent a query solution - which is an error) and many terms of the
104401 ** FROM clause will have multiple WhereLoop objects, each describing a
104402 ** potential way of implementing that FROM-clause term, together with
104403 ** dependencies and cost estimates for using the chosen algorithm.
104404 **
104405 ** Query planning consists of building up a collection of these WhereLoop
104406 ** objects, then computing a particular sequence of WhereLoop objects, with
104407 ** one WhereLoop object per FROM clause term, that satisfy all dependencies
104408 ** and that minimize the overall cost.
104409 */
104410 struct WhereLoop {
104411 Bitmask prereq; /* Bitmask of other loops that must run first */
104412 Bitmask maskSelf; /* Bitmask identifying table iTab */
104413 #ifdef SQLITE_DEBUG
104414 char cId; /* Symbolic ID of this loop for debugging use */
104415 #endif
104416 u8 iTab; /* Position in FROM clause of table for this loop */
104417 u8 iSortIdx; /* Sorting index number. 0==None */
104418 WhereCost rSetup; /* One-time setup cost (ex: create transient index) */
104419 WhereCost rRun; /* Cost of running each loop */
104420 WhereCost nOut; /* Estimated number of output rows */
104421 union {
104422 struct { /* Information for internal btree tables */
104423 int nEq; /* Number of equality constraints */
104424 Index *pIndex; /* Index used, or NULL */
104425 } btree;
104426 struct { /* Information for virtual tables */
104427 int idxNum; /* Index number */
104428 u8 needFree; /* True if sqlite3_free(idxStr) is needed */
104429 u8 isOrdered; /* True if satisfies ORDER BY */
104430 u16 omitMask; /* Terms that may be omitted */
104431 char *idxStr; /* Index identifier string */
104432 } vtab;
104433 } u;
104434 u32 wsFlags; /* WHERE_* flags describing the plan */
104435 u16 nLTerm; /* Number of entries in aLTerm[] */
104436 /**** whereLoopXfer() copies fields above ***********************/
104437 # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
104438 u16 nLSlot; /* Number of slots allocated for aLTerm[] */
104439 WhereTerm **aLTerm; /* WhereTerms used */
104440 WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
104441 WhereTerm *aLTermSpace[4]; /* Initial aLTerm[] space */
104442 };
104443
104444 /* Forward declaration of methods */
104445 static int whereLoopResize(sqlite3*, WhereLoop*, int);
104446
104447 /*
104448 ** Each instance of this object holds a sequence of WhereLoop objects
104449 ** that implement some or all of a query plan.
104450 **
104451 ** Think of each WhereLoop objects as a node in a graph, which arcs
104452 ** showing dependences and costs for travelling between nodes. (That is
104453 ** not a completely accurate description because WhereLoop costs are a
104454 ** vector, not a scalar, and because dependences are many-to-one, not
104455 ** one-to-one as are graph nodes. But it is a useful visualization aid.)
104456 ** Then a WherePath object is a path through the graph that visits some
104457 ** or all of the WhereLoop objects once.
104458 **
104459 ** The "solver" works by creating the N best WherePath objects of length
104460 ** 1. Then using those as a basis to compute the N best WherePath objects
104461 ** of length 2. And so forth until the length of WherePaths equals the
104462 ** number of nodes in the FROM clause. The best (lowest cost) WherePath
104463 ** at the end is the choosen query plan.
104464 */
104465 struct WherePath {
104466 Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */
104467 Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */
104468 WhereCost nRow; /* Estimated number of rows generated by this path */
104469 WhereCost rCost; /* Total cost of this path */
104470 u8 isOrdered; /* True if this path satisfies ORDER BY */
104471 u8 isOrderedValid; /* True if the isOrdered field is valid */
104472 WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */
104473 };
104474
104475 /*
104476 ** The query generator uses an array of instances of this structure to
104477 ** help it analyze the subexpressions of the WHERE clause. Each WHERE
104478 ** clause subexpression is separated from the others by AND operators,
@@ -104461,11 +104521,10 @@
104521 **
104522 ** The number of terms in a join is limited by the number of bits
104523 ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
104524 ** is only able to process joins with 64 or fewer tables.
104525 */
 
104526 struct WhereTerm {
104527 Expr *pExpr; /* Pointer to the subexpression that is this term */
104528 int iParent; /* Disable pWC->a[iParent] when this term disabled */
104529 int leftCursor; /* Cursor number of X in "X <op> <expr>" */
104530 union {
@@ -104495,10 +104554,26 @@
104554 # define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
104555 #else
104556 # define TERM_VNULL 0x00 /* Disabled if not using stat3 */
104557 #endif
104558
104559 /*
104560 ** An instance of the WhereScan object is used as an iterator for locating
104561 ** terms in the WHERE clause that are useful to the query planner.
104562 */
104563 struct WhereScan {
104564 WhereClause *pOrigWC; /* Original, innermost WhereClause */
104565 WhereClause *pWC; /* WhereClause currently being scanned */
104566 char *zCollName; /* Required collating sequence, if not NULL */
104567 char idxaff; /* Must match this affinity, if zCollName!=NULL */
104568 unsigned char nEquiv; /* Number of entries in aEquiv[] */
104569 unsigned char iEquiv; /* Next unused slot in aEquiv[] */
104570 u32 opMask; /* Acceptable operators */
104571 int k; /* Resume scanning at this->pWC->a[this->k] */
104572 int aEquiv[22]; /* Cursor,Column pairs for equivalence classes */
104573 };
104574
104575 /*
104576 ** An instance of the following structure holds all information about a
104577 ** WHERE clause. Mostly this is a container for one or more WhereTerms.
104578 **
104579 ** Explanation of pOuter: For a WHERE clause of the form
@@ -104508,15 +104583,13 @@
104583 ** There are separate WhereClause objects for the whole clause and for
104584 ** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
104585 ** subclauses points to the WhereClause object for the whole clause.
104586 */
104587 struct WhereClause {
104588 WhereInfo *pWInfo; /* WHERE clause processing context */
 
104589 WhereClause *pOuter; /* Outer conjunction */
104590 u8 op; /* Split operator. TK_AND or TK_OR */
 
104591 int nTerm; /* Number of terms */
104592 int nSlot; /* Number of entries in a[] */
104593 WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
104594 #if defined(SQLITE_SMALL_STACK)
104595 WhereTerm aStatic[1]; /* Initial static space for a[] */
@@ -104572,23 +104645,59 @@
104645 int n; /* Number of assigned cursor values */
104646 int ix[BMS]; /* Cursor assigned to each bit */
104647 };
104648
104649 /*
104650 ** This object is a convenience wrapper holding all information needed
104651 ** to construct WhereLoop objects for a particular query.
104652 */
104653 struct WhereLoopBuilder {
104654 WhereInfo *pWInfo; /* Information about this WHERE */
104655 WhereClause *pWC; /* WHERE clause terms */
104656 ExprList *pOrderBy; /* ORDER BY clause */
104657 WhereLoop *pNew; /* Template WhereLoop */
104658 WhereLoop *pBest; /* If non-NULL, store single best loop here */
104659 };
104660
104661 /*
104662 ** The WHERE clause processing routine has two halves. The
104663 ** first part does the start of the WHERE loop and the second
104664 ** half does the tail of the WHERE loop. An instance of
104665 ** this structure is returned by the first half and passed
104666 ** into the second half to give some continuity.
104667 **
104668 ** An instance of this object holds the complete state of the query
104669 ** planner.
104670 */
104671 struct WhereInfo {
104672 Parse *pParse; /* Parsing and code generating context */
104673 SrcList *pTabList; /* List of tables in the join */
104674 ExprList *pOrderBy; /* The ORDER BY clause or NULL */
104675 ExprList *pDistinct; /* DISTINCT ON values, or NULL */
104676 WhereLoop *pLoops; /* List of all WhereLoop objects */
104677 Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
104678 WhereCost nRowOut; /* Estimated number of output rows */
104679 u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
104680 u8 bOBSat; /* ORDER BY satisfied by indices */
104681 u8 okOnePass; /* Ok to use one-pass algorithm for UPDATE/DELETE */
104682 u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
104683 u8 eDistinct; /* One of the WHERE_DISTINCT_* values below */
104684 int iTop; /* The very beginning of the WHERE loop */
104685 int iContinue; /* Jump here to continue with next record */
104686 int iBreak; /* Jump here to break out of the loop */
104687 int nLevel; /* Number of nested loop */
104688 int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
104689 WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */
104690 WhereClause sWC; /* Decomposition of the WHERE clause */
104691 WhereLevel a[1]; /* Information about each nest loop in WHERE */
104692 };
104693
104694 /*
104695 ** Bitmasks for the operators on WhereTerm objects. These are all
104696 ** operators that are of interest to the query planner. An
104697 ** OR-ed combination of these values can be used when searching for
104698 ** particular WhereTerms within a WhereClause.
104699 */
104700 #define WO_IN 0x001
104701 #define WO_EQ 0x002
104702 #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
104703 #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
@@ -104603,96 +104712,106 @@
104712
104713 #define WO_ALL 0xfff /* Mask of all possible WO_* values */
104714 #define WO_SINGLE 0x0ff /* Mask of all non-compound WO_* values */
104715
104716 /*
104717 ** These are definitions of bits in the WhereLoop.wsFlags field.
104718 ** The particular combination of bits in each WhereLoop help to
104719 ** determine the algorithm that WhereLoop represents.
104720 */
104721 #define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR or x IN (...) or x IS NULL */
104722 #define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */
104723 #define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */
104724 #define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */
104725 #define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */
104726 #define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */
104727 #define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */
104728 #define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */
104729 #define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
104730 #define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */
104731 #define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */
104732 #define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */
104733 #define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
104734 #define WHERE_ONEROW 0x00001000 /* Selects no more than one row */
104735 #define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */
104736 #define WHERE_TEMP_INDEX 0x00004000 /* Uses an ephemeral index */
104737
104738
104739 /* Convert a WhereCost value (10 times log2(X)) into its integer value X.
104740 ** A rough approximation is used. The value returned is not exact.
104741 */
104742 static u64 whereCostToInt(WhereCost x){
104743 u64 n;
104744 if( x<10 ) return 1;
104745 n = x%10;
104746 x /= 10;
104747 if( n>=5 ) n -= 2;
104748 else if( n>=1 ) n -= 1;
104749 if( x>=3 ) return (n+8)<<(x-3);
104750 return (n+8)>>(3-x);
104751 }
104752
104753 /*
104754 ** Return the estimated number of output rows from a WHERE clause
104755 */
104756 SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
104757 return whereCostToInt(pWInfo->nRowOut);
104758 }
104759
104760 /*
104761 ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
104762 ** WHERE clause returns outputs for DISTINCT processing.
104763 */
104764 SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
104765 return pWInfo->eDistinct;
104766 }
104767
104768 /*
104769 ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
104770 ** Return FALSE if the output needs to be sorted.
104771 */
104772 SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
104773 return pWInfo->bOBSat!=0;
104774 }
104775
104776 /*
104777 ** Return the VDBE address or label to jump to in order to continue
104778 ** immediately with the next row of a WHERE clause.
104779 */
104780 SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
104781 return pWInfo->iContinue;
104782 }
104783
104784 /*
104785 ** Return the VDBE address or label to jump to in order to break
104786 ** out of a WHERE loop.
104787 */
104788 SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
104789 return pWInfo->iBreak;
104790 }
104791
104792 /*
104793 ** Return TRUE if an UPDATE or DELETE statement can operate directly on
104794 ** the rowids returned by a WHERE clause. Return FALSE if doing an
104795 ** UPDATE or DELETE might change subsequent WHERE clause results.
104796 */
104797 SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo){
104798 return pWInfo->okOnePass;
104799 }
104800
104801 /*
104802 ** Initialize a preallocated WhereClause structure.
104803 */
104804 static void whereClauseInit(
104805 WhereClause *pWC, /* The WhereClause to be initialized */
104806 WhereInfo *pWInfo /* The WHERE processing context */
 
 
104807 ){
104808 pWC->pWInfo = pWInfo;
 
104809 pWC->pOuter = 0;
104810 pWC->nTerm = 0;
104811 pWC->nSlot = ArraySize(pWC->aStatic);
104812 pWC->a = pWC->aStatic;
 
104813 }
104814
104815 /* Forward reference */
104816 static void whereClauseClear(WhereClause*);
104817
@@ -104717,11 +104836,11 @@
104836 ** itself is not freed. This routine is the inverse of whereClauseInit().
104837 */
104838 static void whereClauseClear(WhereClause *pWC){
104839 int i;
104840 WhereTerm *a;
104841 sqlite3 *db = pWC->pWInfo->pParse->db;
104842 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
104843 if( a->wtFlags & TERM_DYNAMIC ){
104844 sqlite3ExprDelete(db, a->pExpr);
104845 }
104846 if( a->wtFlags & TERM_ORINFO ){
@@ -104758,11 +104877,11 @@
104877 WhereTerm *pTerm;
104878 int idx;
104879 testcase( wtFlags & TERM_VIRTUAL ); /* EV: R-00211-15100 */
104880 if( pWC->nTerm>=pWC->nSlot ){
104881 WhereTerm *pOld = pWC->a;
104882 sqlite3 *db = pWC->pWInfo->pParse->db;
104883 pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
104884 if( pWC->a==0 ){
104885 if( wtFlags & TERM_DYNAMIC ){
104886 sqlite3ExprDelete(db, p);
104887 }
@@ -104798,12 +104917,12 @@
104917 **
104918 ** In the previous sentence and in the diagram, "slot[]" refers to
104919 ** the WhereClause.a[] array. The slot[] array grows as needed to contain
104920 ** all terms of the WHERE clause.
104921 */
104922 static void whereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
104923 pWC->op = op;
104924 if( pExpr==0 ) return;
104925 if( pExpr->op!=op ){
104926 whereClauseInsert(pWC, pExpr, 0);
104927 }else{
104928 whereSplit(pWC, pExpr->pLeft, op);
@@ -104810,13 +104929,13 @@
104929 whereSplit(pWC, pExpr->pRight, op);
104930 }
104931 }
104932
104933 /*
104934 ** Initialize a WhereMaskSet object
104935 */
104936 #define initMaskSet(P) (P)->n=0
104937
104938 /*
104939 ** Return the bitmask for the given cursor number. Return 0 if
104940 ** iCursor is not in the set.
104941 */
@@ -104823,11 +104942,11 @@
104942 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
104943 int i;
104944 assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
104945 for(i=0; i<pMaskSet->n; i++){
104946 if( pMaskSet->ix[i]==iCursor ){
104947 return MASKBIT(i);
104948 }
104949 }
104950 return 0;
104951 }
104952
@@ -104843,22 +104962,13 @@
104962 assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
104963 pMaskSet->ix[pMaskSet->n++] = iCursor;
104964 }
104965
104966 /*
104967 ** These routine walk (recursively) an expression tree and generates
104968 ** a bitmask indicating which tables are used in that expression
104969 ** tree.
 
 
 
 
 
 
 
 
 
104970 */
104971 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
104972 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
104973 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
104974 Bitmask mask = 0;
@@ -104908,11 +105018,11 @@
105018 }
105019
105020 /*
105021 ** Return TRUE if the given operator is one of the operators that is
105022 ** allowed for an indexable WHERE clause term. The allowed operators are
105023 ** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
105024 **
105025 ** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
105026 ** of one of the following forms: column = expression column > expression
105027 ** column >= expression column < expression column <= expression
105028 ** expression = column expression > column expression >= column
@@ -104935,14 +105045,13 @@
105045 /*
105046 ** Commute a comparison operator. Expressions of the form "X op Y"
105047 ** are converted into "Y op X".
105048 **
105049 ** If left/right precedence rules come into play when determining the
105050 ** collating sequence, then COLLATE operators are adjusted to ensure
105051 ** that the collating sequence does not change. For example:
105052 ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
 
105053 ** the left hand side of a comparison overrides any collation sequence
105054 ** attached to the right. For the same reason the EP_Collate flag
105055 ** is not commuted.
105056 */
105057 static void exprCommute(Parse *pParse, Expr *pExpr){
@@ -104994,10 +105103,134 @@
105103 assert( op!=TK_LE || c==WO_LE );
105104 assert( op!=TK_GT || c==WO_GT );
105105 assert( op!=TK_GE || c==WO_GE );
105106 return c;
105107 }
105108
105109 /*
105110 ** Advance to the next WhereTerm that matches according to the criteria
105111 ** established when the pScan object was initialized by whereScanInit().
105112 ** Return NULL if there are no more matching WhereTerms.
105113 */
105114 WhereTerm *whereScanNext(WhereScan *pScan){
105115 int iCur; /* The cursor on the LHS of the term */
105116 int iColumn; /* The column on the LHS of the term. -1 for IPK */
105117 Expr *pX; /* An expression being tested */
105118 WhereClause *pWC; /* Shorthand for pScan->pWC */
105119 WhereTerm *pTerm; /* The term being tested */
105120 int k = pScan->k; /* Where to start scanning */
105121
105122 while( pScan->iEquiv<=pScan->nEquiv ){
105123 iCur = pScan->aEquiv[pScan->iEquiv-2];
105124 iColumn = pScan->aEquiv[pScan->iEquiv-1];
105125 while( (pWC = pScan->pWC)!=0 ){
105126 for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
105127 if( pTerm->leftCursor==iCur && pTerm->u.leftColumn==iColumn ){
105128 if( (pTerm->eOperator & WO_EQUIV)!=0
105129 && pScan->nEquiv<ArraySize(pScan->aEquiv)
105130 ){
105131 int j;
105132 pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
105133 assert( pX->op==TK_COLUMN );
105134 for(j=0; j<pScan->nEquiv; j+=2){
105135 if( pScan->aEquiv[j]==pX->iTable
105136 && pScan->aEquiv[j+1]==pX->iColumn ){
105137 break;
105138 }
105139 }
105140 if( j==pScan->nEquiv ){
105141 pScan->aEquiv[j] = pX->iTable;
105142 pScan->aEquiv[j+1] = pX->iColumn;
105143 pScan->nEquiv += 2;
105144 }
105145 }
105146 if( (pTerm->eOperator & pScan->opMask)!=0 ){
105147 /* Verify the affinity and collating sequence match */
105148 if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
105149 CollSeq *pColl;
105150 Parse *pParse = pWC->pWInfo->pParse;
105151 pX = pTerm->pExpr;
105152 if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
105153 continue;
105154 }
105155 assert(pX->pLeft);
105156 pColl = sqlite3BinaryCompareCollSeq(pParse,
105157 pX->pLeft, pX->pRight);
105158 if( pColl==0 ) pColl = pParse->db->pDfltColl;
105159 if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
105160 continue;
105161 }
105162 }
105163 if( (pTerm->eOperator & WO_EQ)!=0
105164 && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
105165 && pX->iTable==pScan->aEquiv[0]
105166 && pX->iColumn==pScan->aEquiv[1]
105167 ){
105168 continue;
105169 }
105170 pScan->k = k+1;
105171 return pTerm;
105172 }
105173 }
105174 }
105175 pScan->pWC = pScan->pWC->pOuter;
105176 k = 0;
105177 }
105178 pScan->pWC = pScan->pOrigWC;
105179 k = 0;
105180 pScan->iEquiv += 2;
105181 }
105182 return 0;
105183 }
105184
105185 /*
105186 ** Initialize a WHERE clause scanner object. Return a pointer to the
105187 ** first match. Return NULL if there are no matches.
105188 **
105189 ** The scanner will be searching the WHERE clause pWC. It will look
105190 ** for terms of the form "X <op> <expr>" where X is column iColumn of table
105191 ** iCur. The <op> must be one of the operators described by opMask.
105192 **
105193 ** If the search is for X and the WHERE clause contains terms of the
105194 ** form X=Y then this routine might also return terms of the form
105195 ** "Y <op> <expr>". The number of levels of transitivity is limited,
105196 ** but is enough to handle most commonly occurring SQL statements.
105197 **
105198 ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
105199 ** index pIdx.
105200 */
105201 WhereTerm *whereScanInit(
105202 WhereScan *pScan, /* The WhereScan object being initialized */
105203 WhereClause *pWC, /* The WHERE clause to be scanned */
105204 int iCur, /* Cursor to scan for */
105205 int iColumn, /* Column to scan for */
105206 u32 opMask, /* Operator(s) to scan for */
105207 Index *pIdx /* Must be compatible with this index */
105208 ){
105209 int j;
105210
105211 /* memset(pScan, 0, sizeof(*pScan)); */
105212 pScan->pOrigWC = pWC;
105213 pScan->pWC = pWC;
105214 if( pIdx && iColumn>=0 ){
105215 pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
105216 for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
105217 if( NEVER(j>=pIdx->nColumn) ) return 0;
105218 }
105219 pScan->zCollName = pIdx->azColl[j];
105220 }else{
105221 pScan->idxaff = 0;
105222 pScan->zCollName = 0;
105223 }
105224 pScan->opMask = opMask;
105225 pScan->k = 0;
105226 pScan->aEquiv[0] = iCur;
105227 pScan->aEquiv[1] = iColumn;
105228 pScan->nEquiv = 2;
105229 pScan->iEquiv = 2;
105230 return whereScanNext(pScan);
105231 }
105232
105233 /*
105234 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
105235 ** where X is a reference to the iColumn of table iCur and <op> is one of
105236 ** the WO_xx operator codes specified by the op parameter.
@@ -105026,98 +105259,32 @@
105259 int iColumn, /* Column number of LHS */
105260 Bitmask notReady, /* RHS must not overlap with this mask */
105261 u32 op, /* Mask of WO_xx values describing operator */
105262 Index *pIdx /* Must be compatible with this index, if not NULL */
105263 ){
105264 WhereTerm *pResult = 0;
105265 WhereTerm *p;
105266 WhereScan scan;
105267
105268 p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
105269 while( p ){
105270 if( (p->prereqRight & notReady)==0 ){
105271 if( p->prereqRight==0 && (p->eOperator&WO_EQ)!=0 ){
105272 return p;
105273 }
105274 if( pResult==0 ) pResult = p;
105275 }
105276 p = whereScanNext(&scan);
105277 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105278 return pResult;
105279 }
105280
105281 /* Forward reference */
105282 static void exprAnalyze(SrcList*, WhereClause*, int);
105283
105284 /*
105285 ** Call exprAnalyze on all terms in a WHERE clause.
 
 
105286 */
105287 static void exprAnalyzeAll(
105288 SrcList *pTabList, /* the FROM clause */
105289 WhereClause *pWC /* the WHERE clause to be analyzed */
105290 ){
@@ -105345,15 +105512,15 @@
105512 static void exprAnalyzeOrTerm(
105513 SrcList *pSrc, /* the FROM clause */
105514 WhereClause *pWC, /* the complete WHERE clause */
105515 int idxTerm /* Index of the OR-term to be analyzed */
105516 ){
105517 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
105518 Parse *pParse = pWInfo->pParse; /* Parser context */
105519 sqlite3 *db = pParse->db; /* Database connection */
105520 WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
105521 Expr *pExpr = pTerm->pExpr; /* The expression of the term */
 
105522 int i; /* Loop counters */
105523 WhereClause *pOrWc; /* Breakup of pTerm into subterms */
105524 WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
105525 WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
105526 Bitmask chngToIN; /* Tables that might satisfy case 1 */
@@ -105368,11 +105535,11 @@
105535 assert( pExpr->op==TK_OR );
105536 pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
105537 if( pOrInfo==0 ) return;
105538 pTerm->wtFlags |= TERM_ORINFO;
105539 pOrWc = &pOrInfo->wc;
105540 whereClauseInit(pOrWc, pWInfo);
105541 whereSplit(pOrWc, pExpr, TK_OR);
105542 exprAnalyzeAll(pSrc, pOrWc);
105543 if( db->mallocFailed ) return;
105544 assert( pOrWc->nTerm>=2 );
105545
@@ -105394,20 +105561,20 @@
105561 Bitmask b = 0;
105562 pOrTerm->u.pAndInfo = pAndInfo;
105563 pOrTerm->wtFlags |= TERM_ANDINFO;
105564 pOrTerm->eOperator = WO_AND;
105565 pAndWC = &pAndInfo->wc;
105566 whereClauseInit(pAndWC, pWC->pWInfo);
105567 whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
105568 exprAnalyzeAll(pSrc, pAndWC);
105569 pAndWC->pOuter = pWC;
105570 testcase( db->mallocFailed );
105571 if( !db->mallocFailed ){
105572 for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
105573 assert( pAndTerm->pExpr );
105574 if( allowedOp(pAndTerm->pExpr->op) ){
105575 b |= getMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
105576 }
105577 }
105578 }
105579 indexable &= b;
105580 }
@@ -105414,14 +105581,14 @@
105581 }else if( pOrTerm->wtFlags & TERM_COPIED ){
105582 /* Skip this term for now. We revisit it when we process the
105583 ** corresponding TERM_VIRTUAL term */
105584 }else{
105585 Bitmask b;
105586 b = getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
105587 if( pOrTerm->wtFlags & TERM_VIRTUAL ){
105588 WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
105589 b |= getMask(&pWInfo->sMaskSet, pOther->leftCursor);
105590 }
105591 indexable &= b;
105592 if( (pOrTerm->eOperator & WO_EQ)==0 ){
105593 chngToIN = 0;
105594 }else{
@@ -105479,11 +105646,11 @@
105646 /* This is the 2-bit case and we are on the second iteration and
105647 ** current term is from the first iteration. So skip this term. */
105648 assert( j==1 );
105649 continue;
105650 }
105651 if( (chngToIN & getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){
105652 /* This term must be of the form t1.a==t2.b where t2 is in the
105653 ** chngToIN set but t1 is not. This term will be either preceeded
105654 ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
105655 ** and use its inversion. */
105656 testcase( pOrTerm->wtFlags & TERM_COPIED );
@@ -105498,11 +105665,11 @@
105665 if( i<0 ){
105666 /* No candidate table+column was found. This can only occur
105667 ** on the second iteration */
105668 assert( j==1 );
105669 assert( IsPowerOfTwo(chngToIN) );
105670 assert( chngToIN==getMask(&pWInfo->sMaskSet, iCursor) );
105671 break;
105672 }
105673 testcase( j==1 );
105674
105675 /* We have found a candidate table and column. Check to see if that
@@ -105547,11 +105714,11 @@
105714 if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
105715 assert( pOrTerm->eOperator & WO_EQ );
105716 assert( pOrTerm->leftCursor==iCursor );
105717 assert( pOrTerm->u.leftColumn==iColumn );
105718 pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
105719 pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
105720 pLeft = pOrTerm->pExpr->pLeft;
105721 }
105722 assert( pLeft!=0 );
105723 pDup = sqlite3ExprDup(db, pLeft, 0);
105724 pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
@@ -105596,10 +105763,11 @@
105763 static void exprAnalyze(
105764 SrcList *pSrc, /* the FROM clause */
105765 WhereClause *pWC, /* the WHERE clause */
105766 int idxTerm /* Index of the term to be analyzed */
105767 ){
105768 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
105769 WhereTerm *pTerm; /* The term to be analyzed */
105770 WhereMaskSet *pMaskSet; /* Set of table index masks */
105771 Expr *pExpr; /* The expression to be analyzed */
105772 Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
105773 Bitmask prereqAll; /* Prerequesites of pExpr */
@@ -105606,18 +105774,18 @@
105774 Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
105775 Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
105776 int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
105777 int noCase = 0; /* LIKE/GLOB distinguishes case */
105778 int op; /* Top-level operator. pExpr->op */
105779 Parse *pParse = pWInfo->pParse; /* Parsing context */
105780 sqlite3 *db = pParse->db; /* Database connection */
105781
105782 if( db->mallocFailed ){
105783 return;
105784 }
105785 pTerm = &pWC->a[idxTerm];
105786 pMaskSet = &pWInfo->sMaskSet;
105787 pExpr = pTerm->pExpr;
105788 assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
105789 prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
105790 op = pExpr->op;
105791 if( op==TK_IN ){
@@ -105891,15 +106059,12 @@
106059 */
106060 pTerm->prereqRight |= extraRight;
106061 }
106062
106063 /*
106064 ** This function searches pList for a entry that matches the iCol-th column
106065 ** of index pIdx.
 
 
 
106066 **
106067 ** If such an expression is found, its index in pList->a[] is returned. If
106068 ** no expression is found, -1 is returned.
106069 */
106070 static int findIndexCol(
@@ -105925,82 +106090,23 @@
106090 }
106091 }
106092
106093 return -1;
106094 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106095
106096 /*
106097 ** Return true if the DISTINCT expression-list passed as the third argument
106098 ** is redundant.
106099 **
106100 ** A DISTINCT list is redundant if the database contains some subset of
106101 ** columns that are unique and non-null.
106102 */
106103 static int isDistinctRedundant(
106104 Parse *pParse, /* Parsing context */
106105 SrcList *pTabList, /* The FROM clause */
106106 WhereClause *pWC, /* The WHERE clause */
106107 ExprList *pDistinct /* The result set that needs to be DISTINCT */
106108 ){
106109 Table *pTab;
106110 Index *pIdx;
106111 int i;
106112 int iBase;
@@ -106051,35 +106157,90 @@
106157 }
106158 }
106159
106160 return 0;
106161 }
106162
106163 /*
106164 ** The (an approximate) sum of two WhereCosts. This computation is
106165 ** not a simple "+" operator because WhereCost is stored as a logarithmic
106166 ** value.
106167 **
106168 */
106169 static WhereCost whereCostAdd(WhereCost a, WhereCost b){
106170 static const unsigned char x[] = {
106171 10, 10, /* 0,1 */
106172 9, 9, /* 2,3 */
106173 8, 8, /* 4,5 */
106174 7, 7, 7, /* 6,7,8 */
106175 6, 6, 6, /* 9,10,11 */
106176 5, 5, 5, /* 12-14 */
106177 4, 4, 4, 4, /* 15-18 */
106178 3, 3, 3, 3, 3, 3, /* 19-24 */
106179 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
106180 };
106181 if( a>=b ){
106182 if( a>b+49 ) return a;
106183 if( a>b+31 ) return a+1;
106184 return a+x[a-b];
106185 }else{
106186 if( b>a+49 ) return b;
106187 if( b>a+31 ) return b+1;
106188 return b+x[b-a];
106189 }
106190 }
106191
106192 /*
106193 ** Convert an integer into a WhereCost. In other words, compute a
106194 ** good approximatation for 10*log2(x).
 
 
 
106195 */
106196 static WhereCost whereCost(tRowcnt x){
106197 static WhereCost a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
106198 WhereCost y = 40;
106199 if( x<8 ){
106200 if( x<2 ) return 0;
106201 while( x<8 ){ y -= 10; x <<= 1; }
106202 }else{
106203 while( x>255 ){ y += 40; x >>= 4; }
106204 while( x>15 ){ y += 10; x >>= 1; }
106205 }
106206 return a[x&7] + y - 10;
106207 }
106208
106209 #ifndef SQLITE_OMIT_VIRTUALTABLE
106210 /*
106211 ** Convert a double (as received from xBestIndex of a virtual table)
106212 ** into a WhereCost. In other words, compute an approximation for
106213 ** 10*log2(x).
106214 */
106215 static WhereCost whereCostFromDouble(double x){
106216 u64 a;
106217 WhereCost e;
106218 assert( sizeof(x)==8 && sizeof(a)==8 );
106219 if( x<=1 ) return 0;
106220 if( x<=2000000000 ) return whereCost((tRowcnt)x);
106221 memcpy(&a, &x, 8);
106222 e = (a>>52) - 1022;
106223 return e*10;
106224 }
106225 #endif /* SQLITE_OMIT_VIRTUALTABLE */
106226
106227 /*
106228 ** Estimate the logarithm of the input value to base 2.
106229 */
106230 static WhereCost estLog(WhereCost N){
106231 WhereCost x = whereCost(N);
106232 return x>33 ? x - 33 : 0;
106233 }
106234
106235 /*
106236 ** Two routines for printing the content of an sqlite3_index_info
106237 ** structure. Used for testing and debugging only. If neither
106238 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
106239 ** are no-ops.
106240 */
106241 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
106242 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
106243 int i;
106244 if( !sqlite3WhereTrace ) return;
106245 for(i=0; i<p->nConstraint; i++){
106246 sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
@@ -106113,111 +106274,10 @@
106274 #else
106275 #define TRACE_IDX_INPUTS(A)
106276 #define TRACE_IDX_OUTPUTS(A)
106277 #endif
106278
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106279 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
106280 /*
106281 ** Return TRUE if the WHERE clause term pTerm is of a form where it
106282 ** could be used with an index to access pSrc, assuming an appropriate
106283 ** index existed.
@@ -106229,92 +106289,17 @@
106289 ){
106290 char aff;
106291 if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
106292 if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
106293 if( (pTerm->prereqRight & notReady)!=0 ) return 0;
106294 if( pTerm->u.leftColumn<0 ) return 0;
106295 aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
106296 if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
106297 return 1;
106298 }
106299 #endif
106300
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106301
106302 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
106303 /*
106304 ** Generate code to construct the Index object for an automatic index
106305 ** and to set up the WhereLevel object pLevel so that the code generator
@@ -106340,10 +106325,11 @@
106325 int regRecord; /* Register holding an index record */
106326 int n; /* Column counter */
106327 int i; /* Loop counter */
106328 int mxBitCol; /* Maximum column in pSrc->colUsed */
106329 CollSeq *pColl; /* Collating sequence to on a column */
106330 WhereLoop *pLoop; /* The Loop object */
106331 Bitmask idxCols; /* Bitmap of columns used for indexing */
106332 Bitmask extraCols; /* Bitmap of additional columns */
106333
106334 /* Generate code to skip over the creation and initialization of the
106335 ** transient index on 2nd and subsequent iterations of the loop. */
@@ -106354,54 +106340,58 @@
106340 /* Count the number of columns that will be added to the index
106341 ** and used to match WHERE clause constraints */
106342 nColumn = 0;
106343 pTable = pSrc->pTab;
106344 pWCEnd = &pWC->a[pWC->nTerm];
106345 pLoop = pLevel->pWLoop;
106346 idxCols = 0;
106347 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
106348 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
106349 int iCol = pTerm->u.leftColumn;
106350 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
106351 testcase( iCol==BMS );
106352 testcase( iCol==BMS-1 );
106353 if( (idxCols & cMask)==0 ){
106354 if( whereLoopResize(pParse->db, pLoop, nColumn+1) ) return;
106355 pLoop->aLTerm[nColumn++] = pTerm;
106356 idxCols |= cMask;
106357 }
106358 }
106359 }
106360 assert( nColumn>0 );
106361 pLoop->u.btree.nEq = pLoop->nLTerm = nColumn;
106362 pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
106363 | WHERE_TEMP_INDEX;
106364
106365 /* Count the number of additional columns needed to create a
106366 ** covering index. A "covering index" is an index that contains all
106367 ** columns that are needed by the query. With a covering index, the
106368 ** original table never needs to be accessed. Automatic indices must
106369 ** be a covering index because the index will not be updated if the
106370 ** original table changes and the index and table cannot both be used
106371 ** if they go out of sync.
106372 */
106373 extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
106374 mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
106375 testcase( pTable->nCol==BMS-1 );
106376 testcase( pTable->nCol==BMS-2 );
106377 for(i=0; i<mxBitCol; i++){
106378 if( extraCols & MASKBIT(i) ) nColumn++;
106379 }
106380 if( pSrc->colUsed & MASKBIT(BMS-1) ){
106381 nColumn += pTable->nCol - BMS + 1;
106382 }
106383 pLoop->wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY;
106384
106385 /* Construct the Index object to describe this index */
106386 nByte = sizeof(Index);
106387 nByte += nColumn*sizeof(int); /* Index.aiColumn */
106388 nByte += nColumn*sizeof(char*); /* Index.azColl */
106389 nByte += nColumn; /* Index.aSortOrder */
106390 pIdx = sqlite3DbMallocZero(pParse->db, nByte);
106391 if( pIdx==0 ) return;
106392 pLoop->u.btree.pIndex = pIdx;
106393 pIdx->azColl = (char**)&pIdx[1];
106394 pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
106395 pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
106396 pIdx->zName = "auto-index";
106397 pIdx->nColumn = nColumn;
@@ -106409,11 +106399,13 @@
106399 n = 0;
106400 idxCols = 0;
106401 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
106402 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
106403 int iCol = pTerm->u.leftColumn;
106404 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
106405 testcase( iCol==BMS-1 );
106406 testcase( iCol==BMS );
106407 if( (idxCols & cMask)==0 ){
106408 Expr *pX = pTerm->pExpr;
106409 idxCols |= cMask;
106410 pIdx->aiColumn[n] = pTerm->u.leftColumn;
106411 pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
@@ -106420,22 +106412,22 @@
106412 pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
106413 n++;
106414 }
106415 }
106416 }
106417 assert( (u32)n==pLoop->u.btree.nEq );
106418
106419 /* Add additional columns needed to make the automatic index into
106420 ** a covering index */
106421 for(i=0; i<mxBitCol; i++){
106422 if( extraCols & MASKBIT(i) ){
106423 pIdx->aiColumn[n] = i;
106424 pIdx->azColl[n] = "BINARY";
106425 n++;
106426 }
106427 }
106428 if( pSrc->colUsed & MASKBIT(BMS-1) ){
106429 for(i=BMS-1; i<pTable->nCol; i++){
106430 pIdx->aiColumn[n] = i;
106431 pIdx->azColl[n] = "BINARY";
106432 n++;
106433 }
@@ -106443,10 +106435,11 @@
106435 assert( n==nColumn );
106436
106437 /* Create the automatic index */
106438 pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
106439 assert( pLevel->iIdxCur>=0 );
106440 pLevel->iIdxCur = pParse->nTab++;
106441 sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
106442 (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
106443 VdbeComment((v, "for %s", pTable->zName));
106444
106445 /* Fill the automatic index with content */
@@ -106469,26 +106462,25 @@
106462 /*
106463 ** Allocate and populate an sqlite3_index_info structure. It is the
106464 ** responsibility of the caller to eventually release the structure
106465 ** by passing the pointer returned by this function to sqlite3_free().
106466 */
106467 static sqlite3_index_info *allocateIndexInfo(
106468 Parse *pParse,
106469 WhereClause *pWC,
106470 struct SrcList_item *pSrc,
106471 ExprList *pOrderBy
106472 ){
106473 int i, j;
106474 int nTerm;
106475 struct sqlite3_index_constraint *pIdxCons;
106476 struct sqlite3_index_orderby *pIdxOrderBy;
106477 struct sqlite3_index_constraint_usage *pUsage;
106478 WhereTerm *pTerm;
106479 int nOrderBy;
106480 sqlite3_index_info *pIdxInfo;
106481
 
 
106482 /* Count the number of possible WHERE clause constraints referring
106483 ** to this virtual table */
106484 for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
106485 if( pTerm->leftCursor != pSrc->iCursor ) continue;
106486 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
@@ -106520,11 +106512,10 @@
106512 pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
106513 + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
106514 + sizeof(*pIdxOrderBy)*nOrderBy );
106515 if( pIdxInfo==0 ){
106516 sqlite3ErrorMsg(pParse, "out of memory");
 
106517 return 0;
106518 }
106519
106520 /* Initialize the structure. The sqlite3_index_info structure contains
106521 ** many fields that are declared "const" to prevent xBestIndex from
@@ -106576,12 +106567,12 @@
106567 }
106568
106569 /*
106570 ** The table object reference passed as the second argument to this function
106571 ** must represent a virtual table. This function invokes the xBestIndex()
106572 ** method of the virtual table with the sqlite3_index_info object that
106573 ** comes in as the 3rd argument to this function.
106574 **
106575 ** If an error occurs, pParse is populated with an error message and a
106576 ** non-zero value is returned. Otherwise, 0 is returned and the output
106577 ** part of the sqlite3_index_info structure is left populated.
106578 **
@@ -106592,11 +106583,10 @@
106583 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
106584 sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
106585 int i;
106586 int rc;
106587
 
106588 TRACE_IDX_INPUTS(p);
106589 rc = pVtab->pModule->xBestIndex(pVtab, p);
106590 TRACE_IDX_OUTPUTS(p);
106591
106592 if( rc!=SQLITE_OK ){
@@ -106618,211 +106608,12 @@
106608 }
106609 }
106610
106611 return pParse->nErr;
106612 }
106613 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
106614
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106615
106616 #ifdef SQLITE_ENABLE_STAT3
106617 /*
106618 ** Estimate the location of a particular key among all keys in an
106619 ** index. Store the results in aStat as follows:
@@ -107060,11 +106851,11 @@
106851 Parse *pParse, /* Parsing & code generating context */
106852 Index *p, /* The index containing the range-compared column; "x" */
106853 int nEq, /* index into p->aCol[] of the range-compared column */
106854 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
106855 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
106856 WhereCost *pRangeDiv /* OUT: Reduce search space by this divisor */
106857 ){
106858 int rc = SQLITE_OK;
106859
106860 #ifdef SQLITE_ENABLE_STAT3
106861
@@ -107098,29 +106889,35 @@
106889 if( (pUpper->eOperator & WO_LE)!=0 ) iUpper += a[1];
106890 }
106891 sqlite3ValueFree(pRangeVal);
106892 }
106893 if( rc==SQLITE_OK ){
106894 WhereCost iBase = whereCost(p->aiRowEst[0]);
106895 if( iUpper>iLower ){
106896 iBase -= whereCost(iUpper - iLower);
 
106897 }
106898 *pRangeDiv = iBase;
106899 WHERETRACE(0x100, ("range scan regions: %u..%u div=%d\n",
106900 (u32)iLower, (u32)iUpper, *pRangeDiv));
106901 return SQLITE_OK;
106902 }
106903 }
106904 #else
106905 UNUSED_PARAMETER(pParse);
106906 UNUSED_PARAMETER(p);
106907 UNUSED_PARAMETER(nEq);
106908 #endif
106909 assert( pLower || pUpper );
106910 *pRangeDiv = 0;
106911 /* TUNING: Each inequality constraint reduces the search space 4-fold.
106912 ** A BETWEEN operator, therefore, reduces the search space 16-fold */
106913 if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ){
106914 *pRangeDiv += 20; assert( 20==whereCost(4) );
106915 }
106916 if( pUpper ){
106917 *pRangeDiv += 20; assert( 20==whereCost(4) );
106918 }
106919 return rc;
106920 }
106921
106922 #ifdef SQLITE_ENABLE_STAT3
106923 /*
@@ -107142,11 +106939,11 @@
106939 */
106940 static int whereEqualScanEst(
106941 Parse *pParse, /* Parsing & code generating context */
106942 Index *p, /* The index whose left-most column is pTerm */
106943 Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
106944 tRowcnt *pnRow /* Write the revised row estimate here */
106945 ){
106946 sqlite3_value *pRhs = 0; /* VALUE on right-hand side of pTerm */
106947 u8 aff; /* Column affinity */
106948 int rc; /* Subfunction return code */
106949 tRowcnt a[2]; /* Statistics */
@@ -107161,11 +106958,11 @@
106958 pRhs = sqlite3ValueNew(pParse->db);
106959 }
106960 if( pRhs==0 ) return SQLITE_NOTFOUND;
106961 rc = whereKeyStats(pParse, p, pRhs, 0, a);
106962 if( rc==SQLITE_OK ){
106963 WHERETRACE(0x100,("equality scan regions: %d\n", (int)a[1]));
106964 *pnRow = a[1];
106965 }
106966 whereEqualScanEst_cancel:
106967 sqlite3ValueFree(pRhs);
106968 return rc;
@@ -107191,16 +106988,16 @@
106988 */
106989 static int whereInScanEst(
106990 Parse *pParse, /* Parsing & code generating context */
106991 Index *p, /* The index whose left-most column is pTerm */
106992 ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
106993 tRowcnt *pnRow /* Write the revised row estimate here */
106994 ){
106995 int rc = SQLITE_OK; /* Subfunction return code */
106996 tRowcnt nEst; /* Number of rows for a single term */
106997 tRowcnt nRowEst = 0; /* New estimate of the number of rows */
106998 int i; /* Loop counter */
106999
107000 assert( p->aSample!=0 );
107001 for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
107002 nEst = p->aiRowEst[0];
107003 rc = whereEqualScanEst(pParse, p, pList->a[i].pExpr, &nEst);
@@ -107207,888 +107004,15 @@
107004 nRowEst += nEst;
107005 }
107006 if( rc==SQLITE_OK ){
107007 if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
107008 *pnRow = nRowEst;
107009 WHERETRACE(0x100,("IN row estimate: est=%g\n", nRowEst));
107010 }
107011 return rc;
107012 }
107013 #endif /* defined(SQLITE_ENABLE_STAT3) */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107014
107015 /*
107016 ** Disable a term in the WHERE clause. Except, do not disable the term
107017 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
107018 ** or USING clause of that join.
@@ -108183,10 +107107,11 @@
107107 static int codeEqualityTerm(
107108 Parse *pParse, /* The parsing context */
107109 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
107110 WhereLevel *pLevel, /* The level of the FROM clause we are working on */
107111 int iEq, /* Index of the equality term within this level */
107112 int bRev, /* True for reverse-order IN operations */
107113 int iTarget /* Attempt to leave results in this register */
107114 ){
107115 Expr *pX = pTerm->pExpr;
107116 Vdbe *v = pParse->pVdbe;
107117 int iReg; /* Register holding results */
@@ -108200,18 +107125,17 @@
107125 #ifndef SQLITE_OMIT_SUBQUERY
107126 }else{
107127 int eType;
107128 int iTab;
107129 struct InLoop *pIn;
107130 WhereLoop *pLoop = pLevel->pWLoop;
107131
107132 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
107133 && pLoop->u.btree.pIndex!=0
107134 && pLoop->u.btree.pIndex->aSortOrder[iEq]
107135 ){
107136 testcase( iEq==0 );
 
 
107137 testcase( bRev );
107138 bRev = !bRev;
107139 }
107140 assert( pX->op==TK_IN );
107141 iReg = iTarget;
@@ -108220,11 +107144,12 @@
107144 testcase( bRev );
107145 bRev = !bRev;
107146 }
107147 iTab = pX->iTable;
107148 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
107149 assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
107150 pLoop->wsFlags |= WHERE_IN_ABLE;
107151 if( pLevel->u.in.nIn==0 ){
107152 pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
107153 }
107154 pLevel->u.in.nIn++;
107155 pLevel->u.in.aInLoop =
@@ -108290,33 +107215,35 @@
107215 ** string in this example would be set to SQLITE_AFF_NONE.
107216 */
107217 static int codeAllEqualityTerms(
107218 Parse *pParse, /* Parsing context */
107219 WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
107220 int bRev, /* Reverse the order of IN operators */
 
107221 int nExtraReg, /* Number of extra registers to allocate */
107222 char **pzAff /* OUT: Set to point to affinity string */
107223 ){
107224 int nEq; /* The number of == or IN constraints to code */
107225 Vdbe *v = pParse->pVdbe; /* The vm under construction */
107226 Index *pIdx; /* The index being used for this loop */
 
107227 WhereTerm *pTerm; /* A single constraint term */
107228 WhereLoop *pLoop; /* The WhereLoop object */
107229 int j; /* Loop counter */
107230 int regBase; /* Base register */
107231 int nReg; /* Number of registers to allocate */
107232 char *zAff; /* Affinity string to return */
107233
107234 /* This module is only called on query plans that use an index. */
107235 pLoop = pLevel->pWLoop;
107236 assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
107237 nEq = pLoop->u.btree.nEq;
107238 pIdx = pLoop->u.btree.pIndex;
107239 assert( pIdx!=0 );
107240
107241 /* Figure out how many memory cells we will need then allocate them.
107242 */
107243 regBase = pParse->nMem + 1;
107244 nReg = pLoop->u.btree.nEq + nExtraReg;
107245 pParse->nMem += nReg;
107246
107247 zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
107248 if( !zAff ){
107249 pParse->db->mallocFailed = 1;
@@ -108325,18 +107252,17 @@
107252 /* Evaluate the equality constraints
107253 */
107254 assert( pIdx->nColumn>=nEq );
107255 for(j=0; j<nEq; j++){
107256 int r1;
107257 pTerm = pLoop->aLTerm[j];
107258 assert( pTerm!=0 );
 
107259 /* The following true for indices with redundant columns.
107260 ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
107261 testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
107262 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
107263 r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
107264 if( r1!=regBase+j ){
107265 if( nReg==1 ){
107266 sqlite3ReleaseTempReg(pParse, regBase);
107267 regBase = r1;
107268 }else{
@@ -108400,20 +107326,19 @@
107326 **
107327 ** The returned pointer points to memory obtained from sqlite3DbMalloc().
107328 ** It is the responsibility of the caller to free the buffer when it is
107329 ** no longer required.
107330 */
107331 static char *explainIndexRange(sqlite3 *db, WhereLoop *pLoop, Table *pTab){
107332 Index *pIndex = pLoop->u.btree.pIndex;
107333 int nEq = pLoop->u.btree.nEq;
 
107334 int i, j;
107335 Column *aCol = pTab->aCol;
107336 int *aiColumn = pIndex->aiColumn;
107337 StrAccum txt;
107338
107339 if( nEq==0 && (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
107340 return 0;
107341 }
107342 sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
107343 txt.db = db;
107344 sqlite3StrAccumAppend(&txt, " (", 2);
@@ -108420,15 +107345,15 @@
107345 for(i=0; i<nEq; i++){
107346 explainAppendTerm(&txt, i, aCol[aiColumn[i]].zName, "=");
107347 }
107348
107349 j = i;
107350 if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
107351 char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
107352 explainAppendTerm(&txt, i++, z, ">");
107353 }
107354 if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
107355 char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
107356 explainAppendTerm(&txt, i, z, "<");
107357 }
107358 sqlite3StrAccumAppend(&txt, ")", 1);
107359 return sqlite3StrAccumFinish(&txt);
@@ -108447,24 +107372,26 @@
107372 int iLevel, /* Value for "level" column of output */
107373 int iFrom, /* Value for "from" column of output */
107374 u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
107375 ){
107376 if( pParse->explain==2 ){
 
107377 struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
107378 Vdbe *v = pParse->pVdbe; /* VM being constructed */
107379 sqlite3 *db = pParse->db; /* Database handle */
107380 char *zMsg; /* Text to add to EQP output */
 
107381 int iId = pParse->iSelectId; /* Select id (left-most output column) */
107382 int isSearch; /* True for a SEARCH. False for SCAN. */
107383 WhereLoop *pLoop; /* The controlling WhereLoop object */
107384 u32 flags; /* Flags that describe this loop */
107385
107386 pLoop = pLevel->pWLoop;
107387 flags = pLoop->wsFlags;
107388 if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
107389
107390 isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
107391 || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
107392 || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
107393
107394 zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
107395 if( pItem->pSelect ){
107396 zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
107397 }else{
@@ -108472,47 +107399,42 @@
107399 }
107400
107401 if( pItem->zAlias ){
107402 zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
107403 }
107404 if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0
107405 && ALWAYS(pLoop->u.btree.pIndex!=0)
107406 ){
107407 char *zWhere = explainIndexRange(db, pLoop, pItem->pTab);
107408 zMsg = sqlite3MAppendf(db, zMsg, "%s USING %s%sINDEX%s%s%s", zMsg,
107409 ((flags & WHERE_TEMP_INDEX)?"AUTOMATIC ":""),
107410 ((flags & WHERE_IDX_ONLY)?"COVERING ":""),
107411 ((flags & WHERE_TEMP_INDEX)?"":" "),
107412 ((flags & WHERE_TEMP_INDEX)?"": pLoop->u.btree.pIndex->zName),
107413 zWhere
107414 );
107415 sqlite3DbFree(db, zWhere);
107416 }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
107417 zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
107418
107419 if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
107420 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
107421 }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
107422 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
107423 }else if( flags&WHERE_BTM_LIMIT ){
107424 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
107425 }else if( ALWAYS(flags&WHERE_TOP_LIMIT) ){
107426 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
107427 }
107428 }
107429 #ifndef SQLITE_OMIT_VIRTUALTABLE
107430 else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
 
107431 zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
107432 pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
107433 }
107434 #endif
107435 zMsg = sqlite3MAppendf(db, zMsg, "%s", zMsg);
 
 
 
 
 
 
107436 sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
107437 }
107438 }
107439 #else
107440 # define explainOneScan(u,v,w,x,y,z)
@@ -108524,19 +107446,19 @@
107446 ** implementation described by pWInfo.
107447 */
107448 static Bitmask codeOneLoopStart(
107449 WhereInfo *pWInfo, /* Complete information about the WHERE clause */
107450 int iLevel, /* Which level of pWInfo->a[] should be coded */
 
107451 Bitmask notReady /* Which tables are currently available */
107452 ){
107453 int j, k; /* Loop counters */
107454 int iCur; /* The VDBE cursor for the table */
107455 int addrNxt; /* Where to jump to continue with the next IN case */
107456 int omitTable; /* True if we use the index only */
107457 int bRev; /* True if we need to scan in reverse order */
107458 WhereLevel *pLevel; /* The where level to be coded */
107459 WhereLoop *pLoop; /* The WhereLoop object being coded */
107460 WhereClause *pWC; /* Decomposition of the entire WHERE clause */
107461 WhereTerm *pTerm; /* A WHERE clause term */
107462 Parse *pParse; /* Parsing context */
107463 Vdbe *v; /* The prepared stmt under constructions */
107464 struct SrcList_item *pTabItem; /* FROM clause term being coded */
@@ -108546,17 +107468,18 @@
107468 int iReleaseReg = 0; /* Temp register to free before returning */
107469 Bitmask newNotReady; /* Return value */
107470
107471 pParse = pWInfo->pParse;
107472 v = pParse->pVdbe;
107473 pWC = &pWInfo->sWC;
107474 pLevel = &pWInfo->a[iLevel];
107475 pLoop = pLevel->pWLoop;
107476 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
107477 iCur = pTabItem->iCursor;
107478 bRev = (pWInfo->revMask>>iLevel)&1;
107479 omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
107480 && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
107481 VdbeNoopComment((v, "Begin Join Loop %d", iLevel));
107482
107483 /* Create labels for the "break" and "continue" instructions
107484 ** for the current loop. Jump to addrBrk to break out of a loop.
107485 ** Jump to cont to go immediately to the next iteration of the
@@ -108589,51 +107512,41 @@
107512 sqlite3VdbeAddOp2(v, OP_If, regYield+1, addrBrk);
107513 pLevel->op = OP_Goto;
107514 }else
107515
107516 #ifndef SQLITE_OMIT_VIRTUALTABLE
107517 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
107518 /* Case 1: The table is a virtual-table. Use the VFilter and VNext
107519 ** to access the data.
107520 */
107521 int iReg; /* P3 Value for OP_VFilter */
107522 int addrNotFound;
107523 int nConstraint = pLoop->nLTerm;
 
 
 
 
 
107524
107525 sqlite3ExprCachePush(pParse);
107526 iReg = sqlite3GetTempRange(pParse, nConstraint+2);
107527 addrNotFound = pLevel->addrBrk;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107528 for(j=0; j<nConstraint; j++){
107529 int iTarget = iReg+j+2;
107530 pTerm = pLoop->aLTerm[j];
107531 if( pTerm==0 ) continue;
107532 if( pTerm->eOperator & WO_IN ){
107533 codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
107534 addrNotFound = pLevel->addrNxt;
107535 }else{
107536 sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
107537 }
107538 }
107539 sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
107540 sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
107541 sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
107542 pLoop->u.vtab.idxStr,
107543 pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
107544 pLoop->u.vtab.needFree = 0;
107545 for(j=0; j<nConstraint && j<16; j++){
107546 if( (pLoop->u.vtab.omitMask>>j)&1 ){
107547 disableTerm(pLevel, pLoop->aLTerm[j]);
107548 }
107549 }
107550 pLevel->op = OP_VNext;
107551 pLevel->p1 = iCur;
107552 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
@@ -108640,41 +107553,49 @@
107553 sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
107554 sqlite3ExprCachePop(pParse, 1);
107555 }else
107556 #endif /* SQLITE_OMIT_VIRTUALTABLE */
107557
107558 if( (pLoop->wsFlags & WHERE_IPK)!=0
107559 && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
107560 ){
107561 /* Case 2: We can directly reference a single row using an
107562 ** equality comparison against the ROWID field. Or
107563 ** we reference multiple rows using a "rowid IN (...)"
107564 ** construct.
107565 */
107566 assert( pLoop->u.btree.nEq==1 );
107567 iReleaseReg = sqlite3GetTempReg(pParse);
107568 pTerm = pLoop->aLTerm[0];
107569 assert( pTerm!=0 );
107570 assert( pTerm->pExpr!=0 );
107571 assert( omitTable==0 );
107572 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
107573 iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
107574 addrNxt = pLevel->addrNxt;
107575 sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
107576 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
107577 sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
107578 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
107579 VdbeComment((v, "pk"));
107580 pLevel->op = OP_Noop;
107581 }else if( (pLoop->wsFlags & WHERE_IPK)!=0
107582 && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
107583 ){
107584 /* Case 3: We have an inequality comparison against the ROWID field.
107585 */
107586 int testOp = OP_Noop;
107587 int start;
107588 int memEndValue = 0;
107589 WhereTerm *pStart, *pEnd;
107590
107591 assert( omitTable==0 );
107592 j = 0;
107593 pStart = pEnd = 0;
107594 if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
107595 if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
107596 assert( pStart!=0 || pEnd!=0 );
107597 if( bRev ){
107598 pTerm = pStart;
107599 pStart = pEnd;
107600 pEnd = pTerm;
107601 }
@@ -108725,24 +107646,20 @@
107646 }
107647 start = sqlite3VdbeCurrentAddr(v);
107648 pLevel->op = bRev ? OP_Prev : OP_Next;
107649 pLevel->p1 = iCur;
107650 pLevel->p2 = start;
107651 assert( pLevel->p5==0 );
 
 
 
 
107652 if( testOp!=OP_Noop ){
107653 iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
107654 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
107655 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
107656 sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
107657 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
107658 }
107659 }else if( pLoop->wsFlags & WHERE_INDEXED ){
107660 /* Case 4: A scan using an index.
107661 **
107662 ** The WHERE clause may contain zero or more equality
107663 ** terms ("==" or "IN" operators) that refer to the N
107664 ** left-most columns of the index. It may also contain
107665 ** inequality constraints (>, <, >= or <=) on the indexed
@@ -108784,12 +107701,12 @@
107701 static const u8 aEndOp[] = {
107702 OP_Noop, /* 0: (!end_constraints) */
107703 OP_IdxGE, /* 1: (end_constraints && !bRev) */
107704 OP_IdxLT /* 2: (end_constraints && bRev) */
107705 };
107706 int nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
107707 int isMinQuery = 0; /* If this is an optimized SELECT min(x).. */
107708 int regBase; /* Base register holding constraint values */
107709 int r1; /* Temp register */
107710 WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
107711 WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
107712 int startEq; /* True if range start uses ==, >= or <= */
@@ -108801,24 +107718,23 @@
107718 int nExtraReg = 0; /* Number of extra registers needed */
107719 int op; /* Instruction opcode */
107720 char *zStartAff; /* Affinity for start of range constraint */
107721 char *zEndAff; /* Affinity for end of range constraint */
107722
107723 pIdx = pLoop->u.btree.pIndex;
107724 iIdxCur = pLevel->iIdxCur;
 
107725
107726 /* If this loop satisfies a sort order (pOrderBy) request that
107727 ** was passed to this function to implement a "SELECT min(x) ..."
107728 ** query, then the caller will only allow the loop to run for
107729 ** a single iteration. This means that the first row returned
107730 ** should not have a NULL value stored in 'x'. If column 'x' is
107731 ** the first one after the nEq equality constraints in the index,
107732 ** this requires some special handling.
107733 */
107734 if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
107735 && (pWInfo->bOBSat!=0)
107736 && (pIdx->nColumn>nEq)
107737 ){
107738 /* assert( pOrderBy->nExpr==1 ); */
107739 /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
107740 isMinQuery = 1;
@@ -108826,26 +107742,25 @@
107742 }
107743
107744 /* Find any inequality constraint terms for the start and end
107745 ** of the range.
107746 */
107747 j = nEq;
107748 if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
107749 pRangeStart = pLoop->aLTerm[j++];
107750 nExtraReg = 1;
107751 }
107752 if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
107753 pRangeEnd = pLoop->aLTerm[j++];
107754 nExtraReg = 1;
107755 }
107756
107757 /* Generate code to evaluate all constraint terms using == or IN
107758 ** and store the values of those terms in an array of registers
107759 ** starting at regBase.
107760 */
107761 regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
 
 
107762 zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
107763 addrNxt = pLevel->addrNxt;
107764
107765 /* If we are doing a reverse order scan on an ascending index, or
107766 ** a forward order scan on a descending index, interchange the
@@ -108855,14 +107770,14 @@
107770 || (bRev && pIdx->nColumn==nEq)
107771 ){
107772 SWAP(WhereTerm *, pRangeEnd, pRangeStart);
107773 }
107774
107775 testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
107776 testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
107777 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
107778 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
107779 startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
107780 endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
107781 start_constraints = pRangeStart || nEq>0;
107782
107783 /* Seek the index cursor to the start of the range. */
@@ -108948,13 +107863,13 @@
107863 /* If there are inequality constraints, check that the value
107864 ** of the table column that the inequality contrains is not NULL.
107865 ** If it is, jump to the next iteration of the loop.
107866 */
107867 r1 = sqlite3GetTempReg(pParse);
107868 testcase( pLoop->wsFlags & WHERE_BTM_LIMIT );
107869 testcase( pLoop->wsFlags & WHERE_TOP_LIMIT );
107870 if( (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
107871 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
107872 sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
107873 }
107874 sqlite3ReleaseTempReg(pParse, r1);
107875
@@ -108969,28 +107884,28 @@
107884 }
107885
107886 /* Record the instruction used to terminate the loop. Disable
107887 ** WHERE clause terms made redundant by the index range scan.
107888 */
107889 if( pLoop->wsFlags & WHERE_ONEROW ){
107890 pLevel->op = OP_Noop;
107891 }else if( bRev ){
107892 pLevel->op = OP_Prev;
107893 }else{
107894 pLevel->op = OP_Next;
107895 }
107896 pLevel->p1 = iIdxCur;
107897 if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
107898 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
107899 }else{
107900 assert( pLevel->p5==0 );
107901 }
107902 }else
107903
107904 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
107905 if( pLoop->wsFlags & WHERE_MULTI_OR ){
107906 /* Case 5: Two or more separately indexed terms connected by OR
107907 **
107908 ** Example:
107909 **
107910 ** CREATE TABLE t1(a,b,c,d);
107911 ** CREATE INDEX i1 ON t1(a);
@@ -109039,11 +107954,11 @@
107954 int iRetInit; /* Address of regReturn init */
107955 int untestedTerms = 0; /* Some terms not completely tested */
107956 int ii; /* Loop counter */
107957 Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
107958
107959 pTerm = pLoop->aLTerm[0];
107960 assert( pTerm!=0 );
107961 assert( pTerm->eOperator & WO_OR );
107962 assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
107963 pOrWc = &pTerm->u.pOrInfo->wc;
107964 pLevel->op = OP_Return;
@@ -109058,11 +107973,11 @@
107973 struct SrcList_item *origSrc; /* Original list of tables */
107974 nNotReady = pWInfo->nLevel - iLevel - 1;
107975 pOrTab = sqlite3StackAllocRaw(pParse->db,
107976 sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
107977 if( pOrTab==0 ) return notReady;
107978 pOrTab->nAlloc = (u8)(nNotReady + 1);
107979 pOrTab->nSrc = pOrTab->nAlloc;
107980 memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
107981 origSrc = pWInfo->pTabList->a;
107982 for(k=1; k<=nNotReady; k++){
107983 memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
@@ -109080,11 +107995,11 @@
107995 ** over the top of the loop into the body of it. In this case the
107996 ** correct response for the end-of-loop code (the OP_Return) is to
107997 ** fall through to the next instruction, just as an OP_Next does if
107998 ** called on an uninitialized cursor.
107999 */
108000 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
108001 regRowset = ++pParse->nMem;
108002 regRowid = ++pParse->nMem;
108003 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
108004 }
108005 iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
@@ -109131,15 +108046,15 @@
108046 pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
108047 WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
108048 WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY, iCovCur);
108049 assert( pSubWInfo || pParse->nErr || pParse->db->mallocFailed );
108050 if( pSubWInfo ){
108051 WhereLoop *pSubLoop;
108052 explainOneScan(
108053 pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
108054 );
108055 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
108056 int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
108057 int r;
108058 r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
108059 regRowid, 0);
108060 sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
@@ -109164,17 +108079,17 @@
108079 ** processed or the index is the same as that used by all previous
108080 ** terms, set pCov to the candidate covering index. Otherwise, set
108081 ** pCov to NULL to indicate that no candidate covering index will
108082 ** be available.
108083 */
108084 pSubLoop = pSubWInfo->a[0].pWLoop;
108085 assert( (pSubLoop->wsFlags & WHERE_TEMP_INDEX)==0 );
108086 if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
108087 && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
108088 ){
108089 assert( pSubWInfo->a[0].iIdxCur==iCovCur );
108090 pCov = pSubLoop->u.btree.pIndex;
108091 }else{
108092 pCov = 0;
108093 }
108094
108095 /* Finish the loop through table entries that match term pOrTerm. */
@@ -109196,23 +108111,22 @@
108111 if( !untestedTerms ) disableTerm(pLevel, pTerm);
108112 }else
108113 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
108114
108115 {
108116 /* Case 6: There is no usable index. We must do a complete
108117 ** scan of the entire table.
108118 */
108119 static const u8 aStep[] = { OP_Next, OP_Prev };
108120 static const u8 aStart[] = { OP_Rewind, OP_Last };
108121 assert( bRev==0 || bRev==1 );
 
108122 pLevel->op = aStep[bRev];
108123 pLevel->p1 = iCur;
108124 pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
108125 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
108126 }
108127 newNotReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur);
108128
108129 /* Insert code to test every subexpression that can be completely
108130 ** computed using the current set of tables.
108131 **
108132 ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
@@ -109258,10 +108172,12 @@
108172 assert( !ExprHasProperty(pE, EP_FromJoin) );
108173 assert( (pTerm->prereqRight & newNotReady)!=0 );
108174 pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
108175 if( pAlt==0 ) continue;
108176 if( pAlt->wtFlags & (TERM_CODED) ) continue;
108177 testcase( pAlt->eOperator & WO_EQ );
108178 testcase( pAlt->eOperator & WO_IN );
108179 VdbeNoopComment((v, "begin transitive constraint"));
108180 sEq = *pAlt->pExpr;
108181 sEq.pLeft = pE->pLeft;
108182 sqlite3ExprIfFalse(pParse, &sEq, addrCont, SQLITE_JUMPIFNULL);
108183 }
@@ -109290,51 +108206,1562 @@
108206 sqlite3ReleaseTempReg(pParse, iReleaseReg);
108207
108208 return newNotReady;
108209 }
108210
108211 #ifdef WHERETRACE_ENABLED
108212 /*
108213 ** Print a WhereLoop object for debugging purposes
 
 
 
108214 */
108215 static void whereLoopPrint(WhereLoop *p, SrcList *pTabList){
108216 int nb = 1+(pTabList->nSrc+7)/8;
108217 struct SrcList_item *pItem = pTabList->a + p->iTab;
108218 Table *pTab = pItem->pTab;
108219 sqlite3DebugPrintf("%c %2d.%0*llx.%0*llx", p->cId,
108220 p->iTab, nb, p->maskSelf, nb, p->prereq);
108221 sqlite3DebugPrintf(" %8s",
108222 pItem->zAlias ? pItem->zAlias : pTab->zName);
108223 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
108224 if( p->u.btree.pIndex ){
108225 const char *zName = p->u.btree.pIndex->zName;
108226 if( zName==0 ) zName = "ipk";
108227 if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
108228 int i = sqlite3Strlen30(zName) - 1;
108229 while( zName[i]!='_' ) i--;
108230 zName += i;
108231 }
108232 sqlite3DebugPrintf(".%-12s %2d", zName, p->u.btree.nEq);
108233 }else{
108234 sqlite3DebugPrintf("%16s","");
108235 }
108236 }else{
108237 char *z;
108238 if( p->u.vtab.idxStr ){
108239 z = sqlite3_mprintf("(%d,\"%s\",%x)",
108240 p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
108241 }else{
108242 z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
108243 }
108244 sqlite3DebugPrintf(" %-15s", z);
108245 sqlite3_free(z);
108246 }
108247 sqlite3DebugPrintf(" fg %05x N %d", p->wsFlags, p->nLTerm);
108248 sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
108249 }
108250 #endif
108251
108252 /*
108253 ** Convert bulk memory into a valid WhereLoop that can be passed
108254 ** to whereLoopClear harmlessly.
108255 */
108256 static void whereLoopInit(WhereLoop *p){
108257 p->aLTerm = p->aLTermSpace;
108258 p->nLTerm = 0;
108259 p->nLSlot = ArraySize(p->aLTermSpace);
108260 p->wsFlags = 0;
108261 }
108262
108263 /*
108264 ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
108265 */
108266 static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
108267 if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_TEMP_INDEX) ){
108268 if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
108269 sqlite3_free(p->u.vtab.idxStr);
108270 p->u.vtab.needFree = 0;
108271 p->u.vtab.idxStr = 0;
108272 }else if( (p->wsFlags & WHERE_TEMP_INDEX)!=0 && p->u.btree.pIndex!=0 ){
108273 sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
108274 sqlite3DbFree(db, p->u.btree.pIndex);
108275 p->u.btree.pIndex = 0;
108276 }
108277 }
108278 }
108279
108280 /*
108281 ** Deallocate internal memory used by a WhereLoop object
108282 */
108283 static void whereLoopClear(sqlite3 *db, WhereLoop *p){
108284 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
108285 whereLoopClearUnion(db, p);
108286 whereLoopInit(p);
108287 }
108288
108289 /*
108290 ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
108291 */
108292 static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
108293 WhereTerm **paNew;
108294 if( p->nLSlot>=n ) return SQLITE_OK;
108295 n = (n+7)&~7;
108296 paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
108297 if( paNew==0 ) return SQLITE_NOMEM;
108298 memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
108299 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
108300 p->aLTerm = paNew;
108301 p->nLSlot = n;
108302 return SQLITE_OK;
108303 }
108304
108305 /*
108306 ** Transfer content from the second pLoop into the first.
108307 */
108308 static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
108309 if( whereLoopResize(db, pTo, pFrom->nLTerm) ) return SQLITE_NOMEM;
108310 whereLoopClearUnion(db, pTo);
108311 memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
108312 memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
108313 if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
108314 pFrom->u.vtab.needFree = 0;
108315 }else if( (pFrom->wsFlags & WHERE_TEMP_INDEX)!=0 ){
108316 pFrom->u.btree.pIndex = 0;
108317 }
108318 return SQLITE_OK;
108319 }
108320
108321 /*
108322 ** Delete a WhereLoop object
108323 */
108324 static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
108325 whereLoopClear(db, p);
108326 sqlite3DbFree(db, p);
108327 }
108328
108329 /*
108330 ** Free a WhereInfo structure
108331 */
108332 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
108333 if( ALWAYS(pWInfo) ){
108334 whereClauseClear(&pWInfo->sWC);
108335 while( pWInfo->pLoops ){
108336 WhereLoop *p = pWInfo->pLoops;
108337 pWInfo->pLoops = p->pNextLoop;
108338 whereLoopDelete(db, p);
108339 }
 
 
 
 
 
 
 
 
 
 
 
 
 
108340 sqlite3DbFree(db, pWInfo);
108341 }
108342 }
108343
108344 /*
108345 ** Insert or replace a WhereLoop entry using the template supplied.
108346 **
108347 ** An existing WhereLoop entry might be overwritten if the new template
108348 ** is better and has fewer dependencies. Or the template will be ignored
108349 ** and no insert will occur if an existing WhereLoop is faster and has
108350 ** fewer dependencies than the template. Otherwise a new WhereLoop is
108351 ** added based on the template.
108352 **
108353 ** If pBuilder->pBest is not NULL then we only care about the very
108354 ** best template and that template should be stored in pBuilder->pBest.
108355 ** If pBuilder->pBest is NULL then a list of the best templates are stored
108356 ** in pBuilder->pWInfo->pLoops.
108357 **
108358 ** When accumulating multiple loops (when pBuilder->pBest is NULL) we
108359 ** still might overwrite similar loops with the new template if the
108360 ** template is better. Loops may be overwritten if the following
108361 ** conditions are met:
108362 **
108363 ** (1) They have the same iTab.
108364 ** (2) They have the same iSortIdx.
108365 ** (3) The template has same or fewer dependencies than the current loop
108366 ** (4) The template has the same or lower cost than the current loop
108367 ** (5) The template uses more terms of the same index but has no additional
108368 ** dependencies
108369 */
108370 static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
108371 WhereLoop **ppPrev, *p, *pNext = 0;
108372 WhereInfo *pWInfo = pBuilder->pWInfo;
108373 sqlite3 *db = pWInfo->pParse->db;
108374
108375 /* If pBuilder->pBest is defined, then only keep track of the single
108376 ** best WhereLoop. pBuilder->pBest->maskSelf==0 indicates that no
108377 ** prior WhereLoops have been evaluated and that the current pTemplate
108378 ** is therefore the first and hence the best and should be retained.
108379 */
108380 if( (p = pBuilder->pBest)!=0 ){
108381 if( p->maskSelf!=0 ){
108382 WhereCost rCost = whereCostAdd(p->rRun,p->rSetup);
108383 WhereCost rTemplate = whereCostAdd(pTemplate->rRun,pTemplate->rSetup);
108384 if( rCost < rTemplate ){
108385 testcase( rCost==rTemplate-1 );
108386 goto whereLoopInsert_noop;
108387 }
108388 if( rCost==rTemplate && (p->prereq & pTemplate->prereq)==p->prereq ){
108389 goto whereLoopInsert_noop;
108390 }
108391 }
108392 #if WHERETRACE_ENABLED
108393 if( sqlite3WhereTrace & 0x8 ){
108394 sqlite3DebugPrintf(p->maskSelf==0 ? "ins-init: " : "ins-best: ");
108395 whereLoopPrint(pTemplate, pWInfo->pTabList);
108396 }
108397 #endif
108398 whereLoopXfer(db, p, pTemplate);
108399 return SQLITE_OK;
108400 }
108401
108402 /* Search for an existing WhereLoop to overwrite, or which takes
108403 ** priority over pTemplate.
108404 */
108405 for(ppPrev=&pWInfo->pLoops, p=*ppPrev; p; ppPrev=&p->pNextLoop, p=*ppPrev){
108406 if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
108407 /* If either the iTab or iSortIdx values for two WhereLoop are different
108408 ** then those WhereLoops need to be considered separately. Neither is
108409 ** a candidate to replace the other. */
108410 continue;
108411 }
108412 /* In the current implementation, the rSetup value is either zero
108413 ** or the cost of building an automatic index (NlogN) and the NlogN
108414 ** is the same for compatible WhereLoops. */
108415 assert( p->rSetup==0 || pTemplate->rSetup==0
108416 || p->rSetup==pTemplate->rSetup );
108417
108418 /* whereLoopAddBtree() always generates and inserts the automatic index
108419 ** case first. Hence compatible candidate WhereLoops never have a larger
108420 ** rSetup. Call this SETUP-INVARIANT */
108421 assert( p->rSetup>=pTemplate->rSetup );
108422
108423 if( (p->prereq & pTemplate->prereq)==p->prereq
108424 && p->rSetup<=pTemplate->rSetup
108425 && p->rRun<=pTemplate->rRun
108426 ){
108427 /* This branch taken when p is equal or better than pTemplate in
108428 ** all of (1) dependences (2) setup-cost, and (3) run-cost. */
108429 assert( p->rSetup==pTemplate->rSetup );
108430 if( p->nLTerm<pTemplate->nLTerm
108431 && (p->wsFlags & WHERE_INDEXED)!=0
108432 && (pTemplate->wsFlags & WHERE_INDEXED)!=0
108433 && p->u.btree.pIndex==pTemplate->u.btree.pIndex
108434 && p->prereq==pTemplate->prereq
108435 ){
108436 /* Overwrite an existing WhereLoop with an similar one that uses
108437 ** more terms of the index */
108438 pNext = p->pNextLoop;
108439 break;
108440 }else{
108441 /* pTemplate is not helpful.
108442 ** Return without changing or adding anything */
108443 goto whereLoopInsert_noop;
108444 }
108445 }
108446 if( (p->prereq & pTemplate->prereq)==pTemplate->prereq
108447 && p->rRun>=pTemplate->rRun
108448 && ALWAYS(p->rSetup>=pTemplate->rSetup) /* See SETUP-INVARIANT above */
108449 ){
108450 /* Overwrite an existing WhereLoop with a better one: one that is
108451 ** better at one of (1) dependences, (2) setup-cost, or (3) run-cost
108452 ** and is no worse in any of those categories. */
108453 pNext = p->pNextLoop;
108454 break;
108455 }
108456 }
108457
108458 /* If we reach this point it means that either p[] should be overwritten
108459 ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
108460 ** WhereLoop and insert it.
108461 */
108462 #if WHERETRACE_ENABLED
108463 if( sqlite3WhereTrace & 0x8 ){
108464 if( p!=0 ){
108465 sqlite3DebugPrintf("ins-del: ");
108466 whereLoopPrint(p, pWInfo->pTabList);
108467 }
108468 sqlite3DebugPrintf("ins-new: ");
108469 whereLoopPrint(pTemplate, pWInfo->pTabList);
108470 }
108471 #endif
108472 if( p==0 ){
108473 p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
108474 if( p==0 ) return SQLITE_NOMEM;
108475 whereLoopInit(p);
108476 }
108477 whereLoopXfer(db, p, pTemplate);
108478 p->pNextLoop = pNext;
108479 *ppPrev = p;
108480 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
108481 Index *pIndex = p->u.btree.pIndex;
108482 if( pIndex && pIndex->tnum==0 ){
108483 p->u.btree.pIndex = 0;
108484 }
108485 }
108486 return SQLITE_OK;
108487
108488 /* Jump here if the insert is a no-op */
108489 whereLoopInsert_noop:
108490 #if WHERETRACE_ENABLED
108491 if( sqlite3WhereTrace & 0x8 ){
108492 sqlite3DebugPrintf(pBuilder->pBest ? "ins-skip: " : "ins-noop: ");
108493 whereLoopPrint(pTemplate, pWInfo->pTabList);
108494 }
108495 #endif
108496 return SQLITE_OK;
108497 }
108498
108499 /*
108500 ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the index pIndex.
108501 ** Try to match one more.
108502 **
108503 ** If pProbe->tnum==0, that means pIndex is a fake index used for the
108504 ** INTEGER PRIMARY KEY.
108505 */
108506 static int whereLoopAddBtreeIndex(
108507 WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
108508 struct SrcList_item *pSrc, /* FROM clause term being analyzed */
108509 Index *pProbe, /* An index on pSrc */
108510 WhereCost nInMul /* log(Number of iterations due to IN) */
108511 ){
108512 WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
108513 Parse *pParse = pWInfo->pParse; /* Parsing context */
108514 sqlite3 *db = pParse->db; /* Database connection malloc context */
108515 WhereLoop *pNew; /* Template WhereLoop under construction */
108516 WhereTerm *pTerm; /* A WhereTerm under consideration */
108517 int opMask; /* Valid operators for constraints */
108518 WhereScan scan; /* Iterator for WHERE terms */
108519 Bitmask saved_prereq; /* Original value of pNew->prereq */
108520 u16 saved_nLTerm; /* Original value of pNew->nLTerm */
108521 int saved_nEq; /* Original value of pNew->u.btree.nEq */
108522 u32 saved_wsFlags; /* Original value of pNew->wsFlags */
108523 WhereCost saved_nOut; /* Original value of pNew->nOut */
108524 int iCol; /* Index of the column in the table */
108525 int rc = SQLITE_OK; /* Return code */
108526 WhereCost nRowEst; /* Estimated index selectivity */
108527 WhereCost rLogSize; /* Logarithm of table size */
108528 WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
108529
108530 pNew = pBuilder->pNew;
108531 if( db->mallocFailed ) return SQLITE_NOMEM;
108532
108533 assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
108534 assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
108535 if( pNew->wsFlags & WHERE_BTM_LIMIT ){
108536 opMask = WO_LT|WO_LE;
108537 }else if( pProbe->tnum<=0 || (pSrc->jointype & JT_LEFT)!=0 ){
108538 opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
108539 }else{
108540 opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE;
108541 }
108542 if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
108543
108544 assert( pNew->u.btree.nEq<=pProbe->nColumn );
108545 if( pNew->u.btree.nEq < pProbe->nColumn ){
108546 iCol = pProbe->aiColumn[pNew->u.btree.nEq];
108547 nRowEst = whereCost(pProbe->aiRowEst[pNew->u.btree.nEq+1]);
108548 if( nRowEst==0 && pProbe->onError==OE_None ) nRowEst = 1;
108549 }else{
108550 iCol = -1;
108551 nRowEst = 0;
108552 }
108553 pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
108554 opMask, pProbe);
108555 saved_nEq = pNew->u.btree.nEq;
108556 saved_nLTerm = pNew->nLTerm;
108557 saved_wsFlags = pNew->wsFlags;
108558 saved_prereq = pNew->prereq;
108559 saved_nOut = pNew->nOut;
108560 pNew->rSetup = 0;
108561 rLogSize = estLog(whereCost(pProbe->aiRowEst[0]));
108562 for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
108563 int nIn = 0;
108564 if( pTerm->prereqRight & pNew->maskSelf ) continue;
108565 pNew->wsFlags = saved_wsFlags;
108566 pNew->u.btree.nEq = saved_nEq;
108567 pNew->nLTerm = saved_nLTerm;
108568 if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
108569 pNew->aLTerm[pNew->nLTerm++] = pTerm;
108570 pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
108571 pNew->rRun = rLogSize; /* Baseline cost is log2(N). Adjustments below */
108572 if( pTerm->eOperator & WO_IN ){
108573 Expr *pExpr = pTerm->pExpr;
108574 pNew->wsFlags |= WHERE_COLUMN_IN;
108575 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
108576 /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
108577 nIn = 46; assert( 46==whereCost(25) );
108578 }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
108579 /* "x IN (value, value, ...)" */
108580 nIn = whereCost(pExpr->x.pList->nExpr);
108581 }
108582 pNew->rRun += nIn;
108583 pNew->u.btree.nEq++;
108584 pNew->nOut = nRowEst + nInMul + nIn;
108585 }else if( pTerm->eOperator & (WO_EQ) ){
108586 assert( (pNew->wsFlags & (WHERE_COLUMN_NULL|WHERE_COLUMN_IN))!=0
108587 || nInMul==0 );
108588 pNew->wsFlags |= WHERE_COLUMN_EQ;
108589 if( iCol<0
108590 || (pProbe->onError!=OE_None && nInMul==0
108591 && pNew->u.btree.nEq==pProbe->nColumn-1)
108592 ){
108593 assert( (pNew->wsFlags & WHERE_COLUMN_IN)==0 || iCol<0 );
108594 pNew->wsFlags |= WHERE_ONEROW;
108595 }
108596 pNew->u.btree.nEq++;
108597 pNew->nOut = nRowEst + nInMul;
108598 }else if( pTerm->eOperator & (WO_ISNULL) ){
108599 pNew->wsFlags |= WHERE_COLUMN_NULL;
108600 pNew->u.btree.nEq++;
108601 /* TUNING: IS NULL selects 2 rows */
108602 nIn = 10; assert( 10==whereCost(2) );
108603 pNew->nOut = nRowEst + nInMul + nIn;
108604 }else if( pTerm->eOperator & (WO_GT|WO_GE) ){
108605 testcase( pTerm->eOperator & WO_GT );
108606 testcase( pTerm->eOperator & WO_GE );
108607 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
108608 pBtm = pTerm;
108609 pTop = 0;
108610 }else{
108611 assert( pTerm->eOperator & (WO_LT|WO_LE) );
108612 testcase( pTerm->eOperator & WO_LT );
108613 testcase( pTerm->eOperator & WO_LE );
108614 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
108615 pTop = pTerm;
108616 pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
108617 pNew->aLTerm[pNew->nLTerm-2] : 0;
108618 }
108619 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
108620 /* Adjust nOut and rRun for STAT3 range values */
108621 WhereCost rDiv;
108622 whereRangeScanEst(pParse, pProbe, pNew->u.btree.nEq,
108623 pBtm, pTop, &rDiv);
108624 pNew->nOut = saved_nOut>rDiv+10 ? saved_nOut - rDiv : 10;
108625 }
108626 #ifdef SQLITE_ENABLE_STAT3
108627 if( pNew->u.btree.nEq==1 && pProbe->nSample ){
108628 tRowcnt nOut = 0;
108629 if( (pTerm->eOperator & (WO_EQ|WO_ISNULL))!=0 ){
108630 testcase( pTerm->eOperator & WO_EQ );
108631 testcase( pTerm->eOperator & WO_ISNULL );
108632 rc = whereEqualScanEst(pParse, pProbe, pTerm->pExpr->pRight, &nOut);
108633 }else if( (pTerm->eOperator & WO_IN)
108634 && !ExprHasProperty(pTerm->pExpr, EP_xIsSelect) ){
108635 rc = whereInScanEst(pParse, pProbe, pTerm->pExpr->x.pList, &nOut);
108636 }
108637 if( rc==SQLITE_OK ) pNew->nOut = whereCost(nOut);
108638 }
108639 #endif
108640 if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
108641 /* Each row involves a step of the index, then a binary search of
108642 ** the main table */
108643 pNew->rRun = whereCostAdd(pNew->rRun, rLogSize>27 ? rLogSize-17 : 10);
108644 }
108645 /* Step cost for each output row */
108646 pNew->rRun = whereCostAdd(pNew->rRun, pNew->nOut);
108647 /* TBD: Adjust nOut for additional constraints */
108648 rc = whereLoopInsert(pBuilder, pNew);
108649 if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
108650 && pNew->u.btree.nEq<(pProbe->nColumn + (pProbe->zName!=0))
108651 ){
108652 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
108653 }
108654 }
108655 pNew->prereq = saved_prereq;
108656 pNew->u.btree.nEq = saved_nEq;
108657 pNew->wsFlags = saved_wsFlags;
108658 pNew->nOut = saved_nOut;
108659 pNew->nLTerm = saved_nLTerm;
108660 return rc;
108661 }
108662
108663 /*
108664 ** Return True if it is possible that pIndex might be useful in
108665 ** implementing the ORDER BY clause in pBuilder.
108666 **
108667 ** Return False if pBuilder does not contain an ORDER BY clause or
108668 ** if there is no way for pIndex to be useful in implementing that
108669 ** ORDER BY clause.
108670 */
108671 static int indexMightHelpWithOrderBy(
108672 WhereLoopBuilder *pBuilder,
108673 Index *pIndex,
108674 int iCursor
108675 ){
108676 ExprList *pOB;
108677 int ii, jj;
108678
108679 if( pIndex->bUnordered ) return 0;
108680 if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
108681 for(ii=0; ii<pOB->nExpr; ii++){
108682 Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
108683 if( pExpr->op!=TK_COLUMN ) return 0;
108684 if( pExpr->iTable==iCursor ){
108685 for(jj=0; jj<pIndex->nColumn; jj++){
108686 if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
108687 }
108688 }
108689 }
108690 return 0;
108691 }
108692
108693 /*
108694 ** Return a bitmask where 1s indicate that the corresponding column of
108695 ** the table is used by an index. Only the first 63 columns are considered.
108696 */
108697 static Bitmask columnsInIndex(Index *pIdx){
108698 Bitmask m = 0;
108699 int j;
108700 for(j=pIdx->nColumn-1; j>=0; j--){
108701 int x = pIdx->aiColumn[j];
108702 testcase( x==BMS-1 );
108703 testcase( x==BMS-2 );
108704 if( x<BMS-1 ) m |= MASKBIT(x);
108705 }
108706 return m;
108707 }
108708
108709
108710 /*
108711 ** Add all WhereLoop objects a single table of the join were the table
108712 ** is idenfied by pBuilder->pNew->iTab. That table is guaranteed to be
108713 ** a b-tree table, not a virtual table.
108714 */
108715 static int whereLoopAddBtree(
108716 WhereLoopBuilder *pBuilder, /* WHERE clause information */
108717 Bitmask mExtra /* Extra prerequesites for using this table */
108718 ){
108719 WhereInfo *pWInfo; /* WHERE analysis context */
108720 Index *pProbe; /* An index we are evaluating */
108721 Index sPk; /* A fake index object for the primary key */
108722 tRowcnt aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
108723 int aiColumnPk = -1; /* The aColumn[] value for the sPk index */
108724 SrcList *pTabList; /* The FROM clause */
108725 struct SrcList_item *pSrc; /* The FROM clause btree term to add */
108726 WhereLoop *pNew; /* Template WhereLoop object */
108727 int rc = SQLITE_OK; /* Return code */
108728 int iSortIdx = 1; /* Index number */
108729 int b; /* A boolean value */
108730 WhereCost rSize; /* number of rows in the table */
108731 WhereCost rLogSize; /* Logarithm of the number of rows in the table */
108732
108733 pNew = pBuilder->pNew;
108734 pWInfo = pBuilder->pWInfo;
108735 pTabList = pWInfo->pTabList;
108736 pSrc = pTabList->a + pNew->iTab;
108737 assert( !IsVirtual(pSrc->pTab) );
108738
108739 if( pSrc->pIndex ){
108740 /* An INDEXED BY clause specifies a particular index to use */
108741 pProbe = pSrc->pIndex;
108742 }else{
108743 /* There is no INDEXED BY clause. Create a fake Index object in local
108744 ** variable sPk to represent the rowid primary key index. Make this
108745 ** fake index the first in a chain of Index objects with all of the real
108746 ** indices to follow */
108747 Index *pFirst; /* First of real indices on the table */
108748 memset(&sPk, 0, sizeof(Index));
108749 sPk.nColumn = 1;
108750 sPk.aiColumn = &aiColumnPk;
108751 sPk.aiRowEst = aiRowEstPk;
108752 sPk.onError = OE_Replace;
108753 sPk.pTable = pSrc->pTab;
108754 aiRowEstPk[0] = pSrc->pTab->nRowEst;
108755 aiRowEstPk[1] = 1;
108756 pFirst = pSrc->pTab->pIndex;
108757 if( pSrc->notIndexed==0 ){
108758 /* The real indices of the table are only considered if the
108759 ** NOT INDEXED qualifier is omitted from the FROM clause */
108760 sPk.pNext = pFirst;
108761 }
108762 pProbe = &sPk;
108763 }
108764 rSize = whereCost(pSrc->pTab->nRowEst);
108765 rLogSize = estLog(rSize);
108766
108767 /* Automatic indexes */
108768 if( !pBuilder->pBest
108769 && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
108770 && pSrc->pIndex==0
108771 && !pSrc->viaCoroutine
108772 && !pSrc->notIndexed
108773 && !pSrc->isCorrelated
108774 ){
108775 /* Generate auto-index WhereLoops */
108776 WhereClause *pWC = pBuilder->pWC;
108777 WhereTerm *pTerm;
108778 WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
108779 for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
108780 if( pTerm->prereqRight & pNew->maskSelf ) continue;
108781 if( termCanDriveIndex(pTerm, pSrc, 0) ){
108782 pNew->u.btree.nEq = 1;
108783 pNew->u.btree.pIndex = 0;
108784 pNew->nLTerm = 1;
108785 pNew->aLTerm[0] = pTerm;
108786 /* TUNING: One-time cost for computing the automatic index is
108787 ** approximately 6*N*log2(N) where N is the number of rows in
108788 ** the table being indexed. */
108789 pNew->rSetup = rLogSize + rSize + 26; assert( 26==whereCost(6) );
108790 /* TUNING: Each index lookup yields 10 rows in the table */
108791 pNew->nOut = 33; assert( 33==whereCost(10) );
108792 pNew->rRun = whereCostAdd(rLogSize,pNew->nOut);
108793 pNew->wsFlags = WHERE_TEMP_INDEX;
108794 pNew->prereq = mExtra | pTerm->prereqRight;
108795 rc = whereLoopInsert(pBuilder, pNew);
108796 }
108797 }
108798 }
108799
108800 /* Loop over all indices
108801 */
108802 for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
108803 pNew->u.btree.nEq = 0;
108804 pNew->nLTerm = 0;
108805 pNew->iSortIdx = 0;
108806 pNew->rSetup = 0;
108807 pNew->prereq = mExtra;
108808 pNew->nOut = rSize;
108809 pNew->u.btree.pIndex = pProbe;
108810 b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
108811 /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
108812 assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
108813 if( pProbe->tnum<=0 ){
108814 /* Integer primary key index */
108815 pNew->wsFlags = WHERE_IPK;
108816
108817 /* Full table scan */
108818 pNew->iSortIdx = b ? iSortIdx : 0;
108819 /* TUNING: Cost of full table scan is 3*(N + log2(N)).
108820 ** + The extra 3 factor is to encourage the use of indexed lookups
108821 ** over full scans. A smaller constant 2 is used for covering
108822 ** index scans so that a covering index scan will be favored over
108823 ** a table scan. */
108824 pNew->rRun = whereCostAdd(rSize,rLogSize) + 16;
108825 rc = whereLoopInsert(pBuilder, pNew);
108826 if( rc ) break;
108827 }else{
108828 Bitmask m = pSrc->colUsed & ~columnsInIndex(pProbe);
108829 pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
108830
108831 /* Full scan via index */
108832 if( b
108833 || ( m==0
108834 && pProbe->bUnordered==0
108835 && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
108836 && sqlite3GlobalConfig.bUseCis
108837 && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
108838 )
108839 ){
108840 pNew->iSortIdx = b ? iSortIdx : 0;
108841 if( m==0 ){
108842 /* TUNING: Cost of a covering index scan is 2*(N + log2(N)).
108843 ** + The extra 2 factor is to encourage the use of indexed lookups
108844 ** over index scans. A table scan uses a factor of 3 so that
108845 ** index scans are favored over table scans.
108846 ** + If this covering index might also help satisfy the ORDER BY
108847 ** clause, then the cost is fudged down slightly so that this
108848 ** index is favored above other indices that have no hope of
108849 ** helping with the ORDER BY. */
108850 pNew->rRun = 10 + whereCostAdd(rSize,rLogSize) - b;
108851 }else{
108852 assert( b!=0 );
108853 /* TUNING: Cost of scanning a non-covering index is (N+1)*log2(N)
108854 ** which we will simplify to just N*log2(N) */
108855 pNew->rRun = rSize + rLogSize;
108856 }
108857 rc = whereLoopInsert(pBuilder, pNew);
108858 if( rc ) break;
108859 }
108860 }
108861 rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
108862
108863 /* If there was an INDEXED BY clause, then only that one index is
108864 ** considered. */
108865 if( pSrc->pIndex ) break;
108866 }
108867 return rc;
108868 }
108869
108870 #ifndef SQLITE_OMIT_VIRTUALTABLE
108871 /*
108872 ** Add all WhereLoop objects for a table of the join identified by
108873 ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
108874 */
108875 static int whereLoopAddVirtual(
108876 WhereLoopBuilder *pBuilder /* WHERE clause information */
108877 ){
108878 WhereInfo *pWInfo; /* WHERE analysis context */
108879 Parse *pParse; /* The parsing context */
108880 WhereClause *pWC; /* The WHERE clause */
108881 struct SrcList_item *pSrc; /* The FROM clause term to search */
108882 Table *pTab;
108883 sqlite3 *db;
108884 sqlite3_index_info *pIdxInfo;
108885 struct sqlite3_index_constraint *pIdxCons;
108886 struct sqlite3_index_constraint_usage *pUsage;
108887 WhereTerm *pTerm;
108888 int i, j;
108889 int iTerm, mxTerm;
108890 int nConstraint;
108891 int seenIn = 0; /* True if an IN operator is seen */
108892 int seenVar = 0; /* True if a non-constant constraint is seen */
108893 int iPhase; /* 0: const w/o IN, 1: const, 2: no IN, 2: IN */
108894 WhereLoop *pNew;
108895 int rc = SQLITE_OK;
108896
108897 pWInfo = pBuilder->pWInfo;
108898 pParse = pWInfo->pParse;
108899 db = pParse->db;
108900 pWC = pBuilder->pWC;
108901 pNew = pBuilder->pNew;
108902 pSrc = &pWInfo->pTabList->a[pNew->iTab];
108903 pTab = pSrc->pTab;
108904 assert( IsVirtual(pTab) );
108905 pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy);
108906 if( pIdxInfo==0 ) return SQLITE_NOMEM;
108907 pNew->prereq = 0;
108908 pNew->rSetup = 0;
108909 pNew->wsFlags = WHERE_VIRTUALTABLE;
108910 pNew->nLTerm = 0;
108911 pNew->u.vtab.needFree = 0;
108912 pUsage = pIdxInfo->aConstraintUsage;
108913 nConstraint = pIdxInfo->nConstraint;
108914 if( whereLoopResize(db, pNew, nConstraint) ){
108915 sqlite3DbFree(db, pIdxInfo);
108916 return SQLITE_NOMEM;
108917 }
108918
108919 for(iPhase=0; iPhase<=3; iPhase++){
108920 if( !seenIn && (iPhase&1)!=0 ){
108921 iPhase++;
108922 if( iPhase>3 ) break;
108923 }
108924 if( !seenVar && iPhase>1 ) break;
108925 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
108926 for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
108927 j = pIdxCons->iTermOffset;
108928 pTerm = &pWC->a[j];
108929 switch( iPhase ){
108930 case 0: /* Constants without IN operator */
108931 pIdxCons->usable = 0;
108932 if( (pTerm->eOperator & WO_IN)!=0 ){
108933 seenIn = 1;
108934 }
108935 if( pTerm->prereqRight!=0 ){
108936 seenVar = 1;
108937 }else if( (pTerm->eOperator & WO_IN)==0 ){
108938 pIdxCons->usable = 1;
108939 }
108940 break;
108941 case 1: /* Constants with IN operators */
108942 assert( seenIn );
108943 pIdxCons->usable = (pTerm->prereqRight==0);
108944 break;
108945 case 2: /* Variables without IN */
108946 assert( seenVar );
108947 pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
108948 break;
108949 default: /* Variables with IN */
108950 assert( seenVar && seenIn );
108951 pIdxCons->usable = 1;
108952 break;
108953 }
108954 }
108955 memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
108956 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
108957 pIdxInfo->idxStr = 0;
108958 pIdxInfo->idxNum = 0;
108959 pIdxInfo->needToFreeIdxStr = 0;
108960 pIdxInfo->orderByConsumed = 0;
108961 pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
108962 rc = vtabBestIndex(pParse, pTab, pIdxInfo);
108963 if( rc ) goto whereLoopAddVtab_exit;
108964 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
108965 pNew->prereq = 0;
108966 mxTerm = -1;
108967 assert( pNew->nLSlot>=nConstraint );
108968 for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
108969 pNew->u.vtab.omitMask = 0;
108970 for(i=0; i<nConstraint; i++, pIdxCons++){
108971 if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
108972 j = pIdxCons->iTermOffset;
108973 if( iTerm>=nConstraint
108974 || j<0
108975 || j>=pWC->nTerm
108976 || pNew->aLTerm[iTerm]!=0
108977 ){
108978 rc = SQLITE_ERROR;
108979 sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
108980 goto whereLoopAddVtab_exit;
108981 }
108982 testcase( iTerm==nConstraint-1 );
108983 testcase( j==0 );
108984 testcase( j==pWC->nTerm-1 );
108985 pTerm = &pWC->a[j];
108986 pNew->prereq |= pTerm->prereqRight;
108987 assert( iTerm<pNew->nLSlot );
108988 pNew->aLTerm[iTerm] = pTerm;
108989 if( iTerm>mxTerm ) mxTerm = iTerm;
108990 testcase( iTerm==15 );
108991 testcase( iTerm==16 );
108992 if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
108993 if( (pTerm->eOperator & WO_IN)!=0 ){
108994 if( pUsage[i].omit==0 ){
108995 /* Do not attempt to use an IN constraint if the virtual table
108996 ** says that the equivalent EQ constraint cannot be safely omitted.
108997 ** If we do attempt to use such a constraint, some rows might be
108998 ** repeated in the output. */
108999 break;
109000 }
109001 /* A virtual table that is constrained by an IN clause may not
109002 ** consume the ORDER BY clause because (1) the order of IN terms
109003 ** is not necessarily related to the order of output terms and
109004 ** (2) Multiple outputs from a single IN value will not merge
109005 ** together. */
109006 pIdxInfo->orderByConsumed = 0;
109007 }
109008 }
109009 }
109010 if( i>=nConstraint ){
109011 pNew->nLTerm = mxTerm+1;
109012 assert( pNew->nLTerm<=pNew->nLSlot );
109013 pNew->u.vtab.idxNum = pIdxInfo->idxNum;
109014 pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
109015 pIdxInfo->needToFreeIdxStr = 0;
109016 pNew->u.vtab.idxStr = pIdxInfo->idxStr;
109017 pNew->u.vtab.isOrdered = (u8)((pIdxInfo->nOrderBy!=0)
109018 && pIdxInfo->orderByConsumed);
109019 pNew->rSetup = 0;
109020 pNew->rRun = whereCostFromDouble(pIdxInfo->estimatedCost);
109021 /* TUNING: Every virtual table query returns 25 rows */
109022 pNew->nOut = 46; assert( 46==whereCost(25) );
109023 whereLoopInsert(pBuilder, pNew);
109024 if( pNew->u.vtab.needFree ){
109025 sqlite3_free(pNew->u.vtab.idxStr);
109026 pNew->u.vtab.needFree = 0;
109027 }
109028 }
109029 }
109030
109031 whereLoopAddVtab_exit:
109032 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
109033 sqlite3DbFree(db, pIdxInfo);
109034 return rc;
109035 }
109036 #endif /* SQLITE_OMIT_VIRTUALTABLE */
109037
109038 /*
109039 ** Add WhereLoop entries to handle OR terms. This works for either
109040 ** btrees or virtual tables.
109041 */
109042 static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){
109043 WhereInfo *pWInfo = pBuilder->pWInfo;
109044 WhereClause *pWC;
109045 WhereLoop *pNew;
109046 WhereTerm *pTerm, *pWCEnd;
109047 int rc = SQLITE_OK;
109048 int iCur;
109049 WhereClause tempWC;
109050 WhereLoopBuilder sSubBuild;
109051 WhereLoop sBest;
109052 struct SrcList_item *pItem;
109053
109054 pWC = pBuilder->pWC;
109055 if( pWInfo->wctrlFlags & WHERE_AND_ONLY ) return SQLITE_OK;
109056 pWCEnd = pWC->a + pWC->nTerm;
109057 pNew = pBuilder->pNew;
109058
109059 for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
109060 if( (pTerm->eOperator & WO_OR)!=0
109061 && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
109062 ){
109063 WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
109064 WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
109065 WhereTerm *pOrTerm;
109066 WhereCost rTotal = 0;
109067 WhereCost nRow = 0;
109068 Bitmask prereq = mExtra;
109069
109070 whereLoopInit(&sBest);
109071 pItem = pWInfo->pTabList->a + pNew->iTab;
109072 iCur = pItem->iCursor;
109073 sSubBuild = *pBuilder;
109074 sSubBuild.pOrderBy = 0;
109075 sSubBuild.pBest = &sBest;
109076
109077 for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
109078 if( (pOrTerm->eOperator & WO_AND)!=0 ){
109079 sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
109080 }else if( pOrTerm->leftCursor==iCur ){
109081 tempWC.pWInfo = pWC->pWInfo;
109082 tempWC.pOuter = pWC;
109083 tempWC.op = TK_AND;
109084 tempWC.nTerm = 1;
109085 tempWC.a = pOrTerm;
109086 sSubBuild.pWC = &tempWC;
109087 }else{
109088 continue;
109089 }
109090 sBest.maskSelf = 0;
109091 sBest.rSetup = 0;
109092 sBest.rRun = 0;
109093 #ifndef SQLITE_OMIT_VIRTUALTABLE
109094 if( IsVirtual(pItem->pTab) ){
109095 rc = whereLoopAddVirtual(&sSubBuild);
109096 }else
109097 #endif
109098 {
109099 rc = whereLoopAddBtree(&sSubBuild, mExtra);
109100 }
109101 /* sBest.maskSelf is always zero if an error occurs */
109102 assert( rc==SQLITE_OK || sBest.maskSelf==0 );
109103 if( sBest.maskSelf==0 ) break;
109104 assert( sBest.rSetup==0 );
109105 rTotal = whereCostAdd(rTotal, sBest.rRun);
109106 nRow = whereCostAdd(nRow, sBest.nOut);
109107 prereq |= sBest.prereq;
109108 }
109109 assert( pNew->nLSlot>=1 );
109110 if( sBest.maskSelf ){
109111 pNew->nLTerm = 1;
109112 pNew->aLTerm[0] = pTerm;
109113 pNew->wsFlags = WHERE_MULTI_OR;
109114 pNew->rSetup = 0;
109115 /* TUNING: Multiple by 3.5 for the secondary table lookup */
109116 pNew->rRun = rTotal + 18; assert( 18==whereCost(7)-whereCost(2) );
109117 pNew->nOut = nRow;
109118 pNew->prereq = prereq;
109119 memset(&pNew->u, 0, sizeof(pNew->u));
109120 rc = whereLoopInsert(pBuilder, pNew);
109121 }
109122 whereLoopClear(pWInfo->pParse->db, &sBest);
109123 }
109124 }
109125 return rc;
109126 }
109127
109128 /*
109129 ** Add all WhereLoop objects for all tables
109130 */
109131 static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
109132 WhereInfo *pWInfo = pBuilder->pWInfo;
109133 Bitmask mExtra = 0;
109134 Bitmask mPrior = 0;
109135 int iTab;
109136 SrcList *pTabList = pWInfo->pTabList;
109137 struct SrcList_item *pItem;
109138 sqlite3 *db = pWInfo->pParse->db;
109139 int nTabList = pWInfo->nLevel;
109140 int rc = SQLITE_OK;
109141 u8 priorJoinType = 0;
109142 WhereLoop *pNew;
109143
109144 /* Loop over the tables in the join, from left to right */
109145 pNew = pBuilder->pNew;
109146 whereLoopInit(pNew);
109147 for(iTab=0, pItem=pTabList->a; iTab<nTabList; iTab++, pItem++){
109148 pNew->iTab = iTab;
109149 pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor);
109150 if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){
109151 mExtra = mPrior;
109152 }
109153 priorJoinType = pItem->jointype;
109154 if( IsVirtual(pItem->pTab) ){
109155 rc = whereLoopAddVirtual(pBuilder);
109156 }else{
109157 rc = whereLoopAddBtree(pBuilder, mExtra);
109158 }
109159 if( rc==SQLITE_OK ){
109160 rc = whereLoopAddOr(pBuilder, mExtra);
109161 }
109162 mPrior |= pNew->maskSelf;
109163 if( rc || db->mallocFailed ) break;
109164 }
109165 whereLoopClear(db, pNew);
109166 return rc;
109167 }
109168
109169 /*
109170 ** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
109171 ** parameters) to see if it outputs rows in the requested ORDER BY
109172 ** (or GROUP BY) without requiring a separate source operation. Return:
109173 **
109174 ** 0: ORDER BY is not satisfied. Sorting required
109175 ** 1: ORDER BY is satisfied. Omit sorting
109176 ** -1: Unknown at this time
109177 **
109178 */
109179 static int wherePathSatisfiesOrderBy(
109180 WhereInfo *pWInfo, /* The WHERE clause */
109181 ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
109182 WherePath *pPath, /* The WherePath to check */
109183 u16 wctrlFlags, /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
109184 u16 nLoop, /* Number of entries in pPath->aLoop[] */
109185 WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
109186 Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
109187 ){
109188 u8 revSet; /* True if rev is known */
109189 u8 rev; /* Composite sort order */
109190 u8 revIdx; /* Index sort order */
109191 u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
109192 u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
109193 u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
109194 u16 nColumn; /* Number of columns in pIndex */
109195 u16 nOrderBy; /* Number terms in the ORDER BY clause */
109196 int iLoop; /* Index of WhereLoop in pPath being processed */
109197 int i, j; /* Loop counters */
109198 int iCur; /* Cursor number for current WhereLoop */
109199 int iColumn; /* A column number within table iCur */
109200 WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
109201 WhereTerm *pTerm; /* A single term of the WHERE clause */
109202 Expr *pOBExpr; /* An expression from the ORDER BY clause */
109203 CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
109204 Index *pIndex; /* The index associated with pLoop */
109205 sqlite3 *db = pWInfo->pParse->db; /* Database connection */
109206 Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
109207 Bitmask obDone; /* Mask of all ORDER BY terms */
109208 Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
109209 Bitmask ready; /* Mask of inner loops */
109210
109211 /*
109212 ** We say the WhereLoop is "one-row" if it generates no more than one
109213 ** row of output. A WhereLoop is one-row if all of the following are true:
109214 ** (a) All index columns match with WHERE_COLUMN_EQ.
109215 ** (b) The index is unique
109216 ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
109217 ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
109218 **
109219 ** We say the WhereLoop is "order-distinct" if the set of columns from
109220 ** that WhereLoop that are in the ORDER BY clause are different for every
109221 ** row of the WhereLoop. Every one-row WhereLoop is automatically
109222 ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
109223 ** is not order-distinct. To be order-distinct is not quite the same as being
109224 ** UNIQUE since a UNIQUE column or index can have multiple rows that
109225 ** are NULL and NULL values are equivalent for the purpose of order-distinct.
109226 ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
109227 **
109228 ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
109229 ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
109230 ** automatically order-distinct.
109231 */
109232
109233 assert( pOrderBy!=0 );
109234
109235 /* Sortability of virtual tables is determined by the xBestIndex method
109236 ** of the virtual table itself */
109237 if( pLast->wsFlags & WHERE_VIRTUALTABLE ){
109238 testcase( nLoop>0 ); /* True when outer loops are one-row and match
109239 ** no ORDER BY terms */
109240 return pLast->u.vtab.isOrdered;
109241 }
109242 if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
109243
109244 nOrderBy = pOrderBy->nExpr;
109245 testcase( nOrderBy==BMS-1 );
109246 if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
109247 isOrderDistinct = 1;
109248 obDone = MASKBIT(nOrderBy)-1;
109249 orderDistinctMask = 0;
109250 ready = 0;
109251 for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
109252 if( iLoop>0 ) ready |= pLoop->maskSelf;
109253 pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
109254 assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
109255 iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
109256
109257 /* Mark off any ORDER BY term X that is a column in the table of
109258 ** the current loop for which there is term in the WHERE
109259 ** clause of the form X IS NULL or X=? that reference only outer
109260 ** loops.
109261 */
109262 for(i=0; i<nOrderBy; i++){
109263 if( MASKBIT(i) & obSat ) continue;
109264 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
109265 if( pOBExpr->op!=TK_COLUMN ) continue;
109266 if( pOBExpr->iTable!=iCur ) continue;
109267 pTerm = findTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
109268 ~ready, WO_EQ|WO_ISNULL, 0);
109269 if( pTerm==0 ) continue;
109270 if( (pTerm->eOperator&WO_EQ)!=0 && pOBExpr->iColumn>=0 ){
109271 const char *z1, *z2;
109272 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
109273 if( !pColl ) pColl = db->pDfltColl;
109274 z1 = pColl->zName;
109275 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
109276 if( !pColl ) pColl = db->pDfltColl;
109277 z2 = pColl->zName;
109278 if( sqlite3StrICmp(z1, z2)!=0 ) continue;
109279 }
109280 obSat |= MASKBIT(i);
109281 }
109282
109283 if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
109284 if( pLoop->wsFlags & WHERE_IPK ){
109285 pIndex = 0;
109286 nColumn = 0;
109287 }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
109288 return 0;
109289 }else{
109290 nColumn = pIndex->nColumn;
109291 isOrderDistinct = pIndex->onError!=OE_None;
109292 }
109293
109294 /* Loop through all columns of the index and deal with the ones
109295 ** that are not constrained by == or IN.
109296 */
109297 rev = revSet = 0;
109298 distinctColumns = 0;
109299 for(j=0; j<=nColumn; j++){
109300 u8 bOnce; /* True to run the ORDER BY search loop */
109301
109302 /* Skip over == and IS NULL terms */
109303 if( j<pLoop->u.btree.nEq
109304 && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL))!=0
109305 ){
109306 if( i & WO_ISNULL ){
109307 testcase( isOrderDistinct );
109308 isOrderDistinct = 0;
109309 }
109310 continue;
109311 }
109312
109313 /* Get the column number in the table (iColumn) and sort order
109314 ** (revIdx) for the j-th column of the index.
109315 */
109316 if( j<nColumn ){
109317 /* Normal index columns */
109318 iColumn = pIndex->aiColumn[j];
109319 revIdx = pIndex->aSortOrder[j];
109320 if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
109321 }else{
109322 /* The ROWID column at the end */
109323 assert( j==nColumn );
109324 iColumn = -1;
109325 revIdx = 0;
109326 }
109327
109328 /* An unconstrained column that might be NULL means that this
109329 ** WhereLoop is not well-ordered
109330 */
109331 if( isOrderDistinct
109332 && iColumn>=0
109333 && j>=pLoop->u.btree.nEq
109334 && pIndex->pTable->aCol[iColumn].notNull==0
109335 ){
109336 isOrderDistinct = 0;
109337 }
109338
109339 /* Find the ORDER BY term that corresponds to the j-th column
109340 ** of the index and and mark that ORDER BY term off
109341 */
109342 bOnce = 1;
109343 isMatch = 0;
109344 for(i=0; bOnce && i<nOrderBy; i++){
109345 if( MASKBIT(i) & obSat ) continue;
109346 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
109347 testcase( wctrlFlags & WHERE_GROUPBY );
109348 testcase( wctrlFlags & WHERE_DISTINCTBY );
109349 if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
109350 if( pOBExpr->op!=TK_COLUMN ) continue;
109351 if( pOBExpr->iTable!=iCur ) continue;
109352 if( pOBExpr->iColumn!=iColumn ) continue;
109353 if( iColumn>=0 ){
109354 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
109355 if( !pColl ) pColl = db->pDfltColl;
109356 if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
109357 }
109358 isMatch = 1;
109359 break;
109360 }
109361 if( isMatch ){
109362 if( iColumn<0 ){
109363 testcase( distinctColumns==0 );
109364 distinctColumns = 1;
109365 }
109366 obSat |= MASKBIT(i);
109367 if( (pWInfo->wctrlFlags & WHERE_GROUPBY)==0 ){
109368 /* Make sure the sort order is compatible in an ORDER BY clause.
109369 ** Sort order is irrelevant for a GROUP BY clause. */
109370 if( revSet ){
109371 if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) return 0;
109372 }else{
109373 rev = revIdx ^ pOrderBy->a[i].sortOrder;
109374 if( rev ) *pRevMask |= MASKBIT(iLoop);
109375 revSet = 1;
109376 }
109377 }
109378 }else{
109379 /* No match found */
109380 if( j==0 || j<nColumn ){
109381 testcase( isOrderDistinct!=0 );
109382 isOrderDistinct = 0;
109383 }
109384 break;
109385 }
109386 } /* end Loop over all index columns */
109387 if( distinctColumns ){
109388 testcase( isOrderDistinct==0 );
109389 isOrderDistinct = 1;
109390 }
109391 } /* end-if not one-row */
109392
109393 /* Mark off any other ORDER BY terms that reference pLoop */
109394 if( isOrderDistinct ){
109395 orderDistinctMask |= pLoop->maskSelf;
109396 for(i=0; i<nOrderBy; i++){
109397 Expr *p;
109398 if( MASKBIT(i) & obSat ) continue;
109399 p = pOrderBy->a[i].pExpr;
109400 if( (exprTableUsage(&pWInfo->sMaskSet, p)&~orderDistinctMask)==0 ){
109401 obSat |= MASKBIT(i);
109402 }
109403 }
109404 }
109405 } /* End the loop over all WhereLoops from outer-most down to inner-most */
109406 if( obSat==obDone ) return 1;
109407 if( !isOrderDistinct ) return 0;
109408 return -1;
109409 }
109410
109411 #ifdef WHERETRACE_ENABLED
109412 /* For debugging use only: */
109413 static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
109414 static char zName[65];
109415 int i;
109416 for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
109417 if( pLast ) zName[i++] = pLast->cId;
109418 zName[i] = 0;
109419 return zName;
109420 }
109421 #endif
109422
109423
109424 /*
109425 ** Given the list of WhereLoop objects on pWInfo->pLoops, this routine
109426 ** attempts to find the lowest cost path that visits each WhereLoop
109427 ** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
109428 **
109429 ** Assume that the total number of output rows that will need to be sorted
109430 ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
109431 ** costs if nRowEst==0.
109432 **
109433 ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
109434 ** error occurs.
109435 */
109436 static int wherePathSolver(WhereInfo *pWInfo, WhereCost nRowEst){
109437 int mxChoice; /* Maximum number of simultaneous paths tracked */
109438 int nLoop; /* Number of terms in the join */
109439 Parse *pParse; /* Parsing context */
109440 sqlite3 *db; /* The database connection */
109441 int iLoop; /* Loop counter over the terms of the join */
109442 int ii, jj; /* Loop counters */
109443 WhereCost rCost; /* Cost of a path */
109444 WhereCost mxCost = 0; /* Maximum cost of a set of paths */
109445 WhereCost rSortCost; /* Cost to do a sort */
109446 int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
109447 WherePath *aFrom; /* All nFrom paths at the previous level */
109448 WherePath *aTo; /* The nTo best paths at the current level */
109449 WherePath *pFrom; /* An element of aFrom[] that we are working on */
109450 WherePath *pTo; /* An element of aTo[] that we are working on */
109451 WhereLoop *pWLoop; /* One of the WhereLoop objects */
109452 WhereLoop **pX; /* Used to divy up the pSpace memory */
109453 char *pSpace; /* Temporary memory used by this routine */
109454
109455 pParse = pWInfo->pParse;
109456 db = pParse->db;
109457 nLoop = pWInfo->nLevel;
109458 /* TUNING: For simple queries, only the best path is tracked.
109459 ** For 2-way joins, the 5 best paths are followed.
109460 ** For joins of 3 or more tables, track the 10 best paths */
109461 mxChoice = (nLoop==1) ? 1 : (nLoop==2 ? 5 : 10);
109462 assert( nLoop<=pWInfo->pTabList->nSrc );
109463 WHERETRACE(0x002, ("---- begin solver\n"));
109464
109465 /* Allocate and initialize space for aTo and aFrom */
109466 ii = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
109467 pSpace = sqlite3DbMallocRaw(db, ii);
109468 if( pSpace==0 ) return SQLITE_NOMEM;
109469 aTo = (WherePath*)pSpace;
109470 aFrom = aTo+mxChoice;
109471 memset(aFrom, 0, sizeof(aFrom[0]));
109472 pX = (WhereLoop**)(aFrom+mxChoice);
109473 for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
109474 pFrom->aLoop = pX;
109475 }
109476
109477 /* Seed the search with a single WherePath containing zero WhereLoops.
109478 **
109479 ** TUNING: Do not let the number of iterations go above 25. If the cost
109480 ** of computing an automatic index is not paid back within the first 25
109481 ** rows, then do not use the automatic index. */
109482 aFrom[0].nRow = MIN(pParse->nQueryLoop, 46); assert( 46==whereCost(25) );
109483 nFrom = 1;
109484
109485 /* Precompute the cost of sorting the final result set, if the caller
109486 ** to sqlite3WhereBegin() was concerned about sorting */
109487 rSortCost = 0;
109488 if( pWInfo->pOrderBy==0 || nRowEst==0 ){
109489 aFrom[0].isOrderedValid = 1;
109490 }else{
109491 /* TUNING: Estimated cost of sorting is N*log2(N) where N is the
109492 ** number of output rows. */
109493 rSortCost = nRowEst + estLog(nRowEst);
109494 WHERETRACE(0x002,("---- sort cost=%-3d\n", rSortCost));
109495 }
109496
109497 /* Compute successively longer WherePaths using the previous generation
109498 ** of WherePaths as the basis for the next. Keep track of the mxChoice
109499 ** best paths at each generation */
109500 for(iLoop=0; iLoop<nLoop; iLoop++){
109501 nTo = 0;
109502 for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
109503 for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
109504 Bitmask maskNew;
109505 Bitmask revMask = 0;
109506 u8 isOrderedValid = pFrom->isOrderedValid;
109507 u8 isOrdered = pFrom->isOrdered;
109508 if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
109509 if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
109510 /* At this point, pWLoop is a candidate to be the next loop.
109511 ** Compute its cost */
109512 rCost = whereCostAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
109513 rCost = whereCostAdd(rCost, pFrom->rCost);
109514 maskNew = pFrom->maskLoop | pWLoop->maskSelf;
109515 if( !isOrderedValid ){
109516 switch( wherePathSatisfiesOrderBy(pWInfo,
109517 pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
109518 iLoop, pWLoop, &revMask) ){
109519 case 1: /* Yes. pFrom+pWLoop does satisfy the ORDER BY clause */
109520 isOrdered = 1;
109521 isOrderedValid = 1;
109522 break;
109523 case 0: /* No. pFrom+pWLoop will require a separate sort */
109524 isOrdered = 0;
109525 isOrderedValid = 1;
109526 rCost = whereCostAdd(rCost, rSortCost);
109527 break;
109528 default: /* Cannot tell yet. Try again on the next iteration */
109529 break;
109530 }
109531 }else{
109532 revMask = pFrom->revLoop;
109533 }
109534 /* Check to see if pWLoop should be added to the mxChoice best so far */
109535 for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
109536 if( pTo->maskLoop==maskNew && pTo->isOrderedValid==isOrderedValid ){
109537 testcase( jj==nTo-1 );
109538 break;
109539 }
109540 }
109541 if( jj>=nTo ){
109542 if( nTo>=mxChoice && rCost>=mxCost ){
109543 #ifdef WHERETRACE_ENABLED
109544 if( sqlite3WhereTrace&0x4 ){
109545 sqlite3DebugPrintf("Skip %s cost=%3d order=%c\n",
109546 wherePathName(pFrom, iLoop, pWLoop), rCost,
109547 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
109548 }
109549 #endif
109550 continue;
109551 }
109552 /* Add a new Path to the aTo[] set */
109553 if( nTo<mxChoice ){
109554 /* Increase the size of the aTo set by one */
109555 jj = nTo++;
109556 }else{
109557 /* New path replaces the prior worst to keep count below mxChoice */
109558 for(jj=nTo-1; aTo[jj].rCost<mxCost; jj--){ assert(jj>0); }
109559 }
109560 pTo = &aTo[jj];
109561 #ifdef WHERETRACE_ENABLED
109562 if( sqlite3WhereTrace&0x4 ){
109563 sqlite3DebugPrintf("New %s cost=%-3d order=%c\n",
109564 wherePathName(pFrom, iLoop, pWLoop), rCost,
109565 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
109566 }
109567 #endif
109568 }else{
109569 if( pTo->rCost<=rCost ){
109570 #ifdef WHERETRACE_ENABLED
109571 if( sqlite3WhereTrace&0x4 ){
109572 sqlite3DebugPrintf(
109573 "Skip %s cost=%-3d order=%c",
109574 wherePathName(pFrom, iLoop, pWLoop), rCost,
109575 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
109576 sqlite3DebugPrintf(" vs %s cost=%-3d order=%c\n",
109577 wherePathName(pTo, iLoop+1, 0), pTo->rCost,
109578 pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
109579 }
109580 #endif
109581 testcase( pTo->rCost==rCost );
109582 continue;
109583 }
109584 testcase( pTo->rCost==rCost+1 );
109585 /* A new and better score for a previously created equivalent path */
109586 #ifdef WHERETRACE_ENABLED
109587 if( sqlite3WhereTrace&0x4 ){
109588 sqlite3DebugPrintf(
109589 "Update %s cost=%-3d order=%c",
109590 wherePathName(pFrom, iLoop, pWLoop), rCost,
109591 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
109592 sqlite3DebugPrintf(" was %s cost=%-3d order=%c\n",
109593 wherePathName(pTo, iLoop+1, 0), pTo->rCost,
109594 pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
109595 }
109596 #endif
109597 }
109598 /* pWLoop is a winner. Add it to the set of best so far */
109599 pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
109600 pTo->revLoop = revMask;
109601 pTo->nRow = pFrom->nRow + pWLoop->nOut;
109602 pTo->rCost = rCost;
109603 pTo->isOrderedValid = isOrderedValid;
109604 pTo->isOrdered = isOrdered;
109605 memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
109606 pTo->aLoop[iLoop] = pWLoop;
109607 if( nTo>=mxChoice ){
109608 mxCost = aTo[0].rCost;
109609 for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
109610 if( pTo->rCost>mxCost ) mxCost = pTo->rCost;
109611 }
109612 }
109613 }
109614 }
109615
109616 #ifdef WHERETRACE_ENABLED
109617 if( sqlite3WhereTrace>=2 ){
109618 sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
109619 for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
109620 sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
109621 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
109622 pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
109623 if( pTo->isOrderedValid && pTo->isOrdered ){
109624 sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
109625 }else{
109626 sqlite3DebugPrintf("\n");
109627 }
109628 }
109629 }
109630 #endif
109631
109632 /* Swap the roles of aFrom and aTo for the next generation */
109633 pFrom = aTo;
109634 aTo = aFrom;
109635 aFrom = pFrom;
109636 nFrom = nTo;
109637 }
109638
109639 if( nFrom==0 ){
109640 sqlite3ErrorMsg(pParse, "no query solution");
109641 sqlite3DbFree(db, pSpace);
109642 return SQLITE_ERROR;
109643 }
109644
109645 /* Find the lowest cost path. pFrom will be left pointing to that path */
109646 pFrom = aFrom;
109647 assert( nFrom==1 );
109648 #if 0 /* The following is needed if nFrom is ever more than 1 */
109649 for(ii=1; ii<nFrom; ii++){
109650 if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
109651 }
109652 #endif
109653 assert( pWInfo->nLevel==nLoop );
109654 /* Load the lowest cost path into pWInfo */
109655 for(iLoop=0; iLoop<nLoop; iLoop++){
109656 WhereLevel *pLevel = pWInfo->a + iLoop;
109657 pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
109658 pLevel->iFrom = pWLoop->iTab;
109659 pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
109660 }
109661 if( (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
109662 && pWInfo->pDistinct
109663 && nRowEst
109664 ){
109665 Bitmask notUsed;
109666 int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pDistinct, pFrom,
109667 WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
109668 if( rc==1 ) pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
109669 }
109670 if( pFrom->isOrdered ){
109671 if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
109672 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
109673 }else{
109674 pWInfo->bOBSat = 1;
109675 pWInfo->revMask = pFrom->revLoop;
109676 }
109677 }
109678 pWInfo->nRowOut = pFrom->nRow;
109679
109680 /* Free temporary memory and return success */
109681 sqlite3DbFree(db, pSpace);
109682 return SQLITE_OK;
109683 }
109684
109685 /*
109686 ** Most queries use only a single table (they are not joins) and have
109687 ** simple == constraints against indexed fields. This routine attempts
109688 ** to plan those simple cases using much less ceremony than the
109689 ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
109690 ** times for the common case.
109691 **
109692 ** Return non-zero on success, if this query can be handled by this
109693 ** no-frills query planner. Return zero if this query needs the
109694 ** general-purpose query planner.
109695 */
109696 static int whereShortCut(WhereLoopBuilder *pBuilder){
109697 WhereInfo *pWInfo;
109698 struct SrcList_item *pItem;
109699 WhereClause *pWC;
109700 WhereTerm *pTerm;
109701 WhereLoop *pLoop;
109702 int iCur;
109703 int j;
109704 Table *pTab;
109705 Index *pIdx;
109706
109707 pWInfo = pBuilder->pWInfo;
109708 if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
109709 assert( pWInfo->pTabList->nSrc>=1 );
109710 pItem = pWInfo->pTabList->a;
109711 pTab = pItem->pTab;
109712 if( IsVirtual(pTab) ) return 0;
109713 if( pItem->zIndex ) return 0;
109714 iCur = pItem->iCursor;
109715 pWC = &pWInfo->sWC;
109716 pLoop = pBuilder->pNew;
109717 pLoop->wsFlags = 0;
109718 pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ, 0);
109719 if( pTerm ){
109720 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
109721 pLoop->aLTerm[0] = pTerm;
109722 pLoop->nLTerm = 1;
109723 pLoop->u.btree.nEq = 1;
109724 /* TUNING: Cost of a rowid lookup is 10 */
109725 pLoop->rRun = 33; /* 33==whereCost(10) */
109726 }else{
109727 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
109728 if( pIdx->onError==OE_None ) continue;
109729 for(j=0; j<pIdx->nColumn; j++){
109730 pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx);
109731 if( pTerm==0 ) break;
109732 whereLoopResize(pWInfo->pParse->db, pLoop, j);
109733 pLoop->aLTerm[j] = pTerm;
109734 }
109735 if( j!=pIdx->nColumn ) continue;
109736 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
109737 if( (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
109738 pLoop->wsFlags |= WHERE_IDX_ONLY;
109739 }
109740 pLoop->nLTerm = j;
109741 pLoop->u.btree.nEq = j;
109742 pLoop->u.btree.pIndex = pIdx;
109743 /* TUNING: Cost of a unique index lookup is 15 */
109744 pLoop->rRun = 39; /* 39==whereCost(15) */
109745 break;
109746 }
109747 }
109748 if( pLoop->wsFlags ){
109749 pLoop->nOut = (WhereCost)1;
109750 pWInfo->a[0].pWLoop = pLoop;
109751 pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur);
109752 pWInfo->a[0].iTabCur = iCur;
109753 pWInfo->nRowOut = 1;
109754 if( pWInfo->pOrderBy ) pWInfo->bOBSat = 1;
109755 if( pWInfo->pDistinct ) pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
109756 #ifdef SQLITE_DEBUG
109757 pLoop->cId = '0';
109758 #endif
109759 return 1;
109760 }
109761 return 0;
109762 }
109763
109764 /*
109765 ** Generate the beginning of the loop used for WHERE clause processing.
109766 ** The return value is a pointer to an opaque structure that contains
109767 ** information needed to terminate the loop. Later, the calling routine
@@ -109410,19 +109837,10 @@
109837 ** ORDER BY CLAUSE PROCESSING
109838 **
109839 ** pOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
109840 ** if there is one. If there is no ORDER BY clause or if this routine
109841 ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
 
 
 
 
 
 
 
 
 
109842 */
109843 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
109844 Parse *pParse, /* The parser context */
109845 SrcList *pTabList, /* A list of all tables to be scanned */
109846 Expr *pWhere, /* The WHERE clause */
@@ -109434,22 +109852,21 @@
109852 int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
109853 int nTabList; /* Number of elements in pTabList */
109854 WhereInfo *pWInfo; /* Will become the return value of this function */
109855 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
109856 Bitmask notReady; /* Cursors that are not yet positioned */
109857 WhereLoopBuilder sWLB; /* The WhereLoop builder */
109858 WhereMaskSet *pMaskSet; /* The expression mask set */
109859 WhereLevel *pLevel; /* A single level in pWInfo->a[] */
 
 
109860 int ii; /* Loop counter */
109861 sqlite3 *db; /* Database connection */
109862 int rc; /* Return code */
109863
109864
109865 /* Variable initialization */
109866 memset(&sWLB, 0, sizeof(sWLB));
109867 sWLB.pOrderBy = pOrderBy;
109868
109869 /* The number of tables in the FROM clause is limited by the number of
109870 ** bits in a Bitmask
109871 */
109872 testcase( pTabList->nSrc==BMS );
@@ -109472,49 +109889,59 @@
109889 ** field (type Bitmask) it must be aligned on an 8-byte boundary on
109890 ** some architectures. Hence the ROUND8() below.
109891 */
109892 db = pParse->db;
109893 nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
109894 pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
 
 
 
 
109895 if( db->mallocFailed ){
109896 sqlite3DbFree(db, pWInfo);
109897 pWInfo = 0;
109898 goto whereBeginError;
109899 }
109900 pWInfo->nLevel = nTabList;
109901 pWInfo->pParse = pParse;
109902 pWInfo->pTabList = pTabList;
109903 pWInfo->pOrderBy = pOrderBy;
109904 pWInfo->pDistinct = pDistinct;
109905 pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
 
109906 pWInfo->wctrlFlags = wctrlFlags;
109907 pWInfo->savedNQueryLoop = pParse->nQueryLoop;
109908 pMaskSet = &pWInfo->sMaskSet;
109909 sWLB.pWInfo = pWInfo;
109910 sWLB.pWC = &pWInfo->sWC;
109911 sWLB.pNew = (WhereLoop*)&pWInfo->a[nTabList];
109912 whereLoopInit(sWLB.pNew);
109913 #ifdef SQLITE_DEBUG
109914 sWLB.pNew->cId = '*';
109915 #endif
109916
109917 /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
109918 ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
109919 if( OptimizationDisabled(db, SQLITE_DistinctOpt) ) pDistinct = 0;
109920
109921 /* Split the WHERE clause into separate subexpressions where each
109922 ** subexpression is separated by an AND operator.
109923 */
109924 initMaskSet(pMaskSet);
109925 whereClauseInit(&pWInfo->sWC, pWInfo);
109926 sqlite3ExprCodeConstants(pParse, pWhere);
109927 whereSplit(&pWInfo->sWC, pWhere, TK_AND); /* IMP: R-15842-53296 */
109928
109929 /* Special case: a WHERE clause that is constant. Evaluate the
109930 ** expression and either jump over all of the code or fall thru.
109931 */
109932 if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
109933 sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
109934 pWhere = 0;
109935 }
109936
109937 /* Special case: No FROM clause
109938 */
109939 if( nTabList==0 ){
109940 if( pOrderBy ) pWInfo->bOBSat = 1;
109941 if( pDistinct ) pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
109942 }
109943
109944 /* Assign a bit from the bitmask to every term in the FROM clause.
109945 **
109946 ** When assigning bitmask values to FROM clause cursors, it must be
109947 ** the case that if X is the bitmask for the N-th FROM clause term then
@@ -109547,337 +109974,153 @@
109974 /* Analyze all of the subexpressions. Note that exprAnalyze() might
109975 ** add new virtual terms onto the end of the WHERE clause. We do not
109976 ** want to analyze these virtual terms, so start analyzing at the end
109977 ** and work forward so that the added virtual terms are never processed.
109978 */
109979 exprAnalyzeAll(pTabList, &pWInfo->sWC);
109980 if( db->mallocFailed ){
109981 goto whereBeginError;
109982 }
109983
109984 /* If the ORDER BY (or GROUP BY) clause contains references to general
109985 ** expressions, then we won't be able to satisfy it using indices, so
109986 ** go ahead and disable it now.
109987 */
109988 if( pOrderBy && pDistinct ){
109989 for(ii=0; ii<pOrderBy->nExpr; ii++){
109990 Expr *pExpr = sqlite3ExprSkipCollate(pOrderBy->a[ii].pExpr);
109991 if( pExpr->op!=TK_COLUMN ){
109992 pWInfo->pOrderBy = pOrderBy = 0;
109993 break;
109994 }else if( pExpr->iColumn<0 ){
109995 break;
109996 }
109997 }
109998 }
109999
110000 /* Check if the DISTINCT qualifier, if there is one, is redundant.
110001 ** If it is, then set pDistinct to NULL and WhereInfo.eDistinct to
110002 ** WHERE_DISTINCT_UNIQUE to tell the caller to ignore the DISTINCT.
110003 */
110004 if( pDistinct ){
110005 if( isDistinctRedundant(pParse,pTabList,&pWInfo->sWC,pDistinct) ){
110006 pDistinct = 0;
110007 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
110008 }else if( pOrderBy==0 ){
110009 pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
110010 pWInfo->pOrderBy = pDistinct;
110011 }
110012 }
110013
110014 /* Construct the WhereLoop objects */
110015 WHERETRACE(0xffff,("*** Optimizer Start ***\n"));
110016 if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
110017 rc = whereLoopAddAll(&sWLB);
110018 if( rc ) goto whereBeginError;
110019
110020 /* Display all of the WhereLoop objects if wheretrace is enabled */
110021 #ifdef WHERETRACE_ENABLED
110022 if( sqlite3WhereTrace ){
110023 WhereLoop *p;
110024 int i = 0;
110025 static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
110026 "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
110027 for(p=pWInfo->pLoops; p; p=p->pNextLoop){
110028 p->cId = zLabel[(i++)%sizeof(zLabel)];
110029 whereLoopPrint(p, pTabList);
110030 }
110031 }
110032 #endif
110033
110034 wherePathSolver(pWInfo, 0);
110035 if( db->mallocFailed ) goto whereBeginError;
110036 if( pWInfo->pOrderBy ){
110037 wherePathSolver(pWInfo, pWInfo->nRowOut+1);
110038 if( db->mallocFailed ) goto whereBeginError;
110039 }
110040 }
110041 if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
110042 pWInfo->revMask = (Bitmask)(-1);
110043 }
110044 if( pParse->nErr || NEVER(db->mallocFailed) ){
110045 goto whereBeginError;
110046 }
110047 #ifdef WHERETRACE_ENABLED
110048 if( sqlite3WhereTrace ){
110049 int ii;
110050 sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
110051 if( pWInfo->bOBSat ){
110052 sqlite3DebugPrintf(" ORDERBY=0x%llx", pWInfo->revMask);
110053 }
110054 switch( pWInfo->eDistinct ){
110055 case WHERE_DISTINCT_UNIQUE: {
110056 sqlite3DebugPrintf(" DISTINCT=unique");
110057 break;
110058 }
110059 case WHERE_DISTINCT_ORDERED: {
110060 sqlite3DebugPrintf(" DISTINCT=ordered");
110061 break;
110062 }
110063 case WHERE_DISTINCT_UNORDERED: {
110064 sqlite3DebugPrintf(" DISTINCT=unordered");
110065 break;
110066 }
110067 }
110068 sqlite3DebugPrintf("\n");
110069 for(ii=0; ii<nTabList; ii++){
110070 whereLoopPrint(pWInfo->a[ii].pWLoop, pTabList);
110071 }
110072 }
110073 #endif
110074 WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
110075 pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110076
110077 /* If the caller is an UPDATE or DELETE statement that is requesting
110078 ** to use a one-pass algorithm, determine if this is appropriate.
110079 ** The one-pass algorithm only works if the WHERE clause constraints
110080 ** the statement to update a single row.
110081 */
110082 assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
110083 if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
110084 && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){
110085 pWInfo->okOnePass = 1;
110086 pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
110087 }
110088
110089 /* Open all tables in the pTabList and any indices selected for
110090 ** searching those tables.
110091 */
110092 sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
110093 notReady = ~(Bitmask)0;
 
110094 for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
110095 Table *pTab; /* Table to open */
110096 int iDb; /* Index of database containing table/index */
110097 struct SrcList_item *pTabItem;
110098 WhereLoop *pLoop;
110099
110100 pTabItem = &pTabList->a[pLevel->iFrom];
110101 pTab = pTabItem->pTab;
 
110102 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
110103 pLoop = pLevel->pWLoop;
110104 if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
110105 /* Do nothing */
110106 }else
110107 #ifndef SQLITE_OMIT_VIRTUALTABLE
110108 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
110109 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
110110 int iCur = pTabItem->iCursor;
110111 sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
110112 }else if( IsVirtual(pTab) ){
110113 /* noop */
110114 }else
110115 #endif
110116 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
110117 && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
110118 int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
110119 sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
110120 testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 );
110121 testcase( !pWInfo->okOnePass && pTab->nCol==BMS );
110122 if( !pWInfo->okOnePass && pTab->nCol<BMS ){
110123 Bitmask b = pTabItem->colUsed;
110124 int n = 0;
110125 for(; b; b=b>>1, n++){}
110126 sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
@@ -109886,26 +110129,27 @@
110129 }
110130 }else{
110131 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
110132 }
110133 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
110134 if( (pLoop->wsFlags & WHERE_TEMP_INDEX)!=0 ){
110135 constructAutomaticIndex(pParse, &pWInfo->sWC, pTabItem, notReady, pLevel);
110136 }else
110137 #endif
110138 if( pLoop->wsFlags & WHERE_INDEXED ){
110139 Index *pIx = pLoop->u.btree.pIndex;
110140 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
110141 /* FIXME: As an optimization use pTabItem->iCursor if WHERE_IDX_ONLY */
110142 int iIndexCur = pLevel->iIdxCur = iIdxCur ? iIdxCur : pParse->nTab++;
110143 assert( pIx->pSchema==pTab->pSchema );
110144 assert( iIndexCur>=0 );
110145 sqlite3VdbeAddOp4(v, OP_OpenRead, iIndexCur, pIx->tnum, iDb,
110146 (char*)pKey, P4_KEYINFO_HANDOFF);
110147 VdbeComment((v, "%s", pIx->zName));
110148 }
110149 sqlite3CodeVerifySchema(pParse, iDb);
110150 notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor);
110151 }
110152 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
110153 if( db->mallocFailed ) goto whereBeginError;
110154
110155 /* Generate the code to do the search. Each iteration of the for
@@ -109914,70 +110158,15 @@
110158 */
110159 notReady = ~(Bitmask)0;
110160 for(ii=0; ii<nTabList; ii++){
110161 pLevel = &pWInfo->a[ii];
110162 explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
110163 notReady = codeOneLoopStart(pWInfo, ii, notReady);
110164 pWInfo->iContinue = pLevel->addrCont;
110165 }
110166
110167 /* Done. */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110168 return pWInfo;
110169
110170 /* Jump here if malloc fails */
110171 whereBeginError:
110172 if( pWInfo ){
@@ -109994,24 +110183,26 @@
110183 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
110184 Parse *pParse = pWInfo->pParse;
110185 Vdbe *v = pParse->pVdbe;
110186 int i;
110187 WhereLevel *pLevel;
110188 WhereLoop *pLoop;
110189 SrcList *pTabList = pWInfo->pTabList;
110190 sqlite3 *db = pParse->db;
110191
110192 /* Generate loop termination code.
110193 */
110194 sqlite3ExprCacheClear(pParse);
110195 for(i=pWInfo->nLevel-1; i>=0; i--){
110196 pLevel = &pWInfo->a[i];
110197 pLoop = pLevel->pWLoop;
110198 sqlite3VdbeResolveLabel(v, pLevel->addrCont);
110199 if( pLevel->op!=OP_Noop ){
110200 sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
110201 sqlite3VdbeChangeP5(v, pLevel->p5);
110202 }
110203 if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
110204 struct InLoop *pIn;
110205 int j;
110206 sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
110207 for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
110208 sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
@@ -110022,16 +110213,16 @@
110213 }
110214 sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
110215 if( pLevel->iLeftJoin ){
110216 int addr;
110217 addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
110218 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
110219 || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
110220 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
110221 sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
110222 }
110223 if( pLoop->wsFlags & WHERE_INDEXED ){
110224 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
110225 }
110226 if( pLevel->op==OP_Return ){
110227 sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
110228 }else{
@@ -110052,42 +110243,41 @@
110243 for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
110244 Index *pIdx = 0;
110245 struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
110246 Table *pTab = pTabItem->pTab;
110247 assert( pTab!=0 );
110248 pLoop = pLevel->pWLoop;
110249 if( (pTab->tabFlags & TF_Ephemeral)==0
110250 && pTab->pSelect==0
110251 && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
110252 ){
110253 int ws = pLoop->wsFlags;
110254 if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
110255 sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
110256 }
110257 if( (ws & WHERE_INDEXED)!=0 && (ws & (WHERE_IPK|WHERE_TEMP_INDEX))==0 ){
110258 sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
110259 }
110260 }
110261
110262 /* If this scan uses an index, make VDBE code substitutions to read data
110263 ** from the index instead of from the table where possible. In some cases
110264 ** this optimization prevents the table from ever being read, which can
110265 ** yield a significant performance boost.
 
 
110266 **
110267 ** Calls to the code generator in between sqlite3WhereBegin and
110268 ** sqlite3WhereEnd will have created code that references the table
110269 ** directly. This loop scans all that code looking for opcodes
110270 ** that reference the table and converts them into opcodes that
110271 ** reference the index.
110272 */
110273 if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
110274 pIdx = pLoop->u.btree.pIndex;
110275 }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
110276 pIdx = pLevel->u.pCovidx;
110277 }
110278 if( pIdx && !db->mallocFailed ){
110279 int k, j, last;
110280 VdbeOp *pOp;
110281
110282 pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
110283 last = sqlite3VdbeCurrentAddr(v);
@@ -110099,12 +110289,11 @@
110289 pOp->p2 = j;
110290 pOp->p1 = pLevel->iIdxCur;
110291 break;
110292 }
110293 }
110294 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || j<pIdx->nColumn );
 
110295 }else if( pOp->opcode==OP_Rowid ){
110296 pOp->p1 = pLevel->iIdxCur;
110297 pOp->opcode = OP_IdxRowid;
110298 }
110299 }
@@ -115480,11 +115669,11 @@
115669 }
115670
115671 /*
115672 ** Another built-in collating sequence: NOCASE.
115673 **
115674 ** This collating sequence is intended to be used for "case independent
115675 ** comparison". SQLite's knowledge of upper and lower case equivalents
115676 ** extends only to the 26 characters used in the English language.
115677 **
115678 ** At the moment there is only a UTF-8 implementation.
115679 */
@@ -115627,16 +115816,10 @@
115816 "statements or unfinished backups");
115817 sqlite3_mutex_leave(db->mutex);
115818 return SQLITE_BUSY;
115819 }
115820
 
 
 
 
 
 
115821 #ifdef SQLITE_ENABLE_SQLLOG
115822 if( sqlite3GlobalConfig.xSqllog ){
115823 /* Closing the handle. Fourth parameter is passed the value 2. */
115824 sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
115825 }
@@ -115686,10 +115869,16 @@
115869 /* If we reach this point, it means that the database connection has
115870 ** closed all sqlite3_stmt and sqlite3_backup objects and has been
115871 ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
115872 ** go ahead and free all resources.
115873 */
115874
115875 /* If a transaction is open, roll it back. This also ensures that if
115876 ** any database schemas have been modified by an uncommitted transaction
115877 ** they are reset. And that the required b-tree mutex is held to make
115878 ** the pager rollback and schema reset an atomic operation. */
115879 sqlite3RollbackAll(db, SQLITE_OK);
115880
115881 /* Free any outstanding Savepoint structures. */
115882 sqlite3CloseSavepoints(db);
115883
115884 /* Close all database connections */
@@ -115787,19 +115976,26 @@
115976 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
115977 int i;
115978 int inTrans = 0;
115979 assert( sqlite3_mutex_held(db->mutex) );
115980 sqlite3BeginBenignMalloc();
115981
115982 /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
115983 ** This is important in case the transaction being rolled back has
115984 ** modified the database schema. If the b-tree mutexes are not taken
115985 ** here, then another shared-cache connection might sneak in between
115986 ** the database rollback and schema reset, which can cause false
115987 ** corruption reports in some cases. */
115988 sqlite3BtreeEnterAll(db);
115989
115990 for(i=0; i<db->nDb; i++){
115991 Btree *p = db->aDb[i].pBt;
115992 if( p ){
115993 if( sqlite3BtreeIsInTrans(p) ){
115994 inTrans = 1;
115995 }
115996 sqlite3BtreeRollback(p, tripCode);
 
115997 }
115998 }
115999 sqlite3VtabRollback(db);
116000 sqlite3EndBenignMalloc();
116001
@@ -117562,12 +117758,10 @@
117758 /*
117759 ** Test to see whether or not the database connection is in autocommit
117760 ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
117761 ** by default. Autocommit is disabled by a BEGIN statement and reenabled
117762 ** by the next COMMIT or ROLLBACK.
 
 
117763 */
117764 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
117765 return db->autoCommit;
117766 }
117767
@@ -119051,10 +119245,22 @@
119245
119246 #endif /* _FTS3_HASH_H_ */
119247
119248 /************** End of fts3_hash.h *******************************************/
119249 /************** Continuing where we left off in fts3Int.h ********************/
119250
119251 /*
119252 ** This constant determines the maximum depth of an FTS expression tree
119253 ** that the library will create and use. FTS uses recursion to perform
119254 ** various operations on the query tree, so the disadvantage of a large
119255 ** limit is that it may allow very large queries to use large amounts
119256 ** of stack space (perhaps causing a stack overflow).
119257 */
119258 #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
119259 # define SQLITE_FTS3_MAX_EXPR_DEPTH 12
119260 #endif
119261
119262
119263 /*
119264 ** This constant controls how often segments are merged. Once there are
119265 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
119266 ** segment of level N+1.
@@ -120709,11 +120915,11 @@
120915 /* By default use a full table scan. This is an expensive option,
120916 ** so search through the constraints to see if a more efficient
120917 ** strategy is possible.
120918 */
120919 pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
120920 pInfo->estimatedCost = 5000000;
120921 for(i=0; i<pInfo->nConstraint; i++){
120922 struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
120923 if( pCons->usable==0 ) continue;
120924
120925 /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
@@ -122270,15 +122476,11 @@
122476 );
122477 if( rc!=SQLITE_OK ){
122478 return rc;
122479 }
122480
 
 
 
122481 rc = fts3EvalStart(pCsr);
 
122482 sqlite3Fts3SegmentsClose(p);
122483 if( rc!=SQLITE_OK ) return rc;
122484 pCsr->pNextId = pCsr->aDoclist;
122485 pCsr->iPrevId = 0;
122486 }
@@ -126129,30 +126331,30 @@
126331 int iDefaultCol, /* Default column to query */
126332 const char *z, int n, /* Text of MATCH query */
126333 Fts3Expr **ppExpr, /* OUT: Parsed query structure */
126334 char **pzErr /* OUT: Error message (sqlite3_malloc) */
126335 ){
 
126336 int rc = fts3ExprParseUnbalanced(
126337 pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
126338 );
126339
126340 /* Rebalance the expression. And check that its depth does not exceed
126341 ** SQLITE_FTS3_MAX_EXPR_DEPTH. */
126342 if( rc==SQLITE_OK && *ppExpr ){
126343 rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
126344 if( rc==SQLITE_OK ){
126345 rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
126346 }
126347 }
126348
126349 if( rc!=SQLITE_OK ){
126350 sqlite3Fts3ExprFree(*ppExpr);
126351 *ppExpr = 0;
126352 if( rc==SQLITE_TOOBIG ){
126353 *pzErr = sqlite3_mprintf(
126354 "FTS expression tree is too large (maximum depth %d)",
126355 SQLITE_FTS3_MAX_EXPR_DEPTH
126356 );
126357 rc = SQLITE_ERROR;
126358 }else if( rc==SQLITE_ERROR ){
126359 *pzErr = sqlite3_mprintf("malformed MATCH expression: [%s]", z);
126360 }
@@ -129110,41 +129312,34 @@
129312 *pRC = rc;
129313 }
129314
129315
129316 /*
129317 ** This function ensures that the caller has obtained an exclusive
129318 ** shared-cache table-lock on the %_segdir table. This is required before
129319 ** writing data to the fts3 table. If this lock is not acquired first, then
129320 ** the caller may end up attempting to take this lock as part of committing
129321 ** a transaction, causing SQLite to return SQLITE_LOCKED or
129322 ** LOCKED_SHAREDCACHEto a COMMIT command.
129323 **
129324 ** It is best to avoid this because if FTS3 returns any error when
129325 ** committing a transaction, the whole transaction will be rolled back.
129326 ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
129327 ** It can still happen if the user locks the underlying tables directly
129328 ** instead of accessing them via FTS.
129329 */
129330 static int fts3Writelock(Fts3Table *p){
129331 int rc = SQLITE_OK;
129332
129333 if( p->nPendingData==0 ){
129334 sqlite3_stmt *pStmt;
129335 rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
 
 
 
 
 
129336 if( rc==SQLITE_OK ){
129337 sqlite3_bind_null(pStmt, 1);
129338 sqlite3_step(pStmt);
129339 rc = sqlite3_reset(pStmt);
129340 }
 
 
129341 }
129342
129343 return rc;
129344 }
129345
@@ -133918,10 +134113,13 @@
134113 goto update_out;
134114 }
134115 aSzIns = &aSzDel[p->nColumn+1];
134116 memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
134117
134118 rc = fts3Writelock(p);
134119 if( rc!=SQLITE_OK ) goto update_out;
134120
134121 /* If this is an INSERT operation, or an UPDATE that modifies the rowid
134122 ** value, then this operation requires constraint handling.
134123 **
134124 ** If the on-conflict mode is REPLACE, this means that the existing row
134125 ** should be deleted from the database before inserting the new row. Or,
@@ -136051,32 +136249,31 @@
136249 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
136250 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
136251 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
136252 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
136253 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
136254 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
136255 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
136256 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
136257 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
136258 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
136259 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
136260 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
136261 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
136262 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
136263 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
136264 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
136265 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
136266 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
136267 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
136268 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
136269 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
136270 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
136271 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
136272 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
136273 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
136274 0x380400F0,
 
136275 };
136276 static const unsigned int aAscii[4] = {
136277 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
136278 };
136279
@@ -139705,11 +139902,11 @@
139902 ** operator) using the ICU uregex_XX() APIs.
139903 **
139904 ** * Implementations of the SQL scalar upper() and lower() functions
139905 ** for case mapping.
139906 **
139907 ** * Integration of ICU and SQLite collation sequences.
139908 **
139909 ** * An implementation of the LIKE operator that uses ICU to
139910 ** provide case-independent matching.
139911 */
139912
139913
+11 -1
--- src/sqlite3.h
+++ src/sqlite3.h
@@ -107,11 +107,11 @@
107107
** [sqlite3_libversion_number()], [sqlite3_sourceid()],
108108
** [sqlite_version()] and [sqlite_source_id()].
109109
*/
110110
#define SQLITE_VERSION "3.7.17"
111111
#define SQLITE_VERSION_NUMBER 3007017
112
-#define SQLITE_SOURCE_ID "2013-05-15 18:34:17 00231fb0127960d700de3549e34e82f8ec1b5819"
112
+#define SQLITE_SOURCE_ID "2013-06-19 23:48:35 bf5764067ab848e19e5971cbdf892c633495e325"
113113
114114
/*
115115
** CAPI3REF: Run-Time Library Version Numbers
116116
** KEYWORDS: sqlite3_version, sqlite3_sourceid
117117
**
@@ -4516,10 +4516,15 @@
45164516
*/
45174517
SQLITE_API int sqlite3_key(
45184518
sqlite3 *db, /* Database to be rekeyed */
45194519
const void *pKey, int nKey /* The key */
45204520
);
4521
+SQLITE_API int sqlite3_key_v2(
4522
+ sqlite3 *db, /* Database to be rekeyed */
4523
+ const char *zDbName, /* Name of the database */
4524
+ const void *pKey, int nKey /* The key */
4525
+);
45214526
45224527
/*
45234528
** Change the key on an open database. If the current database is not
45244529
** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
45254530
** database is decrypted.
@@ -4529,10 +4534,15 @@
45294534
*/
45304535
SQLITE_API int sqlite3_rekey(
45314536
sqlite3 *db, /* Database to be rekeyed */
45324537
const void *pKey, int nKey /* The new key */
45334538
);
4539
+SQLITE_API int sqlite3_rekey_v2(
4540
+ sqlite3 *db, /* Database to be rekeyed */
4541
+ const char *zDbName, /* Name of the database */
4542
+ const void *pKey, int nKey /* The new key */
4543
+);
45344544
45354545
/*
45364546
** Specify the activation key for a SEE database. Unless
45374547
** activated, none of the SEE routines will work.
45384548
*/
45394549
--- src/sqlite3.h
+++ src/sqlite3.h
@@ -107,11 +107,11 @@
107 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
108 ** [sqlite_version()] and [sqlite_source_id()].
109 */
110 #define SQLITE_VERSION "3.7.17"
111 #define SQLITE_VERSION_NUMBER 3007017
112 #define SQLITE_SOURCE_ID "2013-05-15 18:34:17 00231fb0127960d700de3549e34e82f8ec1b5819"
113
114 /*
115 ** CAPI3REF: Run-Time Library Version Numbers
116 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
117 **
@@ -4516,10 +4516,15 @@
4516 */
4517 SQLITE_API int sqlite3_key(
4518 sqlite3 *db, /* Database to be rekeyed */
4519 const void *pKey, int nKey /* The key */
4520 );
 
 
 
 
 
4521
4522 /*
4523 ** Change the key on an open database. If the current database is not
4524 ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
4525 ** database is decrypted.
@@ -4529,10 +4534,15 @@
4529 */
4530 SQLITE_API int sqlite3_rekey(
4531 sqlite3 *db, /* Database to be rekeyed */
4532 const void *pKey, int nKey /* The new key */
4533 );
 
 
 
 
 
4534
4535 /*
4536 ** Specify the activation key for a SEE database. Unless
4537 ** activated, none of the SEE routines will work.
4538 */
4539
--- src/sqlite3.h
+++ src/sqlite3.h
@@ -107,11 +107,11 @@
107 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
108 ** [sqlite_version()] and [sqlite_source_id()].
109 */
110 #define SQLITE_VERSION "3.7.17"
111 #define SQLITE_VERSION_NUMBER 3007017
112 #define SQLITE_SOURCE_ID "2013-06-19 23:48:35 bf5764067ab848e19e5971cbdf892c633495e325"
113
114 /*
115 ** CAPI3REF: Run-Time Library Version Numbers
116 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
117 **
@@ -4516,10 +4516,15 @@
4516 */
4517 SQLITE_API int sqlite3_key(
4518 sqlite3 *db, /* Database to be rekeyed */
4519 const void *pKey, int nKey /* The key */
4520 );
4521 SQLITE_API int sqlite3_key_v2(
4522 sqlite3 *db, /* Database to be rekeyed */
4523 const char *zDbName, /* Name of the database */
4524 const void *pKey, int nKey /* The key */
4525 );
4526
4527 /*
4528 ** Change the key on an open database. If the current database is not
4529 ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
4530 ** database is decrypted.
@@ -4529,10 +4534,15 @@
4534 */
4535 SQLITE_API int sqlite3_rekey(
4536 sqlite3 *db, /* Database to be rekeyed */
4537 const void *pKey, int nKey /* The new key */
4538 );
4539 SQLITE_API int sqlite3_rekey_v2(
4540 sqlite3 *db, /* Database to be rekeyed */
4541 const char *zDbName, /* Name of the database */
4542 const void *pKey, int nKey /* The new key */
4543 );
4544
4545 /*
4546 ** Specify the activation key for a SEE database. Unless
4547 ** activated, none of the SEE routines will work.
4548 */
4549
+2 -2
--- src/timeline.c
+++ src/timeline.c
@@ -1232,17 +1232,17 @@
12321232
** branch to be included in the report. This related check-ins are
12331233
** useful in helping to visualize what has happened on a quiescent
12341234
** branch that is infrequently merged with a much more activate branch.
12351235
*/
12361236
blob_appendf(&sql,
1237
- " OR EXISTS(SELECT 1 FROM plink JOIN tagxref ON rid=cid"
1237
+ " OR EXISTS(SELECT 1 FROM plink CROSS JOIN tagxref ON rid=cid"
12381238
" WHERE tagid=%d AND tagtype>0 AND pid=blob.rid)",
12391239
tagid
12401240
);
12411241
if( P("mionly")==0 ){
12421242
blob_appendf(&sql,
1243
- " OR EXISTS(SELECT 1 FROM plink JOIN tagxref ON rid=pid"
1243
+ " OR EXISTS(SELECT 1 FROM plink CROSS JOIN tagxref ON rid=pid"
12441244
" WHERE tagid=%d AND tagtype>0 AND cid=blob.rid)",
12451245
tagid
12461246
);
12471247
}else{
12481248
url_add_parameter(&url, "mionly", "1");
12491249
--- src/timeline.c
+++ src/timeline.c
@@ -1232,17 +1232,17 @@
1232 ** branch to be included in the report. This related check-ins are
1233 ** useful in helping to visualize what has happened on a quiescent
1234 ** branch that is infrequently merged with a much more activate branch.
1235 */
1236 blob_appendf(&sql,
1237 " OR EXISTS(SELECT 1 FROM plink JOIN tagxref ON rid=cid"
1238 " WHERE tagid=%d AND tagtype>0 AND pid=blob.rid)",
1239 tagid
1240 );
1241 if( P("mionly")==0 ){
1242 blob_appendf(&sql,
1243 " OR EXISTS(SELECT 1 FROM plink JOIN tagxref ON rid=pid"
1244 " WHERE tagid=%d AND tagtype>0 AND cid=blob.rid)",
1245 tagid
1246 );
1247 }else{
1248 url_add_parameter(&url, "mionly", "1");
1249
--- src/timeline.c
+++ src/timeline.c
@@ -1232,17 +1232,17 @@
1232 ** branch to be included in the report. This related check-ins are
1233 ** useful in helping to visualize what has happened on a quiescent
1234 ** branch that is infrequently merged with a much more activate branch.
1235 */
1236 blob_appendf(&sql,
1237 " OR EXISTS(SELECT 1 FROM plink CROSS JOIN tagxref ON rid=cid"
1238 " WHERE tagid=%d AND tagtype>0 AND pid=blob.rid)",
1239 tagid
1240 );
1241 if( P("mionly")==0 ){
1242 blob_appendf(&sql,
1243 " OR EXISTS(SELECT 1 FROM plink CROSS JOIN tagxref ON rid=pid"
1244 " WHERE tagid=%d AND tagtype>0 AND cid=blob.rid)",
1245 tagid
1246 );
1247 }else{
1248 url_add_parameter(&url, "mionly", "1");
1249
--- www/mkdownload.tcl
+++ www/mkdownload.tcl
@@ -8,11 +8,11 @@
88
fconfigure $out -encoding utf-8 -translation lf
99
puts $out \
1010
{<!DOCTYPE html><html>
1111
<head>
1212
<base href="http://www.fossil-scm.org/" />
13
-<title>Fossil: Timeline</title>
13
+<title>Fossil: Downloads</title>
1414
<link rel="stylesheet" href="/fossil/style.css" type="text/css"
1515
media="screen">
1616
</head>
1717
<body>
1818
<div class="header">
1919
--- www/mkdownload.tcl
+++ www/mkdownload.tcl
@@ -8,11 +8,11 @@
8 fconfigure $out -encoding utf-8 -translation lf
9 puts $out \
10 {<!DOCTYPE html><html>
11 <head>
12 <base href="http://www.fossil-scm.org/" />
13 <title>Fossil: Timeline</title>
14 <link rel="stylesheet" href="/fossil/style.css" type="text/css"
15 media="screen">
16 </head>
17 <body>
18 <div class="header">
19
--- www/mkdownload.tcl
+++ www/mkdownload.tcl
@@ -8,11 +8,11 @@
8 fconfigure $out -encoding utf-8 -translation lf
9 puts $out \
10 {<!DOCTYPE html><html>
11 <head>
12 <base href="http://www.fossil-scm.org/" />
13 <title>Fossil: Downloads</title>
14 <link rel="stylesheet" href="/fossil/style.css" type="text/css"
15 media="screen">
16 </head>
17 <body>
18 <div class="header">
19

Keyboard Shortcuts

Open search /
Next entry (timeline) j
Previous entry (timeline) k
Open focused entry Enter
Show this help ?
Toggle theme Top nav button